Skip to content

Commit d3bc787

Browse files
committed
fix: check if a user is authorized via user service in the public guard
1 parent 8c2c13a commit d3bc787

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

src/app/guards/public-guard.ts

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,27 @@
11
import { CanActivateFn, Router } from '@angular/router'
2-
import { inject } from '@angular/core'
2+
import { DestroyRef, inject } from '@angular/core'
3+
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'
4+
import { catchError, of } from 'rxjs'
5+
import { UserService } from '../services/user-service'
6+
import { map } from 'rxjs/operators'
37

48
export const publicGuard: CanActivateFn = (route, state) => {
5-
const savedUserId = localStorage.getItem('user')
9+
const userService = inject(UserService)
10+
const destroyRef = inject(DestroyRef)
611
const path = route.routeConfig?.path
712
const router = inject(Router)
813

9-
if (savedUserId && (path === '' || path === 'auth')) {
10-
return router.createUrlTree(['/articles'])
11-
}
12-
13-
return true
14+
return userService.getUser().pipe(
15+
takeUntilDestroyed(destroyRef),
16+
catchError(() => {
17+
return of(null)
18+
}),
19+
map((user) => {
20+
if (user && (path === '' || path === 'auth')) {
21+
return router.createUrlTree(['/articles'])
22+
} else {
23+
return true
24+
}
25+
}),
26+
)
1427
}

0 commit comments

Comments
 (0)