/
index.ts
79 lines (70 loc) · 2.35 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
import { AuthClient } from "@dfinity/auth-client";
import { renderIndex } from "./views";
import { renderLoggedIn } from "./views/loggedIn";
import { canisterId, createActor } from "../../declarations/whoami";
import { Actor, Identity } from "@dfinity/agent";
const init = async () => {
const authClient = await AuthClient.create({
/**
* Configure the IdleManager
* By default, after 10 minutes, invalidates the identity and logs out
**/
idleOptions: {
// Set to true if you do not want idle functionality
disableIdle: false,
onIdle: async () => {
await logout();
renderIndex("You have been logged out due to inactivity");
},
},
});
const logout = async () => await authClient.logout();
if (await authClient.isAuthenticated()) {
handleAuthenticated(authClient);
}
renderIndex();
setupToast();
const loginButton = document.getElementById(
"loginButton"
) as HTMLButtonElement;
const days = BigInt(1);
const hours = BigInt(24);
const nanoseconds = BigInt(3600000000000);
loginButton.onclick = () => {
authClient.login({
onSuccess: async () => {
handleAuthenticated(authClient);
},
identityProvider:
process.env.DFX_NETWORK === "ic"
? "https://identity.ic0.app/#authorize"
: `http://localhost:${process.env.REPLICA_PORT}?canisterId=${process.env.INTERNET_IDENTITY_CANISTER_ID}#authorize`,
// Maximum authorization expiration is 8 days
maxTimeToLive: days * hours * nanoseconds,
});
};
};
async function setupToast() {
const header = document.getElementById("header");
const status = document.getElementById("status");
const content = document.getElementById("content");
const closeButton = status?.querySelector("button");
closeButton?.addEventListener("click", () => {
status?.classList.add("hidden");
});
}
async function handleAuthenticated(authClient: AuthClient) {
const identity = (await authClient.getIdentity()) as unknown as Identity;
const whoami_actor = createActor(canisterId as string, {
agentOptions: {
identity,
},
});
// Invalidate identity then render login when user goes idle
authClient.idleManager?.registerCallback(() => {
Actor.agentOf(whoami_actor)?.invalidateIdentity?.();
renderIndex();
});
renderLoggedIn(whoami_actor, authClient);
}
init();