-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathclient.ts
More file actions
478 lines (400 loc) · 16.1 KB
/
client.ts
File metadata and controls
478 lines (400 loc) · 16.1 KB
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import {AuthenticationInfo, fetchAuthenticationInfo, logout} from "./api"
import {currentTimeSeconds, getLocalStorageNumber, hasLocalStorage, hasWindow} from "./helpers"
const LOGGED_IN_AT_KEY = "__PROPEL_AUTH_LOGGED_IN_AT"
const LOGGED_OUT_AT_KEY = "__PROPEL_AUTH_LOGGED_OUT_AT"
const AUTH_TOKEN_REFRESH_BEFORE_EXPIRATION_SECONDS = 4 * 60
const DEBOUNCE_DURATION_FOR_REFOCUS_SECONDS = 4 * 60
export interface RedirectToSignupOptions {
postSignupRedirectUrl: string
}
export interface RedirectToLoginOptions {
postLoginRedirectUrl: string
}
export interface IAuthClient {
/**
* If the user is logged in, this method returns an access token, the time (in seconds) that the token will expire,
* the user's organizations (including org names and user's role within the org), and the user's metadata.
* Otherwise, this method returns null.
*
* The promise will generally resolve immediately, unless our current information is stale in which case it will
* make an API request.
*
* @param forceRefresh If true, this method will always make an API request. Default false
*/
getAuthenticationInfoOrNull(forceRefresh?: boolean): Promise<AuthenticationInfo | null>
/**
* Logs the current user out.
* @param redirectAfterLogout If true, will redirect the user to the configured logout URL.
*/
logout(redirectAfterLogout: boolean): Promise<void>
/**
* Gets the URL for the hosted signup page.
*/
getSignupPageUrl(options?: RedirectToSignupOptions): string
/**
* Gets the URL for the hosted login page.
*/
getLoginPageUrl(options?: RedirectToLoginOptions): string
/**
* Gets the URL for the hosted account page.
*/
getAccountPageUrl(): string
/**
* Gets the URL for the hosted organization page.
* @param orgId The ID of the organization's page to load. If not specified, a random one will be used instead.
*/
getOrgPageUrl(orgId?: string): string
/**
* Gets the URL for the hosted create organization page.
*/
getCreateOrgPageUrl(): string
/**
* Gets the URL for the hosted SAML configuration page.
*/
getSetupSAMLPageUrl(orgId: string): string
/**
* Gets the URL for the hosted personal API key page.
*/
getPersonalApiKeyPageUrl(): string
/**
* Gets the URL for the hosted org API key page.
*/
getOrgApiKeyPageUrl(orgId: string): string
/**
* Redirects the user to the signup page.
*/
redirectToSignupPage(options?: RedirectToSignupOptions): void
/**
* Redirects the user to the login page.
*/
redirectToLoginPage(options?: RedirectToLoginOptions): void
/**
* Redirects the user to the account page.
*/
redirectToAccountPage(): void
/**
* Redirects the user to the organization page.
* @param orgId The ID of the organization"s page to load. If not specified, a random one will be used instead.
*/
redirectToOrgPage(orgId?: string): void
/**
* Redirects the user to the create organization page.
*/
redirectToCreateOrgPage(): void
/**
* Redirects the user to the SAML configuration page.
*/
redirectToSetupSAMLPage(orgId: string): void
/**
* Redirects the user to the personal API key page.
*/
redirectToPersonalApiKeyPage(): void
/**
* Redirects the user to the org API key page.
*/
redirectToOrgApiKeyPage(): void
/**
* Adds an observer which is called whenever the users logs in or logs out.
*/
addLoggedInChangeObserver(observer: (isLoggedIn: boolean) => void): void
/**
* Removes the observer
*/
removeLoggedInChangeObserver(observer: (isLoggedIn: boolean) => void): void
/**
* Cleanup the auth client if you no longer need it.
*/
destroy(): void
}
export interface IAuthOptions {
/**
* Base URL where your authentication pages are hosted. See **Frontend Integration** section of your PropelAuth project.
*/
authUrl: string
/**
* If true, periodically refresh the token in the background.
* This helps ensure you always have a valid token ready to go when you need it.
*
* Default true
*/
enableBackgroundTokenRefresh?: boolean
}
interface ClientState {
initialLoadFinished: boolean
authenticationInfo: AuthenticationInfo | null
observers: ((isLoggedIn: boolean) => void)[]
lastLoggedInAtMessage: number | null
lastLoggedOutAtMessage: number | null
refreshInterval: number | null
lastRefresh: number | null
readonly authUrl: string
}
function validateAndCleanupOptions(authOptions: IAuthOptions) {
try {
// This helps make sure we have a consistent URL ignoring things like trailing slashes
const authUrl = new URL(authOptions.authUrl)
authOptions.authUrl = authUrl.origin
} catch (e) {
console.error("Invalid authUrl", e)
throw new Error("Unable to initialize auth client")
}
if (authOptions.enableBackgroundTokenRefresh === undefined) {
authOptions.enableBackgroundTokenRefresh = true
}
}
export function createClient(authOptions: IAuthOptions): IAuthClient {
validateAndCleanupOptions(authOptions)
// Internal state
const clientState: ClientState = {
initialLoadFinished: false,
authenticationInfo: null,
observers: [],
lastLoggedInAtMessage: getLocalStorageNumber(LOGGED_IN_AT_KEY),
lastLoggedOutAtMessage: getLocalStorageNumber(LOGGED_OUT_AT_KEY),
authUrl: authOptions.authUrl,
refreshInterval: null,
lastRefresh: null,
}
// Helper functions
function notifyObservers(isLoggedIn: boolean) {
for (let i = 0; i < clientState.observers.length; i++) {
const observer = clientState.observers[i]
if (observer) {
observer(isLoggedIn)
}
}
}
function userJustLoggedOut(accessToken: string | undefined, previousAccessToken: string | undefined) {
// Edge case: the first time we go to the page, if we can't load the
// auth token we should treat it as a logout event
return !accessToken && (previousAccessToken || !clientState.initialLoadFinished)
}
function userJustLoggedIn(accessToken: string | undefined, previousAccessToken: string | undefined) {
return !previousAccessToken && accessToken
}
function updateLastLoggedOutAt() {
const loggedOutAt = currentTimeSeconds()
clientState.lastLoggedOutAtMessage = loggedOutAt
if (hasLocalStorage()) {
localStorage.setItem(LOGGED_OUT_AT_KEY, String(loggedOutAt))
}
}
function updateLastLoggedInAt() {
const loggedInAt = currentTimeSeconds()
clientState.lastLoggedInAtMessage = loggedInAt
if (hasLocalStorage()) {
localStorage.setItem(LOGGED_IN_AT_KEY, String(loggedInAt))
}
}
function setAuthenticationInfoAndUpdateDownstream(authenticationInfo: AuthenticationInfo | null) {
const previousAccessToken = clientState.authenticationInfo?.accessToken
clientState.authenticationInfo = authenticationInfo
const accessToken = authenticationInfo?.accessToken
if (userJustLoggedOut(accessToken, previousAccessToken)) {
notifyObservers(false)
updateLastLoggedOutAt()
} else if (userJustLoggedIn(accessToken, previousAccessToken)) {
notifyObservers(true)
updateLastLoggedInAt()
}
clientState.lastRefresh = currentTimeSeconds()
clientState.initialLoadFinished = true
}
async function forceRefreshToken(returnCached: boolean): Promise<AuthenticationInfo | null> {
try {
// Happy case, we fetch auth info and save it
const authenticationInfo = await fetchAuthenticationInfo(clientState.authUrl)
setAuthenticationInfoAndUpdateDownstream(authenticationInfo)
return authenticationInfo
} catch (e) {
// If there was an error, we sometimes still want to return the value we have cached
// (e.g. if we were prefetching), so in those cases we swallow the exception
if (returnCached) {
return clientState.authenticationInfo
} else {
setAuthenticationInfoAndUpdateDownstream(null)
throw e
}
}
}
const getSignupPageUrl = (options?: RedirectToSignupOptions) => {
let qs = ""
if (options && options.postSignupRedirectUrl) {
const encode = window ? window.btoa : btoa;
qs = new URLSearchParams({"rt": encode(options.postSignupRedirectUrl)}).toString()
}
return `${clientState.authUrl}/signup?${qs}`
}
const getLoginPageUrl = (options?: RedirectToLoginOptions) => {
let qs = ""
if (options && options.postLoginRedirectUrl) {
const encode = window ? window.btoa : btoa;
qs = new URLSearchParams({"rt": encode(options.postLoginRedirectUrl)}).toString()
}
return `${clientState.authUrl}/login?${qs}`
}
const getAccountPageUrl = () => {
return `${clientState.authUrl}/account`
}
const getOrgPageUrl = (orgId?: string) => {
if (orgId) {
return `${clientState.authUrl}/org?id=${orgId}`
} else {
return `${clientState.authUrl}/org`
}
}
const getCreateOrgPageUrl = () => {
return `${clientState.authUrl}/create_org`
}
const getSetupSAMLPageUrl = (orgId: string) => {
return `${clientState.authUrl}/saml?id=${orgId}`
}
const getPersonalApiKeyPageUrl = () => {
return `${clientState.authUrl}/api_keys/personal`
}
const getOrgApiKeyPageUrl = () => {
return `${clientState.authUrl}/api_keys/org`
}
const client = {
addLoggedInChangeObserver(loggedInChangeObserver: (isLoggedIn: boolean) => void): void {
const hasObserver = clientState.observers.includes(loggedInChangeObserver)
if (hasObserver) {
console.error("Observer has been attached already.")
} else if (!loggedInChangeObserver) {
console.error("Cannot add a null observer")
} else {
clientState.observers.push(loggedInChangeObserver)
}
},
removeLoggedInChangeObserver(loggedInChangeObserver: (isLoggedIn: boolean) => void): void {
const observerIndex = clientState.observers.indexOf(loggedInChangeObserver)
if (observerIndex === -1) {
console.error("Cannot find observer to remove")
} else {
clientState.observers.splice(observerIndex, 1)
}
},
async getAuthenticationInfoOrNull(forceRefresh?: boolean): Promise<AuthenticationInfo | null> {
const currentTimeSecs = currentTimeSeconds()
if (forceRefresh) {
return await forceRefreshToken(false)
} else if (!clientState.authenticationInfo) {
return await forceRefreshToken(false)
} else if (
currentTimeSecs + AUTH_TOKEN_REFRESH_BEFORE_EXPIRATION_SECONDS >
clientState.authenticationInfo.expiresAtSeconds
) {
// Small edge case: If we were being proactive
// and the auth information hasn't expired yet, swallow any exceptions
const returnCached = currentTimeSecs < clientState.authenticationInfo.expiresAtSeconds
return await forceRefreshToken(returnCached)
} else {
return clientState.authenticationInfo
}
},
getSignupPageUrl(options?: RedirectToSignupOptions): string {
return getSignupPageUrl(options)
},
getLoginPageUrl(options?: RedirectToLoginOptions): string {
return getLoginPageUrl(options)
},
getAccountPageUrl(): string {
return getAccountPageUrl()
},
getPersonalApiKeyPageUrl(): string {
return getPersonalApiKeyPageUrl()
},
getOrgApiKeyPageUrl(): string {
return getOrgApiKeyPageUrl()
},
getOrgPageUrl(orgId?: string): string {
return getOrgPageUrl(orgId)
},
getCreateOrgPageUrl(): string {
return getCreateOrgPageUrl()
},
getSetupSAMLPageUrl(orgId: string): string {
return getSetupSAMLPageUrl(orgId)
},
redirectToSignupPage(options?: RedirectToSignupOptions): void {
window.location.href = getSignupPageUrl(options)
},
redirectToLoginPage(options?: RedirectToLoginOptions): void {
window.location.href = getLoginPageUrl(options)
},
redirectToAccountPage(): void {
window.location.href = getAccountPageUrl()
},
redirectToOrgPage(orgId?: string): void {
window.location.href = getOrgPageUrl(orgId)
},
redirectToCreateOrgPage(): void {
window.location.href = getCreateOrgPageUrl()
},
redirectToSetupSAMLPage(orgId: string) {
window.location.href = getSetupSAMLPageUrl(orgId)
},
redirectToPersonalApiKeyPage(): void {
window.location.href = getPersonalApiKeyPageUrl()
},
redirectToOrgApiKeyPage(): void {
window.location.href = getOrgApiKeyPageUrl()
},
async logout(redirectAfterLogout: boolean): Promise<void> {
const logoutResponse = await logout(clientState.authUrl)
setAuthenticationInfoAndUpdateDownstream(null)
if (redirectAfterLogout) {
window.location.href = logoutResponse.redirect_to
}
},
destroy() {
clientState.observers = []
window.removeEventListener("storage", onStorageChange)
if (clientState.refreshInterval) {
clearInterval(clientState.refreshInterval)
}
},
}
const onStorageChange = async function () {
// If localStorage isn't available, nothing to do here.
// This usually happens in frameworks that have some SSR components
if (!hasLocalStorage()) {
return
}
const loggedOutAt = getLocalStorageNumber(LOGGED_OUT_AT_KEY)
const loggedInAt = getLocalStorageNumber(LOGGED_IN_AT_KEY)
// If we've detected a logout event after the last one our client is aware of, trigger a refresh
if (loggedOutAt && (!clientState.lastLoggedOutAtMessage || loggedOutAt > clientState.lastLoggedOutAtMessage)) {
clientState.lastLoggedOutAtMessage = loggedOutAt
if (clientState.authenticationInfo) {
await forceRefreshToken(true)
}
}
// If we've detected a login event after the last one our client is aware of, trigger a refresh
if (loggedInAt && (!clientState.lastLoggedInAtMessage || loggedInAt > clientState.lastLoggedInAtMessage)) {
clientState.lastLoggedInAtMessage = loggedInAt
if (!clientState.authenticationInfo) {
await forceRefreshToken(true)
}
}
}
// If we were offline or on a different tab, when we return, refetch auth info
// Some browsers trigger focus more often than we'd like, so we'll debounce a little here as well
const onOnlineOrFocus = async function () {
if (clientState.lastRefresh && currentTimeSeconds() > clientState.lastRefresh + DEBOUNCE_DURATION_FOR_REFOCUS_SECONDS) {
await forceRefreshToken(true)
} else {
await client.getAuthenticationInfoOrNull()
}
}
if (hasWindow()) {
window.addEventListener("storage", onStorageChange)
window.addEventListener("online", onOnlineOrFocus)
window.addEventListener("focus", onOnlineOrFocus)
if (authOptions.enableBackgroundTokenRefresh) {
client.getAuthenticationInfoOrNull()
clientState.refreshInterval = window.setInterval(client.getAuthenticationInfoOrNull, 60000)
}
}
return client
}