-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.js
270 lines (228 loc) · 8.19 KB
/
main.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
import { createAuthRequest, fetchToken, parseToken, createInviteRequest } from '@hellocoop/helper-browser';
const CONFIG = {
client_id: 'app_GreenfieldFitnessDemoApp_s9z',
redirect_uri: 'https://www.greenfielddemo.com/',
scope: ['openid', 'profile', 'nickname'],
response_mode: 'fragment',
domain_hint: 'personal',
};
// refs
const loginBtn = document.querySelector('#login-btn');
const logoutBtn = document.querySelector('#logout-btn');
const updateBtn = document.querySelector('#update-btn');
const inviteBtn = document.querySelector('#invite-btn');
const profilePage = document.querySelector('#profile-page');
const loginPage = document.querySelector('#login-page');
const profilePageContent = document.querySelector('#profile-page-content');
const modalContainer = document.querySelector('#modal-container');
const errorContainer = document.querySelector('#error-container');
const errorField = document.querySelector('#error');
const fullNameField = document.querySelector('#full-name');
const preferredNameField = document.querySelector('#preferred-name');
const emailField = document.querySelector('#email');
const pictureField = document.querySelector('#picture');
const loadSpinner = document.querySelector('#load-spinner');
const closeModalBtn = document.querySelector('#close-modal-btn');
// bindings
window.addEventListener('load', onLoad);
loginBtn.addEventListener('click', loginEvent);
logoutBtn.addEventListener('click', logout);
updateBtn.addEventListener('click', update);
inviteBtn.addEventListener('click', invite);
closeModalBtn.addEventListener('click', closeModal);
async function onLoad() {
const { search } = window.location;
const hash = window.location.hash.substring(1);
const params = new URLSearchParams(search || hash);
if (params.has('iss')) // 3P initiated login
return login(params);
if (params.has('code')) // successful login from Hellō
processCode(params);
else {
const profile = JSON.parse(sessionStorage.getItem('profile'));
if (params.has('error')) // we got back an error from Hellō
processError(params, profile);
else if (profile) // we are logged in
showProfile(profile);
else
showLoginPage();
}
clearFragment();
removeLoader();
}
function loginEvent(event, params) {
// we don't use the event
return login(params);
}
async function login(params) {
loginBtn.classList.add('hello-btn-loader');
loginBtn.disabled = true;
const { url, nonce, code_verifier } = await createAuthRequest({
...CONFIG,
// set only in idp flow
login_hint: params?.get('login_hint') || undefined,
domain_hint: params?.get('domain_hint') || CONFIG.domain_hint,
});
// needed later for fetching the token
sessionStorage.setItem('nonce', nonce);
sessionStorage.setItem('code_verifier', code_verifier);
await sendPlausibleEvent({ path: '/start/login', n: 'action' });
window.location.href = url;
}
async function update() {
updateBtn.classList.add('hello-btn-loader');
updateBtn.disabled = true;
const { url, nonce, code_verifier } = await createAuthRequest({
...CONFIG,
prompt: 'consent',
});
// needed later for fetching the token
sessionStorage.setItem('nonce', nonce);
sessionStorage.setItem('code_verifier', code_verifier);
await sendPlausibleEvent({ path: '/update', n: 'action' });
window.location.href = url;
}
function logout() {
sendPlausibleEvent({ path: '/logout', n: 'action' });
sessionStorage.clear();
showLoginPage();
}
async function processCode(params) {
try {
const code_verifier = sessionStorage.getItem('code_verifier');
const nonce = sessionStorage.getItem('nonce');
const code = params.get('code');
if (!code_verifier)
throw new Error('Missing code_verifier');
if (!nonce)
throw new Error('Missing nonce');
if (!code)
throw new Error('Missing code');
const token = await fetchToken({
client_id: CONFIG.client_id,
redirect_uri: CONFIG.redirect_uri,
code_verifier,
nonce,
code,
});
if (!token)
throw new Error('Did not get response from token endpoint');
const { payload: profile } = parseToken(token);
if (!profile)
throw new Error('Did not get profile from token');
sessionStorage.clear(); // clean code_verifier, nonce
sessionStorage.setItem('profile', JSON.stringify(profile));
sendPlausibleEvent({ path: '/profile' });
showProfile(profile);
} catch (err) {
console.error(err)
sessionStorage.clear();
showLoginPage();
processError(params);
}
}
function processError(params, profile) {
const error = params && params.get('error');
modalContainer.style.display = 'flex';
errorContainer.style.display = 'block';
if (error === 'access_denied')
errorField.innerText = 'User cancelled request.';
else
errorField.innerText = 'Something went wrong.';
if (profile)
showProfile(profile);
else
showLoginPage();
}
function closeModal() {
modalContainer.style.display = 'none';
}
function clearFragment() {
if (!window.location.hash) return;
window.location.replace('#');
// slice off the remaining '#' in HTML5:
if (typeof window.history.replaceState === 'function') {
history.replaceState({}, '', window.location.href.slice(0, -1));
}
}
function removeLoader() {
loadSpinner.style.display = 'none';
}
function showLoginPage() {
let path = '/';
if (window.location.search) {
path += window.location.search;
}
sendPlausibleEvent({ path });
loginPage.style.visibility = 'visible';
loginPage.style.position = 'relative';
profilePage.style.display = 'none';
profilePageContent.style.display = 'none';
document.body.style.backgroundImage = 'url(/bg.jpg)';
}
const plausibleIgnore = localStorage.getItem('plausible_ignore') == 'true'
|| window.location.origin !== 'https://www.greenfielddemo.com';
async function sendPlausibleEvent(pEvent) {
if (plausibleIgnore)
return console.info('Ignoring Event: localStorage flag');
const { path, n = 'pageview' } = pEvent;
const u = new URL(path, 'https://www.greenfielddemo.com')
const body = {
u, n,
w: window.innerWidth,
d: 'greenfielddemo.com',
r: document.referrer || null,
};
try {
await fetch('/api/event', {
method: 'POST',
body: JSON.stringify(body),
});
console.info(`Event sent: ${body.u} (${body.n})`);
} catch (err) {
console.error(err);
}
}
function showProfile(profile) {
const { name, nickname, picture, email } = profile;
fullNameField.innerText = name;
preferredNameField.innerText = nickname;
emailField.innerText = email;
pictureField.src = picture;
pictureField.style.backgroundImage = `url('${picture}')`;
profilePage.style.display = profilePageContent.style.display = 'block';
}
async function invite() {
inviteBtn.classList.add('hello-btn-loader');
inviteBtn.disabled = true;
try {
const { sub } = JSON.parse(sessionStorage.getItem('profile'));
if (!sub)
throw new Error('Missing sub')
const { url } = createInviteRequest({
inviter: sub,
client_id: CONFIG.client_id,
initiate_login_uri: window.location.origin,
return_uri: window.location.origin
})
window.location.href = url;
} catch (err) {
console.error(err)
inviteBtn.classList.remove('hello-btn-loader');
inviteBtn.disabled = false;
sessionStorage.clear();
processError();
}
}
/*
* If browser back button was used, flush cache
* This ensures that user will always see an accurate, up-to-date view based on their state
* https://stackoverflow.com/questions/8788802/prevent-safari-loading-from-cache-when-back-button-is-clicked
*/
(function () {
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
}());