-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth0.js
315 lines (276 loc) · 8.95 KB
/
auth0.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
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
let time = Date.now();
class Auth0EventEmitter extends EventTarget {
emit(event) {
this.dispatchEvent(new Event(event))
}
}
const auth0EventEmitter = new Auth0EventEmitter()
const printTimeElapsed = (message = '') => {
const timeElapsed = "" + (Date.now() - time)
console.log(`Time elapsed since page load: ${timeElapsed}ms ${message ? `(${message})` : ''}`)
}
const config = {
auth0: {
domain: "login.uhubs.co.uk",
client_id: "BVEBX2h9IbNhbqXHQK88wM3I4vvdMe7S",
cacheLocation: "localstorage",
audience: "https://api.uhubs.co.uk"
},
backend: "https://api.uhubs.co.uk"
}
const toggleAuth0DependantElements = (show) => {
const elements = getElementsByAttribute('show-auth0')
elements.forEach(el => {
if (show) {
el.classList.remove("d-none")
} else {
el.classList.add("d-none")
}
})
}
const attachListeners = () => {
const loginButtons = document.querySelectorAll('[auth0-login]')
loginButtons.forEach(lb => {
lb.addEventListener('click', () => login())
})
const logoutButtons = document.querySelectorAll('[auth0-logout]')
logoutButtons.forEach(lb => {
lb.addEventListener('click', () => {
auth0.logout({
returnTo: window.location.origin
});
})
})
const navigateToDashboardButtons = document.querySelectorAll('[auth0-dashboard]')
navigateToDashboardButtons.forEach(nb => {
nb.addEventListener('click', () => navigateToDashboard())
})
}
const login = async () => {
await auth0.loginWithRedirect({
appState: { target: window.location.href },
redirect_uri: window.location.origin + '/redirecting'
})
}
const isLoggedOut = () => {
const invalidLogoutPaths = [
'/coders51-b',
'/home-profile'
];
const currentLocation = window.location.pathname
return invalidLogoutPaths.indexOf(currentLocation) == -1
}
const logout = (logoutPath = '/') => {
if (!isLoggedOut()) {
auth0.logout({
returnTo: window.location.origin + logoutPath
});
}
}
const hasHomepage = (user) => {
return !!getHomepage(user)
}
const populateAuth0Element = (data, key, domAttribute = 'innerText') => {
const elements = getElementsByAttributeValue('data-auth0', key)
elements.map(element => {
if (element) {
element[domAttribute] = data[key]
}
})
}
const injectAuth0Metadata = (user) => {
const user_metadata = metadata.user;
const app_metadata = metadata.app;
if (user_metadata) {
Object.keys(user_metadata).forEach(k => {
populateAuth0Element(user_metadata, k);
populateAuth0Element(user_metadata, k, 'value');
});
}
if (app_metadata) {
Object.keys(app_metadata).forEach(k => {
populateAuth0Element(app_metadata, k);
});
}
}
const updateUI = () => {
const propertyMap = new Map([
["members", isAuthenticated],
["loggedIn", isAuthenticated],
["hasHomepage", hasHomepage(user)]
])
handleElementsVisibility(propertyMap);
handleElementsVisibility(propertyMap, 'data-auth0-content');
if (user) {
if (user['picture']) {
populateAuth0Element(user, 'picture', 'srcset');
}
injectAuth0Metadata(user);
populateAuth0Element(user, 'name');
populateAuth0Element(user, 'sub');
populateAuth0Element(user, 'email');
populateAuth0Element(user, 'sub', 'value');
populateAuth0Element(user, 'email', 'value');
}
return;
}
const getElementsByAttribute = (attribute) => {
const nodes = document.body.querySelectorAll(`[${attribute}]`);
return Array.from(nodes);
}
const getElementsByAttributeValue = (attribute, value) => {
const nodes = document.body.querySelectorAll(`[${attribute}="${value}"]`);
return Array.from(nodes);
}
const handleElementsVisibility = (propertyMap, visibilityAttribute = 'data-ms-content') => {
const elements = getElementsByAttribute(visibilityAttribute)
elements.forEach(el => {
let attributeVal = el.getAttribute(visibilityAttribute).trim();
if (!isElementVisible(attributeVal, propertyMap)) {
el.classList.add("d-none")
} else {
el.classList.remove("d-none")
printTimeElapsed(`removed ${el.id}`)
}
})
}
const isElementVisible = (attributeVal, propertyMap) => {
if (attributeVal) {
const isNegation = attributeVal.charAt(0) === "!"
if (isNegation) {
attributeVal = attributeVal.substring(1)
}
if (propertyMap.has(attributeVal)) {
const propValue = propertyMap.get(attributeVal)
return !isNegation != !propValue
}
}
return true
}
let auth0Init = false;
let domInit = false;
let domManipulated = false;
let auth0 = null;
let token = null;
let user = null;
let isAuthenticated = null;
let metadata = null;
const navigateToDashboard = () => {
window.location.href = `home-profile/${getHomepage(user)}`
}
const configureClient = async () => {
printTimeElapsed('configure client')
auth0 = await createAuth0Client(config.auth0);
printTimeElapsed('configure client end')
}
triggerDOMManipulation = () => {
if (auth0Init && domInit && !domManipulated) {
attachListeners()
updateUI();
domManipulated = true;
}
}
const handleAuth0 = async () => {
if (auth0) {
return
}
await configureClient();
// check for the code and state parameters
const query = window.location.search;
if (query.includes('code=') && query.includes('state=')) {
// Process the login state
const { appState } = await auth0.handleRedirectCallback();
if (appState.target && appState.target != window.location.href) {
window.location.href = appState.target
}
// Use replaceState to redirect the user away and remove the querystring parameters
window.history.replaceState({}, document.title, window.location.pathname);
}
isAuthenticated = await auth0.isAuthenticated();
if (!isAuthenticated) {
logout();
} else {
user = await auth0.getUser();
token = await auth0.getTokenSilently();
metadata = await fetchMetadata(user)
}
if (isHomepage() && !isUserHomepage(user)) {
window.location.href = hasHomepage(user) ? `/home-profile/${getHomepage(user)}` : '/coders51-a'
}
console.log(isAuthenticated, user)
auth0EventEmitter.emit("ready")
auth0Init = true;
triggerDOMManipulation()
}
const isHomepage = () => {
return window.location.href.includes('/home-profile/')
}
const isUserHomepage = (user) => {
return window.location.href == `${window.location.protocol}//${window.location.host}/home-profile/${getHomepage(user)}`
}
const getHomepage = (user) => {
if (!user) {
return ""
}
return metadata && metadata.app && metadata.app.homepage
}
const fetchMetadata = async (user) => {
const { user_metadata, app_metadata } = await fetch(`${config.backend}/user`, {
headers: {
'Authorization': `Bearer ${token}`,
}
}).then(res => res.json()).then(payload => {
return {...{ app_metadata: {}, user_metadata: {} }, ...payload.user }
})
user_metadata.first_name = user_metadata.first_name || user.given_name;
user_metadata.last_name = user_metadata.last_name || user.family_name;
const rawId = user.sub.includes("|") ? user.sub.split("|")[1] : user.sub;
const homepage = app_metadata.homepage || rawId;
app_metadata.homepage = app_metadata.product_dashboard_access ? homepage : "";
return { app: app_metadata, user: user_metadata }
}
const bootstrapIntegration = () => {
window.onload = () => {
toggleAuth0DependantElements(false)
handleAuth0()
toggleAuth0DependantElements(true)
domInit = true
triggerDOMManipulation()
}
}
bootstrapIntegration()
// Amplitude Event properties code
var standardProperties
function computeStandardProperties() {
if (user) {
standardProperties = {
'auth0_id': user.sub,
'logged_in': true,
'page': window.location.href
}
const msUuid = metadata.app['memberstack_id']
if (msUuid) {
standardProperties = Object.assign(standardProperties, { 'memberstack_id': msUuid })
}
} else {
standardProperties = {
'logged_in': false,
'page': window.location.href
}
}
return standardProperties
}
let auth0Ready = false
auth0EventEmitter.addEventListener("ready", () => {
auth0Ready = true
})
window.getEventProperties = (properties) => {
return new Promise((res, rej) => {
const interval = setInterval(() => {
if (auth0Ready) {
window.clearInterval(interval)
res({ ...properties, ...computeStandardProperties() })
}
}, 200)
})
}