In my application, I have a function called checkAuth
within the ngOnInit
method of the app.component.ts
file. This function checks the localStorage for a token and if the token is valid, the authService logs you in.
Additionally, there is an AuthGuard set up on the /profile
route to verify if you are logged in.
The issue arises when clicking a link in the navbar works fine, but going directly to a link causes the AuthGuard to run before my checkAuth
function, resulting in a false return.
Where should I position my checkAuth
function to ensure it works correctly?
Or should I make changes to the AuthGuard or app.component?
Here is the code for the AuthGuard:
@Injectable({
providedIn:'root'
})
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private auth:AuthService, private router:Router) {
}
canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean>{
console.log(this.auth.isAuth)
console.log(this.auth.isLoggedIn())
if (this.auth.isLoggedIn()){
return of(true)
} else {
this.router.navigate(['/login'])
return of(false)
}
}
canActivateChild(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean>{
return this.canActivate(route, state)
}
}
Code snippet from app.component:
ngOnInit() {
if (localStorage.getItem('token')){
this.auth.checkAuth().subscribe(
(data) => {
console.log(data)
console.log(this.auth.isAuth)
}
)
}
}
Snippet showcasing the checkAuth function in AuthService:
checkAuth():Observable<UserDto>{
return this.http.get<UserDto>(`/api/user/refresh`, {withCredentials:true, observe:'body', responseType:'json'})
.pipe(
tap(
(data) => {
localStorage.setItem('token', data.accessToken)
this.setAuth(true)
this.setUser(data.user)
},
(error) => {
console.log(error)
}
)
)
}