Skip to content

Commit

Permalink
Added auth interceptor.
Browse files Browse the repository at this point in the history
  • Loading branch information
StevenEddies committed Feb 10, 2022
1 parent 570cd15 commit 95e5c65
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
7 changes: 5 additions & 2 deletions edc-frontend/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MatTabsModule } from '@angular/material/tabs';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
Expand All @@ -23,6 +23,7 @@ import { TodaySummaryCardComponent } from './components/today-summary-card/today
import { AchievementCardComponent } from './components/achievement-card/achievement-card.component';
import { StreakPageComponent } from './components/streak-page/streak-page.component';
import { LoginPageComponent } from './components/login-page/login-page.component';
import { BasicAuthInterceptor } from './services/auth/auth-interceptor';

@NgModule({
declarations: [
Expand Down Expand Up @@ -50,7 +51,9 @@ import { LoginPageComponent } from './components/login-page/login-page.component
MatToolbarModule,
ReactiveFormsModule
],
providers: [],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: BasicAuthInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule {
Expand Down
24 changes: 24 additions & 0 deletions edc-frontend/src/app/services/auth/auth-interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

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

@Injectable()
export class BasicAuthInterceptor implements HttpInterceptor {

constructor(private authService: AuthService) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Assume all calls are to our API
const user = this.authService.getUserValue();
if (user != null) {
request = request.clone({
setHeaders: {
Authorization: 'Basic ' + btoa(user.username + ':' + user.password)
}
});
}
return next.handle(request);
}
}

0 comments on commit 95e5c65

Please sign in to comment.