Add authentication and role access guards.

This commit is contained in:
Spencer Ofwiti 2020-12-28 12:05:33 +03:00
parent 02bed9d124
commit 2f8806b8ce
5 changed files with 85 additions and 0 deletions

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthGuard } from './auth.guard';
describe('AuthGuard', () => {
let guard: AuthGuard;
beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(AuthGuard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
});

View File

@ -0,0 +1,23 @@
import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (localStorage.getItem(atob('CICADA_USER'))) {
return true;
}
this.router.navigate(['/auth'], { queryParams: { returnUrl: state.url }});
return false;
}
}

2
src/app/_guards/index.ts Normal file
View File

@ -0,0 +1,2 @@
export * from './auth.guard';
export * from './role.guard';

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { RoleGuard } from './role.guard';
describe('RoleGuard', () => {
let guard: RoleGuard;
beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(RoleGuard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
});

View File

@ -0,0 +1,28 @@
import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class RoleGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const currentUser = JSON.parse(localStorage.getItem(atob('CICADA_USER')));
if (currentUser) {
if (route.data.roles && route.data.roles.indexOf(currentUser.role) === -1) {
this.router.navigate(['/']);
return false;
}
return true;
}
this.router.navigate(['/auth'], { queryParams: { returnUrl: state.url }});
return false;
}
}