-
Notifications
You must be signed in to change notification settings - Fork 36
/
auth.worker.ts
68 lines (56 loc) · 1.8 KB
/
auth.worker.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
import { IdbStorage, type AuthClient } from "@dfinity/auth-client";
import { isDelegationValid } from "@dfinity/authentication";
import { DelegationChain } from "@dfinity/identity";
import { createAuthClient } from "../utils/auth.utils";
let timer: NodeJS.Timeout | undefined = undefined;
/**
* The timer is executed only if user has signed in
*/
export const startIdleTimer = () =>
(timer = setInterval(async () => await onIdleSignOut(), 1000));
export const stopIdleTimer = () => {
if (!timer) {
return;
}
clearInterval(timer);
timer = undefined;
};
const onIdleSignOut = async () => {
const [auth, delegation] = await Promise.all([
checkAuthentication(),
checkDelegationChain(),
]);
// Both identity and delegation are alright, so all good
if (auth && delegation) {
return;
}
logout();
};
/**
* If user is not authenticated - i.e. no identity or anonymous and there is no valid delegation chain, then identity is not valid
*
* @returns true if authenticated
*/
const checkAuthentication = async (): Promise<boolean> => {
const authClient: AuthClient = await createAuthClient();
return authClient.isAuthenticated();
};
/**
* If there is no delegation or if not valid, then delegation is not valid
*
* @returns true if delegation is valid
*/
const checkDelegationChain = async (): Promise<boolean> => {
const idbStorage: IdbStorage = new IdbStorage();
const delegationChain: string | null = await idbStorage.get("delegation");
return (
delegationChain !== null &&
isDelegationValid(DelegationChain.fromJSON(delegationChain))
);
};
// We do the logout on the client side because we reload the window to reload stores afterwards
const logout = () => {
// Clear timer to not emit sign-out multiple times
stopIdleTimer();
postMessage({ msg: "nnsSignOut" });
};