This repository has been archived by the owner on Jan 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth-http-interceptor.ts
56 lines (45 loc) · 1.6 KB
/
auth-http-interceptor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { Injectable, Inject } from '@angular/core';
import { RequestOptionsArgs, Response } from '@angular/http';
import { IHttpInterceptor } from '@covalent/http';
import { Router } from '@angular/router';
import { JWT } from './jwt';
import { APP_CONFIG, AppConfig } from '../app.config';
const XAUTH_TOKEN_KEY = 'X-Auth-Token';
@Injectable()
export class AuthHttpInterceptor implements IHttpInterceptor {
constructor(
// @Inject(APP_CONFIG) config: AppConfig,
private _jwt: JWT,
private _router: Router
) { }
onRequest(requestOptions: RequestOptionsArgs): RequestOptionsArgs {
console.log('AuthHttpInterceptor::onRequest::' + requestOptions);
const token = this._jwt.get();
if (token) {
console.log('restoring token from local storage...::' + token);
requestOptions.headers.set(XAUTH_TOKEN_KEY, token);
}
return requestOptions;
}
onRequestError(requestOptions: RequestOptionsArgs): RequestOptionsArgs {
console.log('AuthHttpInterceptor::onRequestError::' + requestOptions);
return requestOptions;
}
onResponse(response: Response): Response {
console.log('AuthHttpInterceptor::onResponse::' + response);
const token = response.headers.get(XAUTH_TOKEN_KEY);
if (token) {
console.log('saving token to local storage...::' + token);
this._jwt.save(token);
}
return response;
}
onResponseError(response: Response): Response {
console.log('AuthHttpInterceptor::onResponseError::' + response);
if (response.status === 401) {
this._router.navigateByUrl('/auth/signin');
return null;
}
return response;
}
}