-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathauth.guard.ts
More file actions
59 lines (52 loc) · 2.1 KB
/
auth.guard.ts
File metadata and controls
59 lines (52 loc) · 2.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
import { inject } from '@angular/core'
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router'
import { OidcSecurityService } from 'angular-auth-oidc-client'
import { Observable, of } from 'rxjs'
import { map, switchMap, take, filter } from 'rxjs/operators' // <--- Import filter
import { StateStorageService } from './service/state-storage.service'
import { AccountService } from './service/account.service'
import { log } from 'console'
export const AuthGuard = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean => {
const authorities = route.data['authorities']
const router = inject(Router)
const accountService = inject(AccountService)
const stateStorageService = inject(StateStorageService)
const oidcSecurityService = inject(OidcSecurityService)
return oidcSecurityService.checkAuth().pipe(
take(1),
switchMap(({ isAuthenticated }) => {
// 1. If not authenticated at all, redirect to login
if (!isAuthenticated) {
if (state.url === '/login') {
return of(true)
}
console.log('storing state url for redirect after login:', state.url)
stateStorageService.storeUrl(state.url)
router.navigate(['/login'])
return of(false)
}
console.log('AuthGuard: Authenticated. Waiting for Account Data...')
// 2. Fetch Account Data
return accountService.getAccountData().pipe(
// This ensures we don't fail while the HTTP request is still loading.
filter((account) => account !== undefined),
take(1), // Take the first valid result and complete
map((account) => {
if (account) {
const hasAnyAuthority = accountService.hasAnyAuthority(authorities)
if (hasAnyAuthority) {
return true
} else {
router.navigate(['accessdenied'])
return false
}
} else {
// If account is null (API failed or 401), send to login
router.navigate(['/login'])
return false
}
})
)
})
)
}