/
authentication.service.ts
96 lines (88 loc) · 2.83 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { Http, Headers } from '@angular/http';
import { BehaviorSubject } from 'rxjs/Rx';
import { ConfigurationService } from './configuration.service';
@Injectable()
export class AuthenticationService {
public isAuthenticated: BehaviorSubject<any> = new BehaviorSubject({ state: false });
constructor(
private config: ConfigurationService,
private http: Http,
@Inject(PLATFORM_ID) private platformId: Object,
) {
if (isPlatformBrowser(this.platformId)) {
let token = localStorage.getItem('auth');
let lastLogin = localStorage.getItem('auth_time');
// token expires after 12 hours
const expire = 12 * 60 * 60 * 1000;
if (!lastLogin || (Date.now() - Date.parse(lastLogin) > expire)) {
localStorage.removeItem('auth');
token = null;
}
if (token) {
this.isAuthenticated.next({ state: true });
}
}
}
getUserInfo() {
if (isPlatformBrowser(this.platformId)) {
let token = localStorage.getItem('auth');
if (token) {
let tokenParts = token.split('.');
return JSON.parse(atob(tokenParts[1]));
} else {
return null;
}
}
}
login(login: string, password: string) {
if (isPlatformBrowser(this.platformId)) {
let headers = this.getHeaders();
let body = JSON.stringify({
login: login,
password: password
});
this.http.post(
this.config.get('BACKEND_URL') + '/@login', body, { headers: headers })
.subscribe(
res => {
let data = res.json();
if (data.token) {
localStorage.setItem('auth', data.token);
localStorage.setItem('auth_time', (new Date()).toISOString());
this.isAuthenticated.next({ state: true });
} else {
localStorage.removeItem('auth');
localStorage.removeItem('auth_time');
this.isAuthenticated.next({ state: false });
}
},
err => {
localStorage.removeItem('auth');
localStorage.removeItem('auth_time');
this.isAuthenticated.next({ state: false, error: err.json().error });
}
);
}
}
logout() {
if (isPlatformBrowser(this.platformId)) {
localStorage.removeItem('auth');
localStorage.removeItem('auth_time');
this.isAuthenticated.next({ state: false });
}
}
getHeaders(): Headers {
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
if (isPlatformBrowser(this.platformId)) {
let auth = localStorage.getItem('auth');
if (auth) {
headers.append('Authorization', 'Bearer ' + auth);
}
}
return headers;
}
}