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

旧时模样 提交于 2021-01-28 12:21:09

问题


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;
  }
}

回答1:


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")


来源:https://stackoverflow.com/questions/59366530/how-to-check-is-the-user-logged-in-with-angular-6-social-login-npm-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!