-
Notifications
You must be signed in to change notification settings - Fork 70
/
local-password-verify.provider.ts
68 lines (65 loc) · 2.15 KB
/
local-password-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
// Copyright (c) 2023 Sourcefuse Technologies
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
import {Provider} from '@loopback/context';
import {repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {AuthenticateErrorKeys, UserStatus} from '@sourceloop/core';
import {AuthErrorKeys, VerifyFunction} from 'loopback4-authentication';
import {Otp} from '../../../models';
import {
OtpRepository,
UserRepository,
UserTenantRepository,
} from '../../../repositories';
import {AuthUser} from '../models/auth-user.model';
export class LocalPasswordVerifyProvider
implements Provider<VerifyFunction.LocalPasswordFn>
{
constructor(
@repository(UserRepository)
public userRepository: UserRepository,
@repository(UserTenantRepository)
public utRepository: UserTenantRepository,
@repository(OtpRepository)
public otpRepository: OtpRepository,
) {}
value(): VerifyFunction.LocalPasswordFn {
return async (username: string, password: string) => {
try {
const user: AuthUser = new AuthUser(
await this.userRepository.verifyPassword(username, password),
);
user.permissions = [];
return user;
} catch (error) {
const otp: Otp = await this.otpRepository.get(username);
if (!otp || otp.otp !== password) {
throw new HttpErrors.Unauthorized(AuthErrorKeys.InvalidCredentials);
}
const user = await this.userRepository.findOne({
where: {username},
});
if (!user) {
throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientUserMissing);
}
const userTenant = await this.utRepository.findOne({
where: {
userId: user.id,
tenantId: user.defaultTenantId,
status: {
nin: [UserStatus.REJECTED, UserStatus.INACTIVE],
},
},
});
if (!userTenant) {
throw new HttpErrors.Unauthorized(AuthenticateErrorKeys.UserInactive);
}
const retUser = new AuthUser(user);
retUser.permissions = [];
return retUser;
}
};
}
}