Last active
May 11, 2019 17:14
-
-
Save MaxySpark/61aaff9e587dbb4d039673dea32036a7 to your computer and use it in GitHub Desktop.
angular authguard
This file contains hidden or 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 { CanActivate, Router } from '@angular/router'; | |
| import { CookieService } from 'ngx-cookie-service'; | |
| @Injectable() | |
| export class AuthGuardService implements CanActivate { | |
| constructor( | |
| public cookieService: CookieService, | |
| public router: Router | |
| ) { } | |
| canActivate(): boolean { | |
| const token = this.cookieService.get('AuthToken'); | |
| if (token === '') { | |
| this.router.navigate(['auth']); | |
| return false; | |
| } | |
| let payload_buff = token.split('.')[1]; | |
| payload_buff = atob(payload_buff); | |
| const payload = JSON.parse(payload_buff); | |
| if (token !== '' && (payload.exp > (Date.now() / 1000)) && payload.iss === 'MaxySpark') { | |
| return true; | |
| } | |
| this.router.navigate(['auth']); | |
| return false; | |
| } | |
| } |
This file contains hidden or 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 { Routes, CanActivate } from '@angular/router'; | |
| import { TestComponent } from './test.component'; | |
| import { AuthGuardService as AuthGuard } from '../auth/auth-guard.service'; | |
| export const testRoutes: Routes = [ | |
| { | |
| path: '', | |
| component: TestComponent, | |
| canActivate: [AuthGuard] | |
| } | |
| ]; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dependency
npm i -s ngx-cookie-service