-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSaleorRefreshTokenStorageHandler.ts
71 lines (57 loc) · 2.21 KB
/
SaleorRefreshTokenStorageHandler.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
import type { StorageRepository } from "./types";
/* auth state when user signs in / out */
export const getStorageAuthEventKey = (prefix?: string) =>
[prefix, "saleor_storage_auth_change"].filter(Boolean).join("+");
export const getStorageAuthStateKey = (prefix?: string) =>
[prefix, "saleor_auth_module_auth_state"].filter(Boolean).join("+");
export const getRefreshTokenKey = (prefix?: string) =>
[prefix, "saleor_auth_module_refresh_token"].filter(Boolean).join("+");
export type AuthState = "signedIn" | "signedOut";
export type SaleorAuthEvent = CustomEvent<{ authState: AuthState }>;
export class SaleorRefreshTokenStorageHandler {
constructor(
private storage: StorageRepository,
private prefix?: string,
) {
if (typeof window !== "undefined") {
window.addEventListener("storage", this.handleStorageChange);
}
}
private handleStorageChange = (event: StorageEvent) => {
const { oldValue, newValue, type, key } = event;
if (oldValue === newValue || type !== "storage" || key !== getStorageAuthStateKey(this.prefix)) {
return;
}
this.sendAuthStateEvent(newValue as AuthState);
};
cleanup = () => {
if (typeof window !== "undefined") {
window.removeEventListener("storage", this.handleStorageChange);
}
};
/* auth state */
sendAuthStateEvent = (authState: AuthState) => {
if (typeof window !== "undefined") {
const event = new CustomEvent(getStorageAuthEventKey(this.prefix), {
detail: { authState },
});
window.dispatchEvent(event);
}
};
getAuthState = (): AuthState =>
(this.storage.getItem(getStorageAuthStateKey(this.prefix)) as AuthState | undefined) || "signedOut";
setAuthState = (authState: AuthState) => {
this.storage.setItem(getStorageAuthStateKey(this.prefix), authState);
this.sendAuthStateEvent(authState);
};
/* refresh token */
getRefreshToken = () => this.storage.getItem(getRefreshTokenKey(this.prefix)) || null;
setRefreshToken = (token: string) => {
this.storage.setItem(getRefreshTokenKey(this.prefix), token);
};
/* performed on logout */
clearAuthStorage = () => {
this.setAuthState("signedOut");
this.storage.removeItem(getRefreshTokenKey(this.prefix));
};
}