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
|
import { HttpClient } from '@angular/common/http';
import { computed, inject, Injectable, signal } from '@angular/core';
import { environment } from 'src/environments/environment';
import { catchError, map, Observable, of, tap } from 'rxjs';
import { rxResource } from '@angular/core/rxjs-interop';
import { AuthResponse } from '@auth/interfaces/auth-response.interface';
import { User } from '@auth/interfaces/user.interface';
type AuthStatus = 'checking' | 'authenticated' | 'not-authenticated';
const baseUrl = environment.baseUrl;
@Injectable({ providedIn: 'root' })
export class AuthService {
private _authStatus = signal<AuthStatus>('checking');
private _user = signal<User | null>(null);
private _token = signal<string | null>(localStorage.getItem('token'));
private http = inject(HttpClient);
checkStatusResource = rxResource({
stream: () => this.checkStatus(),
});
authStatus = computed<AuthStatus>(() => {
if (this._authStatus() === 'checking') return 'checking';
if (this._user()) {
return 'authenticated';
}
return 'not-authenticated';
});
user = computed(() => this._user());
token = computed(this._token);
isAdmin = computed(() => this._user()?.roles.includes('admin') ?? false);
login(email: string, password: string): Observable<boolean> {
return this.http
.post<AuthResponse>(`${baseUrl}/auth/login`, {
email: email,
password: password,
})
.pipe(
map((resp) => this.handleAuthSuccess(resp)),
catchError((error: any) => this.handleAuthError(error))
);
}
checkStatus(): Observable<boolean> {
const token = localStorage.getItem('token');
if (!token) {
this.logout();
return of(false);
}
return this.http
.get<AuthResponse>(`${baseUrl}/auth/check-status`, {
// headers: {
// Authorization: `Bearer ${token}`,
// },
})
.pipe(
map((resp) => this.handleAuthSuccess(resp)),
catchError((error: any) => this.handleAuthError(error))
);
}
logout() {
this._user.set(null);
this._token.set(null);
this._authStatus.set('not-authenticated');
localStorage.removeItem('token');
}
private handleAuthSuccess({ token, user }: AuthResponse) {
this._user.set(user);
this._authStatus.set('authenticated');
this._token.set(token);
localStorage.setItem('token', token);
return true;
}
private handleAuthError(error: any) {
this.logout();
return of(false);
}
}
|