/
guard.ts
90 lines (75 loc) · 2.19 KB
/
guard.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
80
81
82
83
84
85
86
87
88
89
90
import type { RouteLocation } from 'vue-router';
import { watchEffectOnceAsync } from './utils';
import { client as auth0Client } from './plugin';
import { AUTH0_TOKEN } from './token';
import type { Auth0VueClient } from './interfaces';
import type { App } from 'vue';
import { unref } from 'vue';
import type { RedirectLoginOptions } from '@auth0/auth0-spa-js';
async function createGuardHandler(
client: Auth0VueClient,
to: RouteLocation,
redirectLoginOptions?: RedirectLoginOptions
) {
const fn = async () => {
if (unref(client.isAuthenticated)) {
return true;
}
await client.loginWithRedirect({
appState: { target: to.fullPath },
...redirectLoginOptions
});
return false;
};
if (!unref(client.isLoading)) {
return fn();
}
await watchEffectOnceAsync(() => !unref(client.isLoading));
return fn();
}
/**
* The options used when creating an AuthGuard.
*/
export interface AuthGuardOptions {
/**
* The vue application
*/
app?: App;
/**
* Route specific options to use when being redirected to Auth0
*/
redirectLoginOptions?: RedirectLoginOptions;
}
/**
*
* @param [app] The vue application
*/
export function createAuthGuard(
app?: App
): (to: RouteLocation) => Promise<boolean>;
/**
*
* @param [options] The options used when creating an AuthGuard.
*/
export function createAuthGuard(
options?: AuthGuardOptions
): (to: RouteLocation) => Promise<boolean>;
export function createAuthGuard(
appOrOptions?: App | AuthGuardOptions
): (to: RouteLocation) => Promise<boolean> {
const { app, redirectLoginOptions } =
!appOrOptions || 'config' in appOrOptions
? { app: appOrOptions as App, redirectLoginOptions: undefined }
: (appOrOptions as AuthGuardOptions);
return async (to: RouteLocation) => {
// eslint-disable-next-line security/detect-object-injection
const auth0 = app
? (app.config.globalProperties[AUTH0_TOKEN] as Auth0VueClient)
: (unref(auth0Client) as Auth0VueClient);
return createGuardHandler(auth0, to, redirectLoginOptions);
};
}
export async function authGuard(to: RouteLocation) {
const auth0 = unref(auth0Client) as Auth0VueClient;
return createGuardHandler(auth0, to);
}