-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathauth.graphql.custom.service.ts
64 lines (58 loc) · 1.56 KB
/
auth.graphql.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
58
59
60
61
62
63
64
import { inject, Injectable } from '@angular/core'
import { Apollo } from 'apollo-angular'
import { first, map, Observable } from 'rxjs'
import { $enum } from 'ts-enum-util'
import { IUser, User } from '../user/user/user'
import { Role } from './auth.enum'
import { GET_ME, LOGIN } from './auth.graphql.queries'
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 CustomGraphQLAuthService extends AuthService {
private apollo: Apollo = inject(Apollo)
protected authProvider(
email: string,
password: string
): Observable<IServerAuthResponse> {
return this.apollo
.mutate<{ login: IServerAuthResponse }>({
mutation: LOGIN,
variables: {
email,
password,
},
})
.pipe(
first(),
map((result) => result.data?.login as IServerAuthResponse)
)
}
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.apollo
.watchQuery<{ me: IUser }>({
query: GET_ME,
})
.valueChanges.pipe(
first(),
map((result) => User.Build(result.data.me))
)
}
}