Newer
Older
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
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Store } from '@ngrx/store';
import { BehaviorSubject, Observable, timer } from 'rxjs';
import { tap } from 'rxjs/operators';
import { TryRefreshToken } from '../store/actions/auth.actions';
import { JWToken } from '../models/JWToken.model';
import { User } from '../models/user.model';
import { State } from '../store';
@Injectable({
providedIn: 'root'
})
export class AuthService {
public JWToken: BehaviorSubject<JWToken> = new BehaviorSubject({
isAuthenticated: null,
token: null
});
constructor(
private http: HttpClient,
private store: Store<State>
) {
this.initToken();
}
private initToken(): void {
const token = localStorage.getItem('jwt');
if (token) {
this.JWToken.next({
isAuthenticated: true,
token: token
});
} else {
this.JWToken.next({
isAuthenticated: false,
token: null
});
}
}
public initRefreshToken() {
return timer(5000, 10000).pipe(
tap(() => this.store.dispatch(new TryRefreshToken()))
);
}
public refreshToken(): Observable<string> {
return this.http.get<string>('/api/auth/refresh_token');
}
public signup(user: User): Observable<User> {
return this.http.post<User>('/api/auth/signup', user);
}
public signin(credentials: { email: string, password: string}): Observable<string> {
return this.http.post<string>('/api/auth/signin', credentials);
}
}