Search code examples
angularangular6angular-routingangular-guards

How to redirect to login page if the user is not logged in?


I have implemented the before login and after login guard so that some users can not access all the pages. My question is when user is not logged in & when they try to enter the unauthorized page such as "localhost:4200/restricted_page" it should be redirected to login page "localhost:4200/login". But I am not being able to redirect to login page. Now it redirects only to localhost:4200 only.

Where should I fix the code?

before-login.guard

export class BeforeLoginGuard implements CanActivate {
    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

        return !this._tokenService.loggedIn();

    }

    constructor(private _tokenService: TokenService) { }
}

after-login.guard

export class AfterLoginGuard implements CanActivate {

    constructor(private _tokenService: TokenService) { }

    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

        return this._tokenService.loggedIn();
    }
}

token.service

export class TokenService {
    payload(token) {
        const payload = token.split('.')[1];
        //decoding 
        if (typeof (payload) !== 'undefined')
            return JSON.parse(atob(payload));
        return false;
    }

    loggedIn() {
        // return this.isValid();
        const token = this.getToken();
        console.log("token", token);
        if (token) {
            const payload = this.payload(token);
            if (payload) {
                return Object.values(this.iss).indexOf(payload.iss) > -1 ? true : false;
            }
        }
        return false;
    }
}

Solution

  • I believe localhost:4200/restricted_page - this route will have AfterLoginGuard .

    So in that component

       canActivate( next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
           let flag = this._tokenService.loggedIn();
           if(flag ){
              return flag ;
           } else {
              // Navigate to login component. You will have to add router to constructor 
                 and then this.router.navigate(['/login']);
              return;
           }
           return flag;
        }
    

    Ideally I believe there should be only one Auth gaurd with different conditions. But anyways you have developed 2 above will work for you.