Angular - Typescript variables scope

Viewed 60

I'm brand new in angular. I'm trying to create a auth-guard which send a post request to the backend, and validate the JWT. If JWT is valid guard should allow the access of the requested component. This is how my auth.guard.ts looks like:

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    
    if (this.loginService.isLoggedIn() && this.loginService.isValidateJwt() == 1) {
      console.log("AuthGuard return to requestet page!")
      return true;

    }
    else {

      console.log("AuthGuard redirect to login page!")
      this.router.navigate(['login']);

      return false;
    }

  }

This is how the loginService relevant part looks like:

  isLoggedIn(){

    let token=localStorage.getItem("jwt");
    let username=localStorage.getItem("username");

    if(token==undefined || token=='' || token==null || username==undefined || username == '' || username==null){
      console.log("LoginService isLoggedIn token and username NOT FOUND in local storage!");
      return false;

    }
    else {
      console.log("LoginService isLoggedIn token and username FOUND in local storage! Stat validate JWT!");
      return true;

    }
  }

  isValidateJwt() : number {

    console.log("isValidateJwt invoked!")
    var isvalid = 0

    this.http.post(this.validate_url, new ValidateRequest(localStorage.getItem("jwt") , localStorage.getItem("username"))).subscribe(

        (response:any)=>{
          // success
          console.log("isValidateJwt isValid: " + response.isValid);
          isvalid = response.isValid;

        },
        error=>{
          // error
          console.error(error);
          //window.location.href="/dashboard"

        }
    )
    console.log("isValidateJwt returning: " + isvalid)
    return isvalid;

  }

This is how my backend response looks like:

{
  "isValid": 1,
  "message": "JWT is VALID!"
}
  1. I created two Item in the local storage while login process (username / jwt)
  2. When the user would like to access a component that is protected, the guard calls the isLoggidIn and isValidateJwt functions.
  3. The isLoggedin function reads the localStorage and if username and jwt exists then it returns true
  4. The isValidateJwt function calls the backend and validate the jwt
  5. If the JWT is valid, backend returns isValid = 0 in the response object and I store it to the isValid variable inside the isValidateJwt function, but when the function finally returns the value of isValid variable will be 0 again.
  6. I set up the backend it's always return isValid = 0

I think it is something related to variables scope, but i don't understand why my isValid variable set back to zero.

Thank you!

1 Answers

So to put it in to words your isValidateJwt method looks like this:

  1. Set isValid to zero
  2. Some time in the future validate the jwt, don't really know when.
  3. Return isValid if the validation got executed.

So your isValidateJwt should return an observable or a promise

 isValidateJwt() : Observable<boolean> {
   return this.http.post(this.validate_url, new ValidateRequest(localStorage.getItem("jwt"), localStorage.getItem("username")))
    .pipe(map(
       (response:any) =>{
          // success
          console.log("isValidateJwt isValid: " + response.isValid);
          return response.isValid;
        }));
  }

And then you also need to return an observable from your guard method:

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | boolean {
    
    if (!this.loginService.isLoggedIn()){
       this.router.navigate(['login']);
       return false;
    }
    return this.loginService.isValidateJwt().pipe(map((result) => {                               
           if (!result) this.router.navigate(['login']);
           return result;
      }));
    }
  }
Related