forked from clerk/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateGetAuth.ts
More file actions
69 lines (58 loc) · 2.43 KB
/
Copy pathcreateGetAuth.ts
File metadata and controls
69 lines (58 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import type { AuthObject } from '@clerk/backend/internal';
import { AuthStatus, constants, signedInAuthObject, signedOutAuthObject } from '@clerk/backend/internal';
import { decodeJwt } from '@clerk/backend/jwt';
import { withLogger } from '../utils/debugLogger';
import { API_URL, API_VERSION, SECRET_KEY } from './constants';
import { getAuthAuthHeaderMissing } from './errors';
import type { RequestLike } from './types';
import { getAuthKeyFromRequest, getCookie, getHeader } from './utils';
export const createGetAuth = ({
noAuthStatusMessage,
debugLoggerName,
}: {
debugLoggerName: string;
noAuthStatusMessage: string;
}) =>
withLogger(debugLoggerName, logger => {
return (req: RequestLike, opts?: { secretKey?: string }): AuthObject => {
if (getHeader(req, constants.Headers.EnableDebug) === 'true') {
logger.enable();
}
// When the auth status is set, we trust that the middleware has already run
// Then, we don't have to re-verify the JWT here,
// we can just strip out the claims manually.
const authToken = getAuthKeyFromRequest(req, 'AuthToken');
const authMessage = getAuthKeyFromRequest(req, 'AuthMessage');
const authReason = getAuthKeyFromRequest(req, 'AuthReason');
const authStatus = getAuthKeyFromRequest(req, 'AuthStatus') as AuthStatus;
logger.debug('Headers debug', { authStatus, authMessage, authReason });
if (!authStatus) {
throw new Error(noAuthStatusMessage);
}
const options = {
authStatus,
apiUrl: API_URL,
apiVersion: API_VERSION,
authMessage,
secretKey: opts?.secretKey || SECRET_KEY,
authReason,
};
logger.debug('Options debug', options);
if (authStatus === AuthStatus.SignedIn) {
const jwt = decodeJwt(authToken as string);
logger.debug('JWT debug', jwt.raw.text);
// @ts-expect-error - TODO @nikos: Align types
return signedInAuthObject({ ...options, sessionToken: jwt.raw.text }, jwt.payload);
}
return signedOutAuthObject(options);
};
});
export const getAuth = createGetAuth({
debugLoggerName: 'getAuth()',
noAuthStatusMessage: getAuthAuthHeaderMissing(),
});
export const parseJwt = (req: RequestLike) => {
const cookieToken = getCookie(req, constants.Cookies.Session);
const headerToken = getHeader(req, 'authorization')?.replace('Bearer ', '');
return decodeJwt(cookieToken || headerToken || '');
};