[frontend] Add access token interceptor

This commit is contained in:
Cathy Hu 2020-08-17 19:32:23 +02:00
parent e5c6f14973
commit dcea411f5b
7 changed files with 63 additions and 57 deletions

View file

@ -10,12 +10,13 @@ import { DashboardModule } from './dashboard/dashboard.module';
import { HoodpageComponent } from './hoodpage/hoodpage.component'; import { HoodpageComponent } from './hoodpage/hoodpage.component';
import { HoodspageComponent } from './hoodspage/hoodspage.component'; import { HoodspageComponent } from './hoodspage/hoodspage.component';
import { ApiModule } from './core/api/api.module'; import { ApiModule } from './core/api/api.module';
import { HttpClientModule } from '@angular/common/http'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BASE_PATH } from './core/api/variables'; import { BASE_PATH } from './core/api/variables';
import { environment } from 'src/environments/environment'; import { environment } from 'src/environments/environment';
import { LoginComponent } from './login/login.component'; import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component'; import { RegisterComponent } from './register/register.component';
import { ReactiveFormsModule } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms';
import { AuthTokenInterceptor } from './core/auth/auth-token.interceptor';
@NgModule({ @NgModule({
declarations: [ declarations: [
@ -36,7 +37,10 @@ import { ReactiveFormsModule } from '@angular/forms';
HttpClientModule, HttpClientModule,
ReactiveFormsModule, ReactiveFormsModule,
], ],
providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], providers: [
{ provide: BASE_PATH, useValue: environment.API_BASE_PATH },
{ provide: HTTP_INTERCEPTORS, useClass: AuthTokenInterceptor, multi: true },
],
bootstrap: [AppComponent], bootstrap: [AppComponent],
}) })
export class AppModule {} export class AppModule {}

View file

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

View file

@ -1,26 +0,0 @@
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class AuthTokenInterceptorService {
constructor() {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
// const token = this.loginService.token;
// if (token) {
// req = req.clone({
// setHeaders: {
// Authorization: 'Bearer ' + this.loginService.token,
// },
// });
// }
return next.handle(req);
}
}

View file

@ -0,0 +1,18 @@
import { TestBed } from '@angular/core/testing';
import { AuthTokenInterceptor } from './auth-token.interceptor';
describe('AuthTokenInterceptor', () => {
beforeEach(() =>
TestBed.configureTestingModule({
providers: [AuthTokenInterceptor],
})
);
it('should be created', () => {
const interceptor: AuthTokenInterceptor = TestBed.inject(
AuthTokenInterceptor
);
expect(interceptor).toBeTruthy();
});
});

View file

@ -0,0 +1,29 @@
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { LoginService } from './login.service';
@Injectable()
export class AuthTokenInterceptor implements HttpInterceptor {
constructor(private loginService: LoginService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token = this.loginService.currentHoodAdminValue;
if (token) {
request = request.clone({
setHeaders: {
Authorization: 'Bearer ' + token,
},
});
}
return next.handle(request);
}
}

View file

@ -1,18 +1,19 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs'; import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
import { AdminService } from '../api'; import { AdminService, BodyAccessToken } from '../api';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class LoginService { export class LoginService {
private currentHoodAdminSubject: BehaviorSubject<any>; private currentHoodAdminSubject: BehaviorSubject<BodyAccessToken>;
public currentHoodAdmin: Observable<any>; public currentHoodAdmin: Observable<BodyAccessToken>;
private identifier = 'currentHoodAdmin';
constructor(private readonly adminService: AdminService) { constructor(private readonly adminService: AdminService) {
this.currentHoodAdminSubject = new BehaviorSubject<any>( this.currentHoodAdminSubject = new BehaviorSubject<BodyAccessToken>(
JSON.parse(localStorage.getItem('currentHoodAdmin')) JSON.parse(localStorage.getItem(this.identifier))
); );
this.currentHoodAdmin = this.currentHoodAdminSubject.asObservable(); this.currentHoodAdmin = this.currentHoodAdminSubject.asObservable();
} }
@ -24,7 +25,7 @@ export class LoginService {
login(email, password) { login(email, password) {
return this.adminService.login(email, password).pipe( return this.adminService.login(email, password).pipe(
map((response) => { map((response) => {
localStorage.setItem('currentHoodAdmin', JSON.stringify(response)); localStorage.setItem(this.identifier, JSON.stringify(response));
this.currentHoodAdminSubject.next(response); this.currentHoodAdminSubject.next(response);
return response; return response;
}) })
@ -32,7 +33,7 @@ export class LoginService {
} }
logout() { logout() {
localStorage.removeItem('currentHoodAdmin'); localStorage.removeItem(this.identifier);
this.currentHoodAdminSubject.next(null); this.currentHoodAdminSubject.next(null);
} }
} }

View file

@ -4,12 +4,8 @@ import { HoodsComponent } from './hoods/hoods.component';
import { SettingspageComponent } from './settingspage/settingspage.component'; import { SettingspageComponent } from './settingspage/settingspage.component';
import { DashboardComponent } from './dashboard.component'; import { DashboardComponent } from './dashboard.component';
@NgModule({ @NgModule({
declarations: [HoodsComponent, SettingspageComponent, DashboardComponent], declarations: [HoodsComponent, SettingspageComponent, DashboardComponent],
imports: [ imports: [CommonModule],
CommonModule
]
}) })
export class DashboardModule { } export class DashboardModule {}