Search code examples
angularangular-guardsangular-social-login

How to check: is the User logged in with angular-6-social-login npm package?


I have successfully integrated with angular-6-social-login (https://www.npmjs.com/package/angular-6-social-login) to login into my angular APP using google account.

I am creating an Angular Guard to protect the routes so that only users can access after logging in. The AuthService from angular-6-social-login does not support any direct function to see if the user has logged in or not. Any suggestions here, please?

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from 'angular-6-social-login';

@Injectable({
  providedIn: 'root'
})
export class LoginGuardGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {}

  canActivate(nextRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const requiresLogin = nextRoute.data.requiresLogin || false;
    console.log("AccessGuard canActivate is being called")

      // Check that the user is logged in...
      //TODO: need help with the if condition
      if (!<userLoggedin>) { 
      this.router.navigate(['login'])  
      return false;
    }

    return true;
  }
}

Solution

  • When you have successfully logged in, Facebook/Google will provide unique access token for a particular user.

    For example in Google: userData.getAuthResponse().id_token;

    This token can be stored in Cookies/localStorage/sessionStorage according to your application needs and check if this token is available at the auth guard.

    Example:

    localStorage.setItem("APP_TOKEN", userData.getAuthResponse().id_token);
    

    AuthGuard:

    canActivate(): Observable<boolean> {
      if (!localStorage.getItem("APP_TOKEN")) {
        this.router.navigate(['login'])  
        return false;
      }
      return true;
    }
    

    This token can also be used with your backend server to validate the current user. More details on this link ID Token Auth. For Facebook FB Access tokens

    Make sure to clear this token and call an api to invalidate this token on Logout.

    localStorage.removeItem("APP_TOKEN")