-
Notifications
You must be signed in to change notification settings - Fork 70
/
keycloak-verify.provider.ts
88 lines (85 loc) · 2.66 KB
/
keycloak-verify.provider.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright (c) 2023 Sourcefuse Technologies
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
import {inject, Provider} from '@loopback/context';
import {repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {
AuthErrorKeys,
IAuthUser,
Keycloak,
VerifyFunction,
} from 'loopback4-authentication';
import {SignUpBindings, VerifyBindings} from '../../../providers/keys';
import {
KeyCloakPostVerifyFn,
KeyCloakPreVerifyFn,
KeyCloakSignUpFn,
} from '../../../providers/types';
import {UserCredentialsRepository, UserRepository} from '../../../repositories';
import {AuthUser} from '../models/auth-user.model';
export class KeycloakVerifyProvider
implements Provider<VerifyFunction.KeycloakAuthFn>
{
constructor(
@repository(UserRepository)
public userRepository: UserRepository,
@repository(UserCredentialsRepository)
public userCredsRepository: UserCredentialsRepository,
@inject(SignUpBindings.KEYCLOAK_SIGN_UP_PROVIDER)
private readonly signupProvider: KeyCloakSignUpFn,
@inject(VerifyBindings.KEYCLOAK_PRE_VERIFY_PROVIDER)
private readonly preVerifyProvider: KeyCloakPreVerifyFn,
@inject(VerifyBindings.KEYCLOAK_POST_VERIFY_PROVIDER)
private readonly postVerifyProvider: KeyCloakPostVerifyFn,
) {}
value(): VerifyFunction.KeycloakAuthFn {
return async (
accessToken: string,
refreshToken: string,
profile: Keycloak.Profile,
) => {
let user: IAuthUser | null = await this.userRepository.findOne({
where: {
email: profile.email,
},
});
user = await this.preVerifyProvider(
accessToken,
refreshToken,
profile,
user,
);
if (!user) {
const newUser = await this.signupProvider(profile);
if (newUser) {
user = newUser;
} else {
throw new HttpErrors.Unauthorized(AuthErrorKeys.InvalidCredentials);
}
}
const creds = await this.userCredsRepository.findOne({
where: {
userId: user.id as string,
},
});
if (
!creds ||
creds.authProvider !== 'keycloak' ||
(creds.authId !== profile.keycloakId &&
creds.authId !== profile.username)
) {
throw new HttpErrors.Unauthorized(AuthErrorKeys.InvalidCredentials);
}
const authUser: AuthUser = new AuthUser({
...user,
id: user.id as string,
});
authUser.permissions = [];
authUser.externalAuthToken = accessToken;
authUser.externalRefreshToken = refreshToken;
return this.postVerifyProvider(profile, authUser);
};
}
}