-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSaleorAuthClient.ts
292 lines (244 loc) · 9.08 KB
/
SaleorAuthClient.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import { SaleorRefreshTokenStorageHandler } from "./SaleorRefreshTokenStorageHandler";
import { getRequestData, getTokenIss, isExpiredToken } from "./utils";
import type {
FetchRequestInfo,
FetchWithAdditionalParams,
PasswordResetResponse,
PasswordResetVariables,
StorageRepository,
TokenCreateResponse,
TokenCreateVariables,
TokenRefreshResponse,
} from "./types";
import { invariant } from "./utils";
import { PASSWORD_RESET, TOKEN_CREATE, TOKEN_REFRESH } from "./mutations";
import cookie from "cookie";
import { SaleorAccessTokenStorageHandler } from "./SaleorAccessTokenStorageHandler";
export interface SaleorAuthClientProps {
onAuthRefresh?: (isAuthenticating: boolean) => void;
saleorApiUrl: string;
refreshTokenStorage?: StorageRepository;
accessTokenStorage?: StorageRepository;
tokenGracePeriod?: number;
defaultRequestInit?: RequestInit;
}
export class SaleorAuthClient {
// we'll assume a generous time of 2 seconds for api to
// process our request
private tokenGracePeriod = 2000;
private tokenRefreshPromise: null | Promise<Response> = null;
private onAuthRefresh?: (isAuthenticating: boolean) => void;
private saleorApiUrl: string;
/**
* Persistent storage (for refresh token)
*/
private refreshTokenStorage: SaleorRefreshTokenStorageHandler | null;
/**
* Non-persistent storage for access token
*/
private acessTokenStorage: SaleorAccessTokenStorageHandler;
private defaultRequestInit: RequestInit | undefined;
/**
* Use ths method to clear event listeners from storageHandler
* @example
* ```jsx
* useEffect(() => {
* return () => {
* SaleorAuthClient.cleanup();
* }
* }, [])
* ```
*/
constructor({
saleorApiUrl,
refreshTokenStorage,
accessTokenStorage,
onAuthRefresh,
tokenGracePeriod,
defaultRequestInit,
}: SaleorAuthClientProps) {
this.defaultRequestInit = defaultRequestInit;
if (tokenGracePeriod) {
this.tokenGracePeriod = tokenGracePeriod;
}
this.onAuthRefresh = onAuthRefresh;
this.saleorApiUrl = saleorApiUrl;
const refreshTokenRepo =
refreshTokenStorage ?? (typeof window !== "undefined" ? window.localStorage : undefined);
this.refreshTokenStorage = refreshTokenRepo
? new SaleorRefreshTokenStorageHandler(refreshTokenRepo, saleorApiUrl)
: null;
const accessTokenRepo = accessTokenStorage ?? getInMemoryAccessTokenStorage();
this.acessTokenStorage = new SaleorAccessTokenStorageHandler(accessTokenRepo, saleorApiUrl);
}
cleanup = () => {
this.refreshTokenStorage?.cleanup();
};
private runAuthorizedRequest: FetchWithAdditionalParams = (input, init, additionalParams) => {
// technically we run this only when token is there
// but just to make typescript happy
const token = this.acessTokenStorage.getAccessToken();
if (!token) {
return fetch(input, init);
}
const headers = init?.headers || {};
const getURL = (input: FetchRequestInfo) => {
if (typeof input === "string") {
return input;
} else if ("url" in input) {
return input.url;
} else {
return input.href;
}
};
const iss = getTokenIss(token);
const issuerAndDomainMatch = getURL(input) === iss;
const shouldAddAuthorizationHeader =
issuerAndDomainMatch || additionalParams?.allowPassingTokenToThirdPartyDomains;
if (!issuerAndDomainMatch) {
if (shouldAddAuthorizationHeader) {
console.warn(
"Token's `iss` and request URL do not match but `allowPassingTokenToThirdPartyDomains` was specified.",
);
} else {
console.warn(
"Token's `iss` and request URL do not match. Not adding `Authorization` header to the request.",
);
}
}
return fetch(input, {
...init,
headers: shouldAddAuthorizationHeader ? { ...headers, Authorization: `Bearer ${token}` } : headers,
});
};
private handleRequestWithTokenRefresh: FetchWithAdditionalParams = async (
input,
requestInit,
additionalParams,
) => {
const refreshToken = this.refreshTokenStorage?.getRefreshToken();
invariant(refreshToken, "Missing refresh token in token refresh handler");
const accessToken = this.acessTokenStorage.getAccessToken();
// the refresh already finished, proceed as normal
if (accessToken && !isExpiredToken(accessToken, this.tokenGracePeriod)) {
return this.fetchWithAuth(input, requestInit, additionalParams);
}
this.onAuthRefresh?.(true);
// if the promise is already there, use it
if (this.tokenRefreshPromise) {
const response = await this.tokenRefreshPromise;
const res = (await response.clone().json()) as TokenRefreshResponse;
const {
errors: graphqlErrors,
data: {
tokenRefresh: { errors, token },
},
} = res;
this.onAuthRefresh?.(false);
if (errors?.length || graphqlErrors?.length || !token) {
this.tokenRefreshPromise = null;
this.refreshTokenStorage?.clearAuthStorage();
return fetch(input, requestInit);
}
this.refreshTokenStorage?.setAuthState("signedIn");
this.acessTokenStorage.setAccessToken(token);
this.tokenRefreshPromise = null;
return this.runAuthorizedRequest(input, requestInit, additionalParams);
}
// this is the first failed request, initialize refresh
this.tokenRefreshPromise = fetch(
this.saleorApiUrl,
getRequestData(TOKEN_REFRESH, { refreshToken }, { ...this.defaultRequestInit, ...requestInit }),
);
return this.fetchWithAuth(input, requestInit, additionalParams);
};
private handleSignIn = async <TOperation extends TokenCreateResponse | PasswordResetResponse>(
response: Response,
): Promise<TOperation> => {
const readResponse = (await response.json()) as TOperation;
const responseData =
"tokenCreate" in readResponse.data ? readResponse.data.tokenCreate : readResponse.data.setPassword;
if (!responseData) {
return readResponse;
}
const { errors, token, refreshToken } = responseData;
if (!token || errors.length) {
this.refreshTokenStorage?.setAuthState("signedOut");
return readResponse;
}
if (token) {
this.acessTokenStorage.setAccessToken(token);
}
if (refreshToken) {
this.refreshTokenStorage?.setRefreshToken(refreshToken);
}
this.refreshTokenStorage?.setAuthState("signedIn");
return readResponse;
};
/**
* @param additionalParams
* @param additionalParams.allowPassingTokenToThirdPartyDomains if set to true, the `Authorization` header will be added to the request even if the token's `iss` and request URL do not match
*/
fetchWithAuth: FetchWithAdditionalParams = async (input, init, additionalParams) => {
const refreshToken = this.refreshTokenStorage?.getRefreshToken();
if (!this.acessTokenStorage.getAccessToken() && typeof document !== "undefined") {
// this flow is used by SaleorExternalAuth
const tokenFromCookie = cookie.parse(document.cookie).token ?? null;
if (tokenFromCookie) {
this.acessTokenStorage.setAccessToken(tokenFromCookie);
}
document.cookie = cookie.serialize("token", "", { expires: new Date(0), path: "/" });
}
const accessToken = this.acessTokenStorage.getAccessToken();
// access token is fine, add it to the request and proceed
if (accessToken && !isExpiredToken(accessToken, this.tokenGracePeriod)) {
return this.runAuthorizedRequest(input, init, additionalParams);
}
// refresh token exists, try to authenticate if possible
if (refreshToken) {
return this.handleRequestWithTokenRefresh(input, init, additionalParams);
}
// any regular mutation, no previous sign in, proceed
return fetch(input, init);
};
resetPassword = async (variables: PasswordResetVariables, requestInit?: RequestInit) => {
const response = await fetch(
this.saleorApiUrl,
getRequestData(PASSWORD_RESET, variables, { ...this.defaultRequestInit, ...requestInit }),
);
return this.handleSignIn<PasswordResetResponse>(response);
};
signIn = async (variables: TokenCreateVariables, requestInit?: RequestInit) => {
const response = await fetch(
this.saleorApiUrl,
getRequestData(TOKEN_CREATE, variables, { ...this.defaultRequestInit, ...requestInit }),
);
return this.handleSignIn<TokenCreateResponse>(response);
};
signOut = () => {
this.acessTokenStorage.clearAuthStorage();
this.refreshTokenStorage?.clearAuthStorage();
if (typeof document !== "undefined") {
// this flow is used by SaleorExternalAuth
document.cookie = cookie.serialize("token", "", {
expires: new Date(0),
path: "/",
});
}
};
}
export const createSaleorAuthClient = (props: SaleorAuthClientProps) => new SaleorAuthClient(props);
function getInMemoryAccessTokenStorage(): StorageRepository {
let accessToken: string | null = null;
return {
getItem() {
return accessToken;
},
removeItem() {
return (accessToken = null);
},
setItem(_key, value) {
return (accessToken = value);
},
};
}