/
plugin.ts
219 lines (191 loc) · 6.27 KB
/
plugin.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
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
import type { App, Ref } from 'vue';
import { readonly, ref } from 'vue';
import type { Router } from 'vue-router';
import type {
AppState,
Auth0PluginOptions,
Auth0VueClient,
Auth0VueClientOptions,
LogoutOptions,
RedirectLoginOptions
} from './interfaces';
import { AUTH0_INJECTION_KEY, AUTH0_TOKEN } from './token';
import version from './version';
import type {
GetTokenSilentlyOptions,
GetTokenSilentlyVerboseResponse,
GetTokenWithPopupOptions,
IdToken,
PopupConfigOptions,
PopupLoginOptions,
RedirectLoginResult
} from '@auth0/auth0-spa-js';
import { Auth0Client, User } from '@auth0/auth0-spa-js';
import { bindPluginMethods, deprecateRedirectUri } from './utils';
/**
* Helper callback that's used by default before the plugin is installed.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const PLUGIN_NOT_INSTALLED_HANDLER: any = () => {
console.error(`Please ensure Auth0's Vue plugin is correctly installed.`);
};
/**
* Helper client that's used by default before the plugin is installed.
*/
const PLUGIN_NOT_INSTALLED_CLIENT: Auth0VueClient = {
isLoading: ref(false),
isAuthenticated: ref(false),
user: ref(undefined),
idTokenClaims: ref(undefined),
error: ref(null),
loginWithPopup: PLUGIN_NOT_INSTALLED_HANDLER,
loginWithRedirect: PLUGIN_NOT_INSTALLED_HANDLER,
getAccessTokenSilently: PLUGIN_NOT_INSTALLED_HANDLER,
getAccessTokenWithPopup: PLUGIN_NOT_INSTALLED_HANDLER,
logout: PLUGIN_NOT_INSTALLED_HANDLER,
checkSession: PLUGIN_NOT_INSTALLED_HANDLER,
handleRedirectCallback: PLUGIN_NOT_INSTALLED_HANDLER
};
/**
* @ignore
*/
export const client: Ref<Auth0VueClient> = ref(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
PLUGIN_NOT_INSTALLED_CLIENT as any
);
/**
* @ignore
*/
export class Auth0Plugin implements Auth0VueClient {
private _client!: Auth0Client;
private _isLoading: Ref<boolean> = ref(true);
private _isAuthenticated: Ref<boolean> = ref(false);
private _user: Ref<User | undefined> = ref({});
private _idTokenClaims = ref<IdToken>();
private _error = ref<Error | null>(null);
isLoading = readonly(this._isLoading);
isAuthenticated = readonly(this._isAuthenticated);
user = readonly(this._user);
idTokenClaims = readonly(this._idTokenClaims);
error = readonly(this._error);
constructor(
private clientOptions: Auth0VueClientOptions,
private pluginOptions?: Auth0PluginOptions
) {
// Vue Plugins can have issues when passing around the instance to `provide`
// Therefor we need to bind all methods correctly to `this`.
bindPluginMethods(this, ['constructor']);
}
install(app: App) {
this._client = new Auth0Client({
...this.clientOptions,
auth0Client: {
name: 'auth0-vue',
version: version
}
});
this.__checkSession(app.config.globalProperties.$router);
// eslint-disable-next-line security/detect-object-injection
app.config.globalProperties[AUTH0_TOKEN] = this;
app.provide(AUTH0_INJECTION_KEY, this as Auth0VueClient);
client.value = this as Auth0VueClient;
}
async loginWithRedirect(options?: RedirectLoginOptions<AppState>) {
deprecateRedirectUri(options);
return this._client.loginWithRedirect(options);
}
async loginWithPopup(
options?: PopupLoginOptions,
config?: PopupConfigOptions
) {
deprecateRedirectUri(options);
return this.__proxy(() => this._client.loginWithPopup(options, config));
}
async logout(options?: LogoutOptions) {
if (options?.openUrl || options?.openUrl === false) {
return this.__proxy(() => this._client.logout(options));
}
return this._client.logout(options);
}
/* istanbul ignore next */
async getAccessTokenSilently(
options: GetTokenSilentlyOptions & { detailedResponse: true }
): Promise<GetTokenSilentlyVerboseResponse>;
/* istanbul ignore next */
async getAccessTokenSilently(
options?: GetTokenSilentlyOptions
): Promise<string>;
/* istanbul ignore next */
async getAccessTokenSilently(
options: GetTokenSilentlyOptions = {}
): Promise<string | GetTokenSilentlyVerboseResponse> {
deprecateRedirectUri(options);
return this.__proxy(() => this._client.getTokenSilently(options));
}
async getAccessTokenWithPopup(
options?: GetTokenWithPopupOptions,
config?: PopupConfigOptions
) {
deprecateRedirectUri(options);
return this.__proxy(() => this._client.getTokenWithPopup(options, config));
}
async checkSession(options?: GetTokenSilentlyOptions) {
return this.__proxy(() => this._client.checkSession(options));
}
async handleRedirectCallback(
url?: string
): Promise<RedirectLoginResult<AppState>> {
return this.__proxy(() =>
this._client.handleRedirectCallback<AppState>(url)
);
}
private async __checkSession(router?: Router) {
const search = window.location.search;
try {
if (
(search.includes('code=') || search.includes('error=')) &&
search.includes('state=') &&
!this.pluginOptions?.skipRedirectCallback
) {
const result = await this.handleRedirectCallback();
const appState = result?.appState;
const target = appState?.target ?? '/';
window.history.replaceState({}, '', '/');
if (router) {
router.push(target);
}
return result;
} else {
await this.checkSession();
}
} catch (e) {
// __checkSession should never throw an exception as it will fail installing the plugin.
// Instead, errors during __checkSession are propagated using the errors property on `useAuth0`.
window.history.replaceState({}, '', '/');
if (router) {
router.push(this.pluginOptions?.errorPath || '/');
}
}
}
private async __refreshState() {
this._isAuthenticated.value = await this._client.isAuthenticated();
this._user.value = await this._client.getUser();
this._idTokenClaims.value = await this._client.getIdTokenClaims();
this._isLoading.value = false;
}
private async __proxy<T>(cb: () => T, refreshState = true) {
let result;
try {
result = await cb();
this._error.value = null;
} catch (e) {
this._error.value = e as Error;
throw e;
} finally {
if (refreshState) {
await this.__refreshState();
}
}
return result;
}
}