Skip to content

chore(backend,express): Introduce treatPendingAsSignedOut option to getAuth #5842

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/flat-papers-begin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@clerk/backend': minor
'@clerk/express': minor
---

Introduce `treatPendingAsSignedOut` option to `getAuth`

```ts
// `pending` sessions will be treated as signed-out by default
const { userId } = getAuth(req)
```

```ts
// Both `active` and `pending` sessions will be treated as authenticated when `treatPendingAsSignedOut` is false
const { userId } = getAuth(req, { treatPendingAsSignedOut: false })
```
10 changes: 7 additions & 3 deletions packages/backend/src/tokens/authObjects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
JwtPayload,
ServerGetToken,
ServerGetTokenOptions,
SessionStatusClaim,
SharedSignedInAuthObjectProperties,
} from '@clerk/types';

Expand Down Expand Up @@ -37,7 +38,7 @@ export type SignedInAuthObject = SharedSignedInAuthObjectProperties & {
export type SignedOutAuthObject = {
sessionClaims: null;
sessionId: null;
sessionStatus: null;
sessionStatus: SessionStatusClaim | null;
actor: null;
userId: null;
orgId: null;
Expand Down Expand Up @@ -113,11 +114,14 @@ export function signedInAuthObject(
/**
* @internal
*/
export function signedOutAuthObject(debugData?: AuthObjectDebugData): SignedOutAuthObject {
export function signedOutAuthObject(
debugData?: AuthObjectDebugData,
initialSessionStatus?: SessionStatusClaim,
): SignedOutAuthObject {
return {
sessionClaims: null,
sessionId: null,
sessionStatus: null,
sessionStatus: initialSessionStatus ?? null,
userId: null,
actor: null,
orgId: null,
Expand Down
13 changes: 10 additions & 3 deletions packages/backend/src/tokens/authStatus.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { JwtPayload } from '@clerk/types';
import type { JwtPayload, PendingSessionOptions } from '@clerk/types';

import { constants } from '../constants';
import type { TokenVerificationErrorReason } from '../errors';
Expand Down Expand Up @@ -27,7 +27,7 @@ export type SignedInState = {
afterSignInUrl: string;
afterSignUpUrl: string;
isSignedIn: true;
toAuth: () => SignedInAuthObject;
toAuth: (opts?: PendingSessionOptions) => SignedInAuthObject;
headers: Headers;
token: string;
};
Expand Down Expand Up @@ -99,7 +99,14 @@ export function signedIn(
afterSignInUrl: authenticateContext.afterSignInUrl || '',
afterSignUpUrl: authenticateContext.afterSignUpUrl || '',
isSignedIn: true,
toAuth: () => authObject,
// @ts-expect-error The return type is intentionally overridden here to support consumer-facing logic that treats pending sessions as signed out. This override does not affect internal session management like handshake flows.
toAuth: ({ treatPendingAsSignedOut = true } = {}) => {
if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {
return signedOutAuthObject(undefined, authObject.sessionStatus);
}

return authObject;
},
headers,
token,
};
Expand Down
4 changes: 2 additions & 2 deletions packages/express/src/__tests__/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function mockRequest(): ExpressRequest {

export function mockRequestWithAuth(auth: Partial<AuthObject> = {}): ExpressRequestWithAuth {
return {
auth: {
auth: () => ({
sessionClaims: null,
sessionId: null,
actor: null,
Expand All @@ -41,7 +41,7 @@ export function mockRequestWithAuth(auth: Partial<AuthObject> = {}): ExpressRequ
has: () => false,
debug: () => ({}),
...auth,
},
}),
} as unknown as ExpressRequestWithAuth;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/express/src/__tests__/requireAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ describe('requireAuth', () => {
return next();
}
const requestState = mockAuthenticateRequest({ request: req });
Object.assign(req, { auth: requestState.toAuth() });
Object.assign(req, { auth: () => requestState.toAuth() });
next();
};
});
Expand Down
2 changes: 1 addition & 1 deletion packages/express/src/authenticateRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export const authenticateAndDecorateRequest = (options: ClerkMiddlewareOptions =
}
}

const auth = requestState.toAuth();
const auth = (opts: Parameters<typeof requestState.toAuth>[0]) => requestState.toAuth(opts);
Object.assign(request, { auth });

next();
Expand Down
8 changes: 6 additions & 2 deletions packages/express/src/getAuth.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
import type { AuthObject } from '@clerk/backend';
import type { PendingSessionOptions } from '@clerk/types';
import type { Request as ExpressRequest } from 'express';

import { middlewareRequired } from './errors';
import { requestHasAuthObject } from './utils';

type GetAuthOptions = PendingSessionOptions;

/**
* Retrieves the Clerk AuthObject using the current request object.
*
* @param {ExpressRequest} req - The current request object.
* @param {GetAuthOptions} options - Optional configuration for retriving auth object.
* @returns {AuthObject} Object with information about the request state and claims.
* @throws {Error} `clerkMiddleware` or `requireAuth` is required to be set in the middleware chain before this util is used.
*/
export const getAuth = (req: ExpressRequest): AuthObject => {
export const getAuth = (req: ExpressRequest, options?: GetAuthOptions): AuthObject => {
if (!requestHasAuthObject(req)) {
throw new Error(middlewareRequired('getAuth'));
}

return req.auth;
return req.auth(options);
};
2 changes: 1 addition & 1 deletion packages/express/src/requireAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const requireAuth = (options: ClerkMiddlewareOptions = {}): RequestHandle

const signInUrl = options.signInUrl || process.env.CLERK_SIGN_IN_URL || '/';

if (!(request as ExpressRequestWithAuth).auth?.userId) {
if (!(request as ExpressRequestWithAuth).auth()?.userId) {
return response.redirect(signInUrl);
}

Expand Down
3 changes: 2 additions & 1 deletion packages/express/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { AuthObject, createClerkClient } from '@clerk/backend';
import type { AuthenticateRequestOptions } from '@clerk/backend/internal';
import type { PendingSessionOptions } from '@clerk/types';
import type { Request as ExpressRequest } from 'express';

export type ExpressRequestWithAuth = ExpressRequest & { auth: AuthObject };
export type ExpressRequestWithAuth = ExpressRequest & { auth: (options?: PendingSessionOptions) => AuthObject };

export type ClerkMiddlewareOptions = AuthenticateRequestOptions & {
debug?: boolean;
Expand Down