-
Notifications
You must be signed in to change notification settings - Fork 7
/
sdk.ts
81 lines (66 loc) · 2.16 KB
/
sdk.ts
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
70
71
72
73
74
75
76
77
78
79
80
81
// workaround for TS issue https://github.com/microsoft/TypeScript/issues/42873
// eslint-disable-next-line
import type * as _1 from '@descope/core-js-sdk';
import createSdk from '@descope/web-js-sdk';
import { IS_BROWSER } from './constants';
import { wrapInTry } from './utils';
type Sdk = ReturnType<typeof createSdkWrapper>;
let globalSdk: Sdk;
const createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(
config: P,
) => {
const sdk = createSdk({
persistTokens: IS_BROWSER as true,
autoRefresh: IS_BROWSER as true,
...config,
});
globalSdk = sdk;
return sdk;
};
// eslint-disable-next-line import/exports-last
export const createTempSdk = () =>
createSdkWrapper({
projectId: 'temp pid',
persistTokens: false,
autoRefresh: false,
storeLastAuthenticatedUser: false,
});
/**
* We want to make sure the getSessionToken fn is used only when persistTokens is on
*
* So we are keeping the SDK init in a single place,
* and we are creating a temp instance in order to export the getSessionToken
* even before the SDK was init
*/
globalSdk = createTempSdk();
export const getSessionToken = () => {
if (IS_BROWSER) {
return globalSdk?.getSessionToken();
}
// eslint-disable-next-line no-console
console.warn('Get session token is not supported in SSR');
return '';
};
export const getRefreshToken = () => {
if (IS_BROWSER) {
return globalSdk?.getRefreshToken();
}
// eslint-disable-next-line no-console
console.warn('Get refresh token is not supported in SSR');
return '';
};
export const isSessionTokenExpired = (token = getSessionToken()) =>
globalSdk?.isJwtExpired(token);
export const isRefreshTokenExpired = (token = getRefreshToken()) =>
globalSdk?.isJwtExpired(token);
export const getJwtPermissions = wrapInTry(
(token = getSessionToken(), tenant?: string) =>
globalSdk?.getJwtPermissions(token, tenant),
);
export const getJwtRoles = wrapInTry(
(token = getSessionToken(), tenant?: string) =>
globalSdk?.getJwtRoles(token, tenant),
);
export const refresh = (token = getRefreshToken()) => globalSdk?.refresh(token);
export const getGlobalSdk = () => globalSdk;
export default createSdkWrapper;