Skip to content

Commit

Permalink
add auth guard
Browse files Browse the repository at this point in the history
  • Loading branch information
oxenprogrammer committed May 24, 2020
1 parent b39084a commit 03d0e90
Show file tree
Hide file tree
Showing 8 changed files with 132 additions and 36 deletions.
8 changes: 5 additions & 3 deletions src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { SmesComponent } from './components/smes/smes.component';
import { UserModule } from './components/user/user.module';
import { SignInComponent } from './components/sign-in/sign-in.component';
import { SmesDashboardComponent } from './components/smes-dashboard/smes-dashboard.component';

import { AuthGuardService as AuthGuard } from './services/auth-guard.service';

const routes: Routes = [
{
Expand All @@ -17,7 +17,8 @@ const routes: Routes = [
},
{
path: 'smes-dashboard',
component: SmesDashboardComponent
component: SmesDashboardComponent,
canActivate: [AuthGuard]
},
{ path: 'user', loadChildren: () => UserModule },
{
Expand All @@ -29,7 +30,8 @@ const routes: Routes = [
{ path: 'Smes', component: SmesComponent},
]
},
{ path: 'sign-in', component: SignInComponent}
{ path: 'sign-in', component: SignInComponent},
{ path: '**', redirectTo: '/' }
];


Expand Down
17 changes: 15 additions & 2 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { TokenInterceptor, ErrorInterceptor } from './services/token.interceptor';
import { SideNavService } from './shared/services/side-nav.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
Expand All @@ -23,7 +24,7 @@ import { AuthService } from './services/auth.service';
import { authReducers } from './store/state/user.state';
import { EffectsModule } from '@ngrx/effects';
import { AuthEffects } from './store/effects/auth.effects';
import { HttpClientModule } from '@angular/common/http';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment';
import { SideNavTogglerComponent } from './shared/components/side-nav-toggler/side-nav-toggler.component';
Expand Down Expand Up @@ -64,7 +65,19 @@ import { SideNavComponent } from './shared/components/side-nav/side-nav.componen
StoreDevtoolsModule.instrument({ maxAge: 25, logOnly: environment.production }),
],

providers: [AuthService, SideNavService],
providers: [
AuthService, SideNavService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})

Expand Down
58 changes: 29 additions & 29 deletions src/app/components/home-page/home-page.component.html
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
<div class="main">
<nav class="navbar navbar-expand-md navbar-dark bg-dark">
<a class="navbar-brand" href="#">U Business</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample04"
aria-controls="navbarsExample04" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<nav class="navbar navbar-expand-md navbar-dark bg-dark">
<a class="navbar-brand" href="#">U Business</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample04"
aria-controls="navbarsExample04" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>

<div class="collapse navbar-collapse" id="navbarsExample04">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Sign In </a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Create Account</a>
</li>
<div class="collapse navbar-collapse" id="navbarsExample04">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" [routerLink]="['/sign-in']">Log in</a>
</li>
<li class="nav-item">
<a class="nav-link" [routerLink]="['/user/sign-up']">Sign up</a>
</li>

</ul>
<form class="form-inline my-2 my-md-0">
<input class="form-control" type="text" placeholder="Search">
</form>
</div>
</nav>

<div class="jumbotron img-fluid">
<div class="header">
U Business
<span>Connecting Businesses to Opportunity</span>
</div>
</ul>
<form class="form-inline my-2 my-md-0">
<input class="form-control" type="text" placeholder="Search">
</form>
</div>
</nav>

<div class="jumbotron img-fluid">
<div class="header">
U Business
<span>Connecting Businesses to Opportunity</span>
</div>

</div>
</div>
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Router } from '@angular/router';
import { selectAuthState } from './../../store/state/user.state';
import { Observable } from 'rxjs';
import { Component, OnInit } from '@angular/core';
Expand All @@ -17,7 +18,7 @@ export class SmesDashboardComponent implements OnInit {
user = null;
errorMessage = null;

constructor(private store: Store<UserState>) {
constructor(private store: Store<UserState>, public router: Router) {
this.getState = this.store.select(selectAuthState);
}

Expand All @@ -31,6 +32,7 @@ export class SmesDashboardComponent implements OnInit {

logout(): void {
this.store.dispatch(new Logout());
this.router.navigateByUrl('/');
}

}
16 changes: 16 additions & 0 deletions src/app/services/auth-guard.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';

import { AuthGuardService } from './auth-guard.service';

describe('AuthGuardService', () => {
let service: AuthGuardService;

beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AuthGuardService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});
22 changes: 22 additions & 0 deletions src/app/services/auth-guard.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';

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

constructor(
public auth: AuthService,
public router: Router
) { }

canActivate(): boolean {
if (!this.auth.getToken()) {
this.router.navigateByUrl('/sign-in');
return false;
}
return true;
}
}
39 changes: 39 additions & 0 deletions src/app/services/token.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { catchError } from 'rxjs/operators';
import { Injectable, Injector } from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
private authService: AuthService;

constructor(private injector: Injector) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.authService = this.injector.get(AuthService);
const token = this.authService.getToken();
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
return next.handle(request);
}
}

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private router: Router) {}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(response => {
if (response instanceof HttpErrorResponse && response.status === 401) {}
return throwError(response);
})
);
}
}
4 changes: 3 additions & 1 deletion src/app/shared/components/navbar/navbar.component.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { Logout } from './../../../store/actions/auth.actions';
import { selectAuthState, UserState } from './../../../store/state/user.state';
Expand All @@ -17,7 +18,7 @@ export class NavbarComponent implements OnInit {
user = null;
errorMessage = null;

constructor(private store: Store<UserState>) {
constructor(private store: Store<UserState>, public router: Router) {
this.getState = this.store.select(selectAuthState);
}

Expand All @@ -31,6 +32,7 @@ export class NavbarComponent implements OnInit {

logout(): void {
this.store.dispatch(new Logout());
this.router.navigateByUrl('/');
}

}

0 comments on commit 03d0e90

Please sign in to comment.