Skip to content
Permalink
Browse files

AuthGuard implemented.

  • Loading branch information
little-pinecone committed Jan 10, 2019
1 parent 5ebdf3b commit f9d82ce0c3c4ee26b058c374f999df3f360a0d65
@@ -1,11 +1,12 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth/guards/auth.guard';
import { LoginComponent } from './auth/components/login/login.component';
import { CookieListComponent } from './pages/cookie-list/cookie-list.component';

const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'cookies', component: CookieListComponent }
{ canActivate: [AuthGuard], path: 'cookies', component: CookieListComponent }
];

@NgModule({
@@ -0,0 +1,43 @@
import { TestBed, inject, getTestBed } from '@angular/core/testing';

import { AuthGuard } from './auth.guard';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';
import { HttpClientTestingModule } from '@angular/common/http/testing';

describe('AuthGuard', () => {
let injector: TestBed;
let authService: AuthService
let guard: AuthGuard;
let routeMock: any = { snapshot: {}};
let routeStateMock: any = { snapshot: {}, url: '/cookies'};
let routerMock = {navigate: jasmine.createSpy('navigate')}

beforeEach(() => {
TestBed.configureTestingModule({
providers: [
AuthGuard, { provide: Router, useValue: routerMock },
],
imports: [
HttpClientTestingModule
]
});
injector = getTestBed();
authService = injector.get(AuthService);
guard = injector.get(AuthGuard);
});

it('should be created', inject([AuthGuard], (guard: AuthGuard) => {
expect(guard).toBeTruthy();
}));

it('should redirect an unauthenticated user to the login route', () => {
expect(guard.canActivate(routeMock, routeStateMock)).toEqual(false);
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
});

it('should allow the authenticated user to access app', () => {
spyOn(authService, 'isLoggedIn').and.returnValue(true);
expect(guard.canActivate(routeMock, routeStateMock)).toEqual(true);
});
});
@@ -0,0 +1,30 @@
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';

import { AuthService } from './../services/auth.service';

@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {

constructor(private authService: AuthService, private router: Router) {}

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

let url: string = state.url;
return this.checkLogin(url);
}

private checkLogin(url: string): boolean {
if(this.authService.isLoggedIn()) {
return true;
}
this.authService.redirectToUrl = url;
this.router.navigate(['/login']);
return false;
}
}

0 comments on commit f9d82ce

Please sign in to comment.
You can’t perform that action at this time.