Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
groupH_M32COM/Code/groupH_M32COM.Angular/ClientApp/src/app/auth/auth.service.ts
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
166 lines (148 sloc)
4.79 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { HttpClient } from '@angular/common/http'; | |
import { Subject, Observable, of } from 'rxjs'; | |
import { tap, delay } from 'rxjs/operators'; | |
import { Router } from '@angular/router'; | |
import { environment } from '../../environments/environment'; | |
import * as auth0 from 'auth0-js'; | |
import { JwtHelperService } from '@auth0/angular-jwt'; | |
import { CrewMember } from '../models/CrewMember'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class AuthService { | |
constructor(private http: HttpClient, private router: Router) { | |
this._idToken = ''; | |
this._accessToken = ''; | |
this._expiresAt = 0; | |
} | |
get accessToken(): string { | |
return this._accessToken; | |
} | |
get idToken(): string { | |
return this._idToken; | |
} | |
private _idToken: string; | |
private _accessToken: string; | |
private _expiresAt: number; | |
private _userRoles: string[] = []; | |
private authStatuesListener = new Subject<boolean>(); | |
redirectUrl: string; | |
apiUrl: string = environment.apiUrl; | |
auth0 = new auth0.WebAuth({ | |
clientID: 'E02Ls5Bl6mYQK48j9MdQyyETFXcIygwj', | |
domain: 'groupm32com.auth0.com', | |
responseType: 'token id_token', | |
redirectUri: environment.apiUrl + 'callback', | |
scope: 'openid email profile', | |
audience: 'https://api.rcboat.com' | |
}); | |
login() { | |
this.auth0.authorize(); | |
} | |
getUserIsAdmin(): boolean { | |
console.log('IsInRole', this.isInRole('Admin')); | |
return this.isInRole('Admin'); | |
} | |
getAuthStatusListener() { | |
return this.authStatuesListener.asObservable(); | |
} | |
getProfile(cb: (e, x: any) => void): void { | |
if (!this._accessToken) { | |
throw new Error('Access Token must exist to fetch profile'); | |
} | |
const self = this; | |
this.auth0.client.userInfo(this._accessToken, (err, profile) => { | |
if (profile) { | |
cb(err, profile); | |
} else { | |
cb(err, null); | |
} | |
}); | |
} | |
isInRole(roleName: string) { | |
return this._userRoles.indexOf(roleName) > -1; | |
} | |
decodeToken(token) { | |
const jwt = new JwtHelperService(); | |
const decodedToken = jwt.decodeToken(token); | |
console.log('jwt', decodedToken); | |
return decodedToken; | |
} | |
handleAuthentication(): void { | |
if (localStorage.getItem('isLoggedIn')) { | |
console.log('already logged in'); | |
this._accessToken = localStorage.getItem('accessToken'); | |
this._idToken = localStorage.getItem('idToken'); | |
this._expiresAt = parseInt(localStorage.getItem('expiresAt'), 10); | |
if (!this.getIsAuth()) { | |
this.logout(); | |
} | |
} else { | |
this.auth0.parseHash((err, authResult) => { | |
if (authResult && authResult.accessToken && authResult.idToken) { | |
window.location.hash = ''; | |
console.log('local login'); | |
this.localLogin(authResult); | |
this.router.navigate(['/']); | |
} else if (err) { | |
console.log('Unauthenticated'); | |
this.router.navigate(['/']); | |
console.log(err); | |
} | |
}); | |
} | |
} | |
renewTokens(): void { | |
this.auth0.checkSession({}, (err, authResult) => { | |
console.log('Trying to renew session'); | |
if (authResult && authResult.accessToken && authResult.idToken) { | |
this.localLogin(authResult); | |
} else if (err) { | |
alert( | |
`Could not get a new token (${err.error}: ${err.error_description}).` | |
); | |
this.logout(); | |
} | |
}); | |
} | |
logout(): void { | |
// Remove tokens and expiry time | |
this._accessToken = ''; | |
this._idToken = ''; | |
this._expiresAt = 0; | |
this._userRoles = []; | |
// Remove isLoggedIn flag from localStorage | |
localStorage.removeItem('isLoggedIn'); | |
localStorage.removeItem('accessToken'); | |
localStorage.removeItem('idToken'); | |
localStorage.removeItem('expiresAt'); | |
// Go back to the home route | |
this.router.navigate(['/']); | |
this.authStatuesListener.next(false); | |
} | |
getIsAuth(): boolean { | |
// Check whether the current time is past the | |
// access token's expiry time | |
return new Date().getTime() < this._expiresAt; | |
} | |
private localLogin(authResult): void { | |
// Set isLoggedIn flag in localStorage | |
// Set the time that the access token will expire at | |
const expiresAt = authResult.expiresIn * 1000 + new Date().getTime(); | |
this._accessToken = authResult.accessToken; | |
this._idToken = authResult.idToken; | |
this._expiresAt = expiresAt; | |
const decodedToken = this.decodeToken(this._accessToken); | |
if (decodedToken['https://rcboat.com/roles']) { | |
this._userRoles = decodedToken['https://rcboat.com/roles']; | |
} else { | |
this._userRoles = ['Guest']; | |
} | |
localStorage.setItem('isLoggedIn', 'true'); | |
localStorage.setItem('accessToken', this._accessToken); | |
localStorage.setItem('idToken', this._idToken); | |
localStorage.setItem('expiresAt', this._expiresAt.toString()); | |
this.authStatuesListener.next(true); | |
} | |
} |