-
Notifications
You must be signed in to change notification settings - Fork 156
/
authService.ts
354 lines (311 loc) · 12.1 KB
/
authService.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
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
import { UserManager } from './userManager'
import { PublicLinkManager } from './publicLinkManager'
import {
AuthStore,
ClientService,
UserStore,
CapabilityStore,
ConfigStore,
useTokenTimerWorker,
AuthServiceInterface
} from '@ownclouders/web-pkg'
import { RouteLocation, Router } from 'vue-router'
import {
extractPublicLinkToken,
isAnonymousContext,
isIdpContextRequired,
isPublicLinkContextRequired,
isUserContextRequired
} from '../../router'
import { unref } from 'vue'
import { Ability } from '@ownclouders/web-client'
import { Language } from 'vue3-gettext'
import { PublicLinkType } from '@ownclouders/web-client'
import { WebWorkersStore } from '@ownclouders/web-pkg'
export class AuthService implements AuthServiceInterface {
private clientService: ClientService
private configStore: ConfigStore
private router: Router
private userManager: UserManager
private publicLinkManager: PublicLinkManager
private ability: Ability
private language: Language
private userStore: UserStore
private authStore: AuthStore
private capabilityStore: CapabilityStore
private webWorkersStore: WebWorkersStore
private tokenTimerWorker: ReturnType<typeof useTokenTimerWorker>
private tokenTimerInitialized = false
// number of seconds before an access token is to expire to raise the accessTokenExpiring event
private accessTokenExpiryThreshold = 10
public hasAuthErrorOccurred: boolean
public initialize(
configStore: ConfigStore,
clientService: ClientService,
router: Router,
ability: Ability,
language: Language,
userStore: UserStore,
authStore: AuthStore,
capabilityStore: CapabilityStore,
webWorkersStore: WebWorkersStore
): void {
this.configStore = configStore
this.clientService = clientService
this.router = router
this.hasAuthErrorOccurred = false
this.ability = ability
this.language = language
this.userStore = userStore
this.authStore = authStore
this.capabilityStore = capabilityStore
this.webWorkersStore = webWorkersStore
}
/**
* Initialize publicLinkContext and userContext (whichever is available, respectively).
*
* FIXME: at the moment the order "publicLink first, user second" is important, because we trigger the `ready` hook of all applications
* as soon as any context is ready. This works well for user context pages, because they can't have a public link context at the same time.
* Public links on the other hand could have a logged in user as well, thus we need to make sure that the public link context is loaded first.
* For the moment this is fine. In the future we might want to wait triggering the `ready` hook of applications until all available contexts
* are loaded.
*
* @param to {Route}
*/
public async initializeContext(to: RouteLocation) {
if (!this.publicLinkManager) {
this.publicLinkManager = new PublicLinkManager({
clientService: this.clientService,
authStore: this.authStore,
capabilityStore: this.capabilityStore
})
}
if (isPublicLinkContextRequired(this.router, to)) {
const publicLinkToken = extractPublicLinkToken(to)
if (publicLinkToken) {
await this.publicLinkManager.updateContext(publicLinkToken)
}
} else {
this.publicLinkManager.clearContext()
}
if (!this.userManager) {
this.userManager = new UserManager({
clientService: this.clientService,
configStore: this.configStore,
ability: this.ability,
language: this.language,
userStore: this.userStore,
authStore: this.authStore,
capabilityStore: this.capabilityStore,
webWorkersStore: this.webWorkersStore,
accessTokenExpiryThreshold: this.accessTokenExpiryThreshold
})
if (!this.tokenTimerWorker) {
const { options } = this.configStore
if (!options.embed?.enabled || !options.embed?.delegateAuthentication) {
this.tokenTimerWorker = useTokenTimerWorker({ authService: this })
this.tokenTimerWorker.startWorker()
}
}
}
if (!isAnonymousContext(this.router, to)) {
const fetchUserData = !isIdpContextRequired(this.router, to)
if (!this.userManager.areEventHandlersRegistered) {
this.userManager.events.addAccessTokenExpired((...args): void => {
console.error('AccessToken Expired:', ...args)
this.handleAuthError(unref(this.router.currentRoute))
})
this.userManager.events.addAccessTokenExpiring((...args) => {
console.debug('AccessToken Expiring:', ...args)
})
this.userManager.events.addUserLoaded(async (user) => {
this.tokenTimerWorker?.setTokenTimer({
expiry: user.expires_in,
expiryThreshold: this.accessTokenExpiryThreshold
})
console.debug(
`New User Loaded. access_token: ${user.access_token}, refresh_token: ${user.refresh_token}`
)
try {
await this.userManager.updateContext(user.access_token, fetchUserData)
} catch (e) {
console.error(e)
await this.handleAuthError(unref(this.router.currentRoute))
}
})
this.userManager.events.addUserUnloaded(async () => {
console.log('user unloaded…')
this.tokenTimerWorker?.resetTokenTimer()
this.resetStateAfterUserLogout()
if (this.userManager.unloadReason === 'authError') {
this.hasAuthErrorOccurred = true
return this.router.push({
name: 'accessDenied',
query: { redirectUrl: unref(this.router.currentRoute)?.fullPath }
})
}
// handle redirect after logout
if (this.configStore.isOAuth2) {
const oAuth2 = this.configStore.oAuth2
if (oAuth2.logoutUrl) {
return (window.location = oAuth2.logoutUrl as any)
}
}
})
this.userManager.events.addSilentRenewError(async (error) => {
console.error('Silent Renew Error:', error)
await this.handleAuthError(unref(this.router.currentRoute))
})
this.userManager.areEventHandlersRegistered = true
}
// This is to prevent issues in embed mode when the expired token is still saved but already expired
// If the following code gets executed, it would toggle errorOccurred var which would then lead to redirect to the access denied screen
if (
this.configStore.options.embed?.enabled &&
this.configStore.options.embed.delegateAuthentication
) {
return
}
// relevant for page reload: token is already in userStore
// no userLoaded event and no signInCallback gets triggered
const accessToken = await this.userManager.getAccessToken()
if (accessToken) {
console.debug('[authService:initializeContext] - updating context with saved access_token')
try {
await this.userManager.updateContext(accessToken, fetchUserData)
if (!this.tokenTimerInitialized) {
const user = await this.userManager.getUser()
this.tokenTimerWorker?.setTokenTimer({
expiry: user.expires_in,
expiryThreshold: this.accessTokenExpiryThreshold
})
this.tokenTimerInitialized = true
}
} catch (e) {
console.error(e)
await this.handleAuthError(unref(this.router.currentRoute))
}
}
}
}
public loginUser(redirectUrl?: string) {
this.userManager.setPostLoginRedirectUrl(redirectUrl)
return this.userManager.signinRedirect()
}
public signinSilent() {
return this.userManager.signinSilent()
}
/**
* Sign in callback gets called from the IDP after initial login.
*/
public async signInCallback(accessToken?: string) {
try {
if (
this.configStore.options.embed.enabled &&
this.configStore.options.embed.delegateAuthentication &&
accessToken
) {
console.debug('[authService:signInCallback] - setting access_token and fetching user')
await this.userManager.updateContext(accessToken, true)
// Setup a listener to handle token refresh
console.debug('[authService:signInCallback] - adding listener to update-token event')
window.addEventListener('message', this.handleDelegatedTokenUpdate)
} else {
await this.userManager.signinRedirectCallback(this.buildSignInCallbackUrl())
}
const redirectRoute = this.router.resolve(this.userManager.getAndClearPostLoginRedirectUrl())
return this.router.replace({
path: redirectRoute.path,
...(redirectRoute.query && { query: redirectRoute.query })
})
} catch (e) {
console.warn('error during authentication:', e)
return this.handleAuthError(unref(this.router.currentRoute))
}
}
/**
* Sign in silent callback gets called with OIDC during access token renewal when no `refresh_token`
* is present (`refresh_token` exists when `offline_access` is present in scopes).
*
* The oidc-client lib emits a userLoaded event internally, which already handles the token update
* in web.
*/
public async signInSilentCallback() {
await this.userManager.signinSilentCallback(this.buildSignInCallbackUrl())
}
/**
* craft a url that the parser in oidc-client-ts can handle…
*/
private buildSignInCallbackUrl() {
const currentQuery = unref(this.router.currentRoute).query
return '/?' + new URLSearchParams(currentQuery as Record<string, string>).toString()
}
public async handleAuthError(route: RouteLocation) {
if (isPublicLinkContextRequired(this.router, route)) {
const token = extractPublicLinkToken(route)
this.publicLinkManager.clear(token)
return this.router.push({
name: 'resolvePublicLink',
params: { token },
query: { redirectUrl: route.fullPath }
})
}
if (isUserContextRequired(this.router, route) || isIdpContextRequired(this.router, route)) {
const user = await this.userManager.getUser()
if (user?.expires_in !== undefined && user.expires_in < 0) {
// token expired, simply return and let the regular auth flow do its thing
return
}
await this.userManager.removeUser('authError')
this.tokenTimerWorker?.resetTokenTimer()
return
}
// authGuard is taking care of redirecting the user to the
// accessDenied page if hasAuthErrorOccurred is set to true
// we can't push the route ourselves, see authGuard for details.
this.hasAuthErrorOccurred = true
}
public async resolvePublicLink(
token: string,
passwordRequired: boolean,
password: string,
type: PublicLinkType
) {
this.publicLinkManager.setPasswordRequired(token, passwordRequired)
this.publicLinkManager.setPassword(token, password)
this.publicLinkManager.setResolved(token, true)
this.publicLinkManager.setType(token, type)
await this.publicLinkManager.updateContext(token)
}
public async logoutUser() {
const endSessionEndpoint = await this.userManager.metadataService?.getEndSessionEndpoint()
if (!endSessionEndpoint) {
await this.userManager.removeUser()
return this.router.push({ name: 'logout' })
}
const u = await this.userManager.getUser()
if (u && u.id_token) {
return this.userManager.signoutRedirect({ id_token_hint: u.id_token })
}
return await this.userManager.removeUser()
}
private resetStateAfterUserLogout() {
// TODO: create UserUnloadTask interface and allow registering unload-tasks in the authService
this.userStore.$reset()
this.authStore.clearUserContext()
}
private handleDelegatedTokenUpdate(event: MessageEvent) {
if (
this.configStore.options.embed?.delegateAuthenticationOrigin &&
event.origin !== this.configStore.options.embed.delegateAuthenticationOrigin
) {
return
}
if (event.data?.name !== 'owncloud-embed:update-token') {
return
}
console.debug('[authService:handleDelegatedTokenUpdate] - going to update the access_token')
return this.userManager.updateContext(event.data, false)
}
}
export const authService = new AuthService()