Skip to content

Commit

Permalink
Add getSession (#91)
Browse files Browse the repository at this point in the history
* Add getSession

* Update wording

* Fixed bug where getSession wouldn't return a session after a refresh
  • Loading branch information
Paul Asjes authored Sep 26, 2024
1 parent 57d00da commit 41a2dbe
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 4 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,30 @@ In the above example the `/admin` page will require a user to be signed in, wher
`unauthenticatedPaths` uses the same glob logic as the [Next.js matcher](https://nextjs.org/docs/pages/building-your-application/routing/middleware#matcher).
### Retrieve session in middleware
Sometimes it's useful to check the user session if you want to compose custom middleware. The `getSession` helper method will retrieve the session from the cookie and verify the access token.
```ts
import { authkitMiddleware, getSession } from '@workos-inc/authkit-nextjs';
import { NextRequest } from 'next/server';
export default async function middleware(request: NextRequest) {
// authkitMiddleware will handle refreshing the session if the access token has expired
const response = await authkitMiddleware()(request);
// If session is undefined, the user is not authenticated
const session = await getSession(response);
// ...add additional middleware logic here
return response;
}
// Match against pages that require auth
export const config = { matcher: ['/', '/account/:path*'] };
```
### Signing out
Use the `signOut` method to sign out the current logged in user and redirect to your app's homepage. The homepage redirect is set in your WorkOS dashboard settings under "Redirect".
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { handleAuth } from './authkit-callback-route.js';
import { authkitMiddleware } from './middleware.js';
import { getUser, refreshSession } from './session.js';
import { getUser, refreshSession, getSession } from './session.js';
import { getSignInUrl, getSignUpUrl, signOut } from './auth.js';
import { Impersonation } from './impersonation.js';
import { AuthKitProvider } from './provider.js';
Expand All @@ -9,6 +9,7 @@ export {
handleAuth,
//
authkitMiddleware,
getSession,
//
getSignInUrl,
getSignUpUrl,
Expand Down
31 changes: 28 additions & 3 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,15 +239,40 @@ async function verifyAccessToken(accessToken: string) {
}
}

async function getSessionFromCookie() {
const cookie = cookies().get(cookieName);
async function getSessionFromCookie(response?: NextResponse) {
const cookie = response ? response.cookies.get(cookieName) : cookies().get(cookieName);
if (cookie) {
return unsealData<Session>(cookie.value, {
password: WORKOS_COOKIE_PASSWORD,
});
}
}

/**
* Retrieves the session from the cookie. Meant for use in the middleware, for client side use `getUser` instead.
*
* @returns Session | undefined
*/
async function getSession(response?: NextResponse) {
const session = await getSessionFromCookie(response);

if (!session) return;

if (await verifyAccessToken(session.accessToken)) {
const { sid: sessionId, org_id: organizationId, role, permissions } = decodeJwt<AccessToken>(session.accessToken);

return {
sessionId,
user: session.user,
organizationId,
role,
permissions,
impersonator: session.impersonator,
accessToken: session.accessToken,
};
}
}

async function getSessionFromHeader(caller: string): Promise<Session | undefined> {
const hasMiddleware = Boolean(headers().get(middlewareHeaderName));

Expand All @@ -269,4 +294,4 @@ function getReturnPathname(url: string): string {
return `${newUrl.pathname}${newUrl.searchParams.size > 0 ? '?' + newUrl.searchParams.toString() : ''}`;
}

export { encryptSession, getUser, refreshSession, terminateSession, updateSession };
export { encryptSession, getUser, refreshSession, terminateSession, updateSession, getSession };

0 comments on commit 41a2dbe

Please sign in to comment.