-
Notifications
You must be signed in to change notification settings - Fork 1
/
AccountProvider.js
92 lines (78 loc) · 2.02 KB
/
AccountProvider.js
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
import React, {
createContext,
useEffect,
useState,
useMemo,
useLayoutEffect,
} from "react";
import { Identity } from "./Identity.js";
import { hasAccess } from "./hasAccess.js";
const isBrowser = typeof window !== "undefined";
function publishEvents() {
window.dispatchEvent(
new window.CustomEvent("identity-initialized", {
detail: { ready: true },
})
);
}
function initIdentity({ identity, varnish, pulse = false }) {
const instance = new Identity(identity);
window.Identity = instance;
varnish && instance.enableVarnishCookie(varnish);
const promise = instance.hasSession();
if (pulse && window.pulse) {
window.pulse("update", {
actor: promise
.then((session) => ({
id: session.userId,
realm: "spid.no",
}))
.catch(() => false),
});
}
promise.then(publishEvents).catch(() => false);
return instance;
}
const useIsomorphicLayoutEffect = isBrowser ? useLayoutEffect : useEffect;
export const AccountContext = createContext();
export const AccountProvider = ({ config, children }) => {
const account = useMemo(() => isBrowser && initIdentity(config), []);
const [session, setSession] = useState({
access: null,
isLoggedIn: null,
user: null,
});
useIsomorphicLayoutEffect(() => {
if (!account) {
return;
}
account
.hasSession()
.then((session) => {
if (session.result) {
hasAccess(session.sp_id, config.access).then((access) => {
setSession({ user: session, isLoggedIn: true, access });
});
}
})
.catch(() => {
setSession({ user: null, isLoggedIn: false, access: false });
});
}, [account]);
const value = useMemo(
() => ({
hasAccess: session.access,
account,
user: session.user,
isLoggedIn: session.isLoggedIn,
}),
[session.access, account, session.user, session.isLoggedIn]
);
return React.createElement(
AccountContext.Provider,
{
value,
},
children
);
};