-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathauth.custom.service.ts
57 lines (51 loc) · 1.54 KB
/
auth.custom.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
import { HttpClient } from '@angular/common/http'
import { inject, Injectable } from '@angular/core'
import { Observable } from 'rxjs'
import { catchError, first, map } from 'rxjs/operators'
import { $enum } from 'ts-enum-util'
import { environment } from '../../environments/environment'
import { transformError } from '../common/common'
import { IUser, User } from '../user/user/user'
import { Role } from './auth.enum'
import { AuthService, IAuthStatus, IServerAuthResponse } from './auth.service'
interface IJwtToken {
email: string
role: string
picture: string
iat: number
exp: number
sub: string
}
@Injectable({
providedIn: 'root',
})
export class CustomAuthService extends AuthService {
private httpClient: HttpClient = inject(HttpClient)
protected authProvider(
email: string,
password: string
): Observable<IServerAuthResponse> {
return this.httpClient
.post<IServerAuthResponse>(`${environment.baseUrl}/v1/auth/login`, {
email,
password,
})
.pipe(first())
}
protected transformJwtToken(token: IJwtToken): IAuthStatus {
return {
isAuthenticated: token.email ? true : false,
userId: token.sub,
userRole: $enum(Role).asValueOrDefault(token.role, Role.None),
userEmail: token.email,
userPicture: token.picture,
} as IAuthStatus
}
protected getCurrentUser(): Observable<User> {
return this.httpClient.get<IUser>(`${environment.baseUrl}/v1/auth/me`).pipe(
first(),
map((user) => User.Build(user)),
catchError(transformError)
)
}
}