Files
maptology/web/angular/src/app/auth.interceptor.ts
T
handte 852fb2ffd0
lbs-gitea/maptology/master This commit looks good
Fun with services, interceptors, di and forms.
2017-11-21 18:22:26 +01:00

58 lines
2.2 KiB
TypeScript

import {Injectable, Optional, Inject} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { HttpResponse } from '@angular/common/http';
import { Subject } from 'rxjs/Subject';
import { ConsoleService } from './console.service';
import { AuthService } from './auth.service';
import { Injector } from '@angular/core';
/**
* This interceptor intercepts http requests and attaches a
* basic auth header to them as long as the auth service is
* issuing them.
*/
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
/**
* The authentication service to get tokens.
*/
private authService: AuthService;
/**
* Creates a new interceptor with the injected console service
* and auth service.
*
* @param consoleService The console service for logging.
* @param authService The auth service to generate auth headers.
*/
constructor(private consoleService: ConsoleService, private injector: Injector) { }
/**
* Intercepts the requests and possibly attaches an auth header.
*
* @param req The request that is intercepted.
* @param next The handler to continue the request.
*/
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.authService == null) {
// this is dumb, but by using http service in the
// auth service (indirectly through ApiClientService)
// there will be a cyclic dependency between:
// ApiClientService -> HttpClient -> AuthInterceptor -> AuthSerivce -> ApiClientService
// but it can be resolved at runtime (see https://github.com/angular/angular/issues/18224)
this.authService = this.injector.get(AuthService);
}
let authHeader = this.authService.getHeader();
let clone = req;
if (authHeader != null) {
this.consoleService.log("Attaching Authorization header.");
clone = req.clone({ headers: req.headers.set("Authorization", authHeader)});
} else {
this.consoleService.log("Skipping Authorization header.");
}
return next.handle(clone);
}
}