-
Notifications
You must be signed in to change notification settings - Fork 25
/
authentication.service.ts
69 lines (57 loc) · 2.27 KB
/
authentication.service.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from '@environments/environment';
import { User } from '@app/_models';
@Injectable({ providedIn: 'root' })
export class AuthenticationService {
private userSubject: BehaviorSubject<User>;
public user: Observable<User>;
constructor(
private router: Router,
private http: HttpClient
) {
this.userSubject = new BehaviorSubject<User>(null);
this.user = this.userSubject.asObservable();
}
public get userValue(): User {
return this.userSubject.value;
}
login(username: string, password: string) {
return this.http.post<any>(`${environment.apiUrl}/users/authenticate`, { username, password }, { withCredentials: true })
.pipe(map(user => {
this.userSubject.next(user);
this.startRefreshTokenTimer();
return user;
}));
}
logout() {
this.http.post<any>(`${environment.apiUrl}/users/revoke-token`, {}, { withCredentials: true }).subscribe();
this.stopRefreshTokenTimer();
this.userSubject.next(null);
this.router.navigate(['/login']);
}
refreshToken() {
return this.http.post<any>(`${environment.apiUrl}/users/refresh-token`, {}, { withCredentials: true })
.pipe(map((user) => {
this.userSubject.next(user);
this.startRefreshTokenTimer();
return user;
}));
}
// helper methods
private refreshTokenTimeout;
private startRefreshTokenTimer() {
// parse json object from base64 encoded jwt token
const jwtToken = JSON.parse(atob(this.userValue.jwtToken.split('.')[1]));
// set a timeout to refresh the token a minute before it expires
const expires = new Date(jwtToken.exp * 1000);
const timeout = expires.getTime() - Date.now() - (60 * 1000);
this.refreshTokenTimeout = setTimeout(() => this.refreshToken().subscribe(), timeout);
}
private stopRefreshTokenTimer() {
clearTimeout(this.refreshTokenTimeout);
}
}