-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.ts
193 lines (172 loc) · 8.15 KB
/
index.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* You may not use this file except in compliance with the License. You may
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import AuthHttpRequestFetch, { getTokenForHeaderAuth } from "./fetch";
import { ClaimValidationError, InputType, RecipeInterface, SessionClaim, SessionClaimValidator } from "./types";
import RecipeImplementation from "./recipeImplementation";
import OverrideableBuilder from "supertokens-js-override";
import { getNormalisedUserContext, validateAndNormaliseInputOrThrowError } from "./utils";
import CookieHandlerReference from "./utils/cookieHandler";
import WindowHandlerReference from "./utils/windowHandler";
import LockFactoryReference from "./utils/lockFactory";
import { SessionClaimValidatorStore } from "./utils/sessionClaimValidatorStore";
import { enableLogging } from "./logger";
import DateProviderReference from "./utils/dateProvider";
export default class AuthHttpRequest {
private static axiosInterceptorQueue: (() => void)[] = [];
static init(options: InputType) {
CookieHandlerReference.init(options.cookieHandler);
WindowHandlerReference.init(options.windowHandler);
DateProviderReference.init(options.dateProvider);
LockFactoryReference.init(
options.lockFactory,
WindowHandlerReference.getReferenceOrThrow().windowHandler.localStorage
);
let config = validateAndNormaliseInputOrThrowError(options);
if (options.enableDebugLogs !== undefined && options.enableDebugLogs) {
enableLogging();
}
const recipeImpl = new OverrideableBuilder(
RecipeImplementation({
onHandleEvent: config.onHandleEvent,
preAPIHook: config.preAPIHook,
postAPIHook: config.postAPIHook,
sessionExpiredStatusCode: config.sessionExpiredStatusCode
})
)
.override(config.override.functions)
.build();
AuthHttpRequestFetch.init(config, recipeImpl);
AuthHttpRequest.axiosInterceptorQueue.forEach(f => {
f();
});
AuthHttpRequest.axiosInterceptorQueue = [];
}
static getUserId(input?: { userContext?: any }): Promise<string> {
return AuthHttpRequestFetch.recipeImpl.getUserId({
userContext: getNormalisedUserContext(input === undefined ? undefined : input.userContext)
});
}
static async getAccessTokenPayloadSecurely(input?: { userContext?: any }): Promise<any> {
return AuthHttpRequestFetch.recipeImpl.getAccessTokenPayloadSecurely({
userContext: getNormalisedUserContext(input === undefined ? undefined : input.userContext)
});
}
static attemptRefreshingSession = async (): Promise<boolean> => {
return AuthHttpRequestFetch.attemptRefreshingSession();
};
static doesSessionExist = (input?: { userContext?: any }) => {
return AuthHttpRequestFetch.recipeImpl.doesSessionExist({
userContext: getNormalisedUserContext(input === undefined ? undefined : input.userContext)
});
};
/**
* @deprecated
*/
static addAxiosInterceptors = (axiosInstance: any, userContext?: any) => {
if (!AuthHttpRequestFetch.initCalled) {
// the recipe implementation has not been initialised yet, so add
// this to the queue and wait for it to be initialised, and then on
// init call, we add all the interceptors.
AuthHttpRequest.axiosInterceptorQueue.push(() => {
AuthHttpRequestFetch.recipeImpl.addAxiosInterceptors({
axiosInstance,
userContext: getNormalisedUserContext(userContext)
});
});
} else {
AuthHttpRequestFetch.recipeImpl.addAxiosInterceptors({
axiosInstance,
userContext: getNormalisedUserContext(userContext)
});
}
};
static signOut = (input?: { userContext?: any }) => {
return AuthHttpRequestFetch.recipeImpl.signOut({
userContext: getNormalisedUserContext(input === undefined ? undefined : input.userContext)
});
};
static getInvalidClaimsFromResponse = async function (input: {
response: { data: any } | Response;
userContext?: any;
}): Promise<ClaimValidationError[]> {
return AuthHttpRequestFetch.recipeImpl.getInvalidClaimsFromResponse({
response: input.response,
userContext: getNormalisedUserContext(input.userContext)
});
};
static getClaimValue = async function <T>(input: {
claim: SessionClaim<T>;
userContext?: any;
}): Promise<T | undefined> {
const userContext = getNormalisedUserContext(input === undefined ? undefined : input.userContext);
const accessTokenPayload = await AuthHttpRequest.getAccessTokenPayloadSecurely({ userContext });
return input.claim.getValueFromPayload(accessTokenPayload, userContext);
};
static validateClaims = (
overrideGlobalClaimValidators?: (
globalClaimValidators: SessionClaimValidator[],
userContext: any
) => SessionClaimValidator[],
userContext?: any
): Promise<ClaimValidationError[]> | ClaimValidationError[] => {
const normalisedUserContext = getNormalisedUserContext(userContext);
const claimValidatorsAddedByOtherRecipes = SessionClaimValidatorStore.getClaimValidatorsAddedByOtherRecipes();
const globalClaimValidators = AuthHttpRequestFetch.recipeImpl.getGlobalClaimValidators({
claimValidatorsAddedByOtherRecipes,
userContext: normalisedUserContext
});
const claimValidators =
overrideGlobalClaimValidators !== undefined
? overrideGlobalClaimValidators(globalClaimValidators, normalisedUserContext)
: globalClaimValidators;
if (claimValidators.length === 0) {
return [];
}
return AuthHttpRequestFetch.recipeImpl.validateClaims({
claimValidators,
userContext: getNormalisedUserContext(userContext)
});
};
static getAccessToken = async (input?: { userContext?: any }): Promise<string | undefined> => {
// This takes care of refreshing the access token if necessary.
if (
await AuthHttpRequestFetch.recipeImpl.doesSessionExist({
userContext: getNormalisedUserContext(input === undefined ? undefined : input.userContext)
})
) {
return getTokenForHeaderAuth("access");
}
return undefined;
};
}
export let init = AuthHttpRequest.init;
export let getUserId = AuthHttpRequest.getUserId;
export let getAccessTokenPayloadSecurely = AuthHttpRequest.getAccessTokenPayloadSecurely;
export let getAccessToken = AuthHttpRequest.getAccessToken;
export let attemptRefreshingSession = AuthHttpRequest.attemptRefreshingSession;
export let doesSessionExist = AuthHttpRequest.doesSessionExist;
/**
* @deprecated
*/
export let addAxiosInterceptors = AuthHttpRequest.addAxiosInterceptors;
export let signOut = AuthHttpRequest.signOut;
export const validateClaims = AuthHttpRequest.validateClaims;
export const getClaimValue = AuthHttpRequest.getClaimValue;
export const getInvalidClaimsFromResponse = AuthHttpRequest.getInvalidClaimsFromResponse;
export { RecipeInterface, InputType };
export { ClaimValidationError, ClaimValidationResult, SessionClaimValidator, SessionClaim } from "./types";
export { PrimitiveClaim } from "./claims/primitiveClaim";
export { PrimitiveArrayClaim } from "./claims/primitiveArrayClaim";
export { BooleanClaim } from "./claims/booleanClaim";