-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathauth.service.ts
More file actions
90 lines (70 loc) · 2.17 KB
/
auth.service.ts
File metadata and controls
90 lines (70 loc) · 2.17 KB
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
import { UtilsService } from './../../shared/services/utils.service';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { environment } from '@env/environment';
import { Observable, throwError, BehaviorSubject } from 'rxjs';
import { UserResponse, User } from '@shared/models/user.interface';
import { catchError, map } from 'rxjs/operators';
import { JwtHelperService } from '@auth0/angular-jwt';
const helper = new JwtHelperService();
@Injectable({
providedIn: 'root',
})
export class AuthService {
private user = new BehaviorSubject<UserResponse>(null);
constructor(
private http: HttpClient,
private router: Router,
private utilsSvc: UtilsService
) {
this.checkToken();
}
get user$(): Observable<UserResponse> {
return this.user.asObservable();
}
get userValue(): UserResponse {
return this.user.getValue();
}
login(authData: User): Observable<UserResponse | void> {
return this.http
.post<UserResponse>(`${environment.API_URL}/auth/login`, authData)
.pipe(
map((user: UserResponse) => {
this.saveLocalStorage(user);
this.user.next(user);
return user;
}),
catchError((err) => this.handlerError(err))
);
}
logout(): void {
localStorage.removeItem('user');
this.user.next(null);
this.utilsSvc.openSidebar(false);
this.router.navigate(['/login']);
}
private checkToken(): void {
const user = JSON.parse(localStorage.getItem('user')) || null;
if (user) {
const isExpired = helper.isTokenExpired(user.token);
if (isExpired) {
this.logout();
} else {
this.user.next(user);
}
}
}
private saveLocalStorage(user: UserResponse): void {
const { userId, message, ...rest } = user;
localStorage.setItem('user', JSON.stringify(rest));
}
private handlerError(err): Observable<never> {
let errorMessage = 'An errror occured retrienving data';
if (err) {
errorMessage = `Error: code ${err.message}`;
}
window.alert(errorMessage);
return throwError(errorMessage);
}
}