import { Injectable } from '@angular/core' ; import { Router } from '@angular/router' ; import * as auth0 from 'auth0-js' ; import { environment } from '../../environments/environment' ; ( window as any ) . global = window ; @ Injectable ( { providedIn : 'root' } ) export class AuthService { auth0 = new auth0 . WebAuth ( { clientID : environment . auth . clientID , domain : environment . auth . domain , responseType : 'token' , redirectUri : environment . auth . auth0RedirectUri , audience : environment . auth . audience , scope : 'openid profile' } ) ; expiresAt : number ; userProfile : any ; accessToken : string ; authenticated : boolean ; isUser : boolean ; isEmployer : boolean ; constructor ( public router ) { } public login ( ) { this . auth0 . authorize ( ) ; } public handleLoginCallback ( ) { this . auth0 . parseHash ( ( err , authResult ) => { if ( authResult && authResult . accessToken ) { window . location . hash = '' ; this . getUserInfo ( authResult ) ; } else if ( err ) { console . log ( `Error: ${ err . error }` ) ; } this . router . navigate ( [ '/' ] ) ; } ) ; } getAccessToken ( ) { this . auth0 . checkSession ( { } , ( err , authResult ) => { if ( authResult && authResult . accessToken ) { this . getUserInfo ( authResult ) ; } } ) ; } getUserInfo ( authResult ) { this . auth0 . client . userInfo ( authResult . accessToken , ( err , profile ) => { if ( profile ) { this . setSession ( authResult , profile ) ; } } ) ; } private setSession ( authResult , profile ) { this . expiresAt = authResult . expiresIn * 1000 + Date . now ( ) ; this . accessToken = authResult . accessToken ; this . userProfile = profile ; this . authenticated = true ; } public logout ( ) { this . auth0 . logout ( { returnTo : environment . auth . auth0ReturnTo , clientID : environment . auth . clientID } ) ; } get isLoggedIn ( ) : boolean { return Date . now ( ) < this . expiresAt && this . authenticated ; } }