-
Notifications
You must be signed in to change notification settings - Fork 70
/
jwt-payload.provider.ts
149 lines (138 loc) · 4.52 KB
/
jwt-payload.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// Copyright (c) 2023 Sourcefuse Technologies
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
import {inject, Provider} from '@loopback/core';
import {AnyObject, repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {
AuthenticateErrorKeys,
ConfigKey,
getAge,
ILogger,
LOGGER,
} from '@sourceloop/core';
import {AuthErrorKeys, IAuthClient, IAuthUser} from 'loopback4-authentication';
import {
AuthorizationBindings,
UserPermissionsFn,
} from 'loopback4-authorization';
import {User, UserTenant} from '../models';
import {AuthUser} from '../modules/auth';
import {
RoleRepository,
TenantConfigRepository,
UserLevelPermissionRepository,
UserTenantRepository,
} from '../repositories';
import {JwtPayloadFn} from './types';
export class JwtPayloadProvider implements Provider<JwtPayloadFn> {
constructor(
@repository(RoleRepository)
private readonly roleRepo: RoleRepository,
@repository(UserLevelPermissionRepository)
private readonly utPermsRepo: UserLevelPermissionRepository,
@repository(UserTenantRepository)
private readonly userTenantRepo: UserTenantRepository,
@repository(TenantConfigRepository)
private readonly tenantConfigRepo: TenantConfigRepository,
@inject(AuthorizationBindings.USER_PERMISSIONS)
private readonly getUserPermissions: UserPermissionsFn<string>,
@inject(LOGGER.LOGGER_INJECT) private readonly logger: ILogger,
) {}
value() {
return async (
authUserData: IAuthUser,
authClient: IAuthClient,
tenantId?: string,
) => {
const user = authUserData as User;
const userTenant = await this.userTenantRepo.findOne({
where: {
userId: (user as User).id, //NOSONAR
tenantId: tenantId ?? user.defaultTenantId,
},
});
if (!userTenant) {
throw new HttpErrors.Unauthorized(
AuthenticateErrorKeys.UserDoesNotExist,
);
}
if (
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
user.authClientIds.indexOf(authClient.id ?? 0) < 0
) {
throw new HttpErrors.Unauthorized(AuthErrorKeys.ClientInvalid);
}
delete user.authClientIds;
// Create user DTO for payload to JWT
const authUser: AuthUser = new AuthUser({...user});
this._removeUnnecessaryData(authUser);
// Add locale info
await this._setLocale(authUser, userTenant);
authUser.tenantId = userTenant.tenantId;
authUser.userTenantId = userTenant.id;
authUser.status = userTenant.status;
const role = await this.roleRepo.findById(userTenant.roleId);
if (!role) {
this.logger.error('Role not found for the user');
throw new HttpErrors.UnprocessableEntity(
AuthenticateErrorKeys.UnprocessableData,
);
}
const utPerms = await this.utPermsRepo.find({
where: {
userTenantId: userTenant.id,
},
fields: {
permission: true,
allowed: true,
},
});
authUser.permissions = this.getUserPermissions(utPerms, role.permissions);
authUser.role = role.name;
if (authUser.dob) {
const age = getAge(new Date(authUser.dob));
authUser.age = age;
}
return authUser.toJSON();
};
}
private _removeUnnecessaryData(authUser: AnyObject) {
delete authUser.externalAuthToken;
delete authUser.externalRefreshToken;
delete authUser.createdBy;
delete authUser.createdOn;
delete authUser.deleted;
delete authUser.deletedBy;
delete authUser.deletedOn;
delete authUser.modifiedBy;
delete authUser.modifiedOn;
return authUser;
}
private async _setLocale(authUser: AuthUser, userTenant: UserTenant) {
if (userTenant.locale && userTenant.locale.length > 0) {
// Use locale from user preferences first
authUser.userPreferences = {locale: userTenant.locale};
} else {
// Use tenant config locale at second priority
const config = await this.tenantConfigRepo.findOne({
where: {
configKey: ConfigKey.Profile,
},
});
// Use locale from environment as fallback overall
let locale = process.env.LOCALE ?? 'en';
if (config?.configValue) {
// sonarignore:start
// eslint-disable-next-line @typescript-eslint/no-explicit-any
locale = (config.configValue as any).locale;
// sonarignore:end
}
authUser.userPreferences = {
locale,
};
}
}
}