-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathuser-service.ts
356 lines (318 loc) · 13 KB
/
user-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
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/**
* SudoSOS back-end API service.
* Copyright (C) 2024 Study association GEWIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @license
*/
/**
* This is the module page of the user-service.
*
* @module users
*/
import { RequestWithToken } from '../middleware/token-middleware';
import { asBoolean, asDate, asNumber, asUserType } from '../helpers/validators';
import { PaginationParameters } from '../helpers/pagination';
import { PaginatedUserResponse, UserResponse } from '../controller/response/user-response';
import QueryFilter, { FilterMapping } from '../helpers/query-filter';
import User, { LocalUserTypes, TermsOfServiceStatus, TOSRequired, UserType } from '../entity/user/user';
import MemberAuthenticator from '../entity/authenticator/member-authenticator';
import { CreateUserRequest, UpdateUserRequest } from '../controller/request/user-request';
import TransactionService, { TransactionFilterParameters } from './transaction-service';
import {
FinancialMutationResponse,
PaginatedFinancialMutationResponse,
} from '../controller/response/financial-mutation-response';
import TransferService, { TransferFilterParameters } from './transfer-service';
import Mailer from '../mailer';
import WelcomeToSudosos from '../mailer/messages/welcome-to-sudosos';
import { AcceptTosRequest } from '../controller/request/accept-tos-request';
import Bindings from '../helpers/bindings';
import AuthenticationService from './authentication-service';
import WelcomeWithReset from '../mailer/messages/welcome-with-reset';
import { Brackets, In } from 'typeorm';
import BalanceService from './balance-service';
import AssignedRole from '../entity/rbac/assigned-role';
/**
* Parameters used to filter on Get Users functions.
*/
export interface UserFilterParameters {
search?: string,
active?: boolean,
ofAge?: boolean,
id?: number | number[],
deleted?: boolean,
type?: UserType,
organId?: number,
assignedRoleIds?: number | number[],
}
export type FinancialMutationsFilterParams = TransactionFilterParameters & TransferFilterParameters;
/**
* Extracts UserFilterParameters from the RequestWithToken
* @param req - Request to parse
*/
export function parseGetUsersFilters(req: RequestWithToken): UserFilterParameters {
let assignedRoleIds: number[];
if (req.query.assignedRoleIds && Array.isArray(req.query.assignedRoleIds)) {
assignedRoleIds = req.query.assignedRoleIds.map((r) => Number(r));
} else if (req.query.assignedRoleIds) {
assignedRoleIds = [Number(req.query.assignedRoleIds)];
}
return {
search: req.query.search as string,
active: req.query.active ? asBoolean(req.query.active) : undefined,
ofAge: req.query.active ? asBoolean(req.query.ofAge) : undefined,
id: asNumber(req.query.id),
assignedRoleIds,
organId: asNumber(req.query.organ),
deleted: req.query.active ? asBoolean(req.query.deleted) : false,
type: asUserType(req.query.type),
};
}
export function parseGetFinancialMutationsFilters(req: RequestWithToken): FinancialMutationsFilterParams {
return {
fromDate: asDate(req.query.fromDate),
tillDate: asDate(req.query.tillDate),
};
}
export default class UserService {
/**
* Function for getting al Users
* @param filters - Query filters to apply
* @param pagination - Pagination to adhere to
*/
public static async getUsers(
filters: UserFilterParameters = {}, pagination: PaginationParameters = {},
): Promise<PaginatedUserResponse> {
const { take, skip } = pagination;
const filterMapping: FilterMapping = {
active: 'active',
ofAge: 'ofAge',
id: 'id',
deleted: 'deleted',
type: 'type',
};
const f = filters;
if (filters.organId) {
// This allows us to search for organ members
const userIds = await MemberAuthenticator
.find({ where: { authenticateAs: { id: filters.organId } }, relations: ['user'] });
f.id = userIds.map((auth) => auth.user.id);
}
if (filters.assignedRoleIds) {
// Get all user IDs of the user belonging to any of the given roles
const assignedRoles = await AssignedRole
.find({ where: { roleId: In(filters.assignedRoleIds as number[]) } });
const userIds = assignedRoles.map((r) => r.userId);
if (f.id && Array.isArray(f.id)) {
// If we already have a list of IDs to filter on, we need to filter on the intersection
f.id = f.id.filter((id) => userIds.includes(id));
} else if (f.id) {
// If we only have a single ID to filter on, only keep it if it exists in one of the roles
f.id = userIds.includes(f.id as number) ? f.id : [];
} else {
// No existing filter on user ID, so we set the filter to the list of users in these groups
f.id = userIds;
}
}
const builder = Bindings.Users.getBuilder();
builder.where(`user.type NOT IN ("${UserType.POINT_OF_SALE}")`);
QueryFilter.applyFilter(builder, filterMapping, f);
// Note this is only for MySQL
if (filters.search) {
const searchTerms = filters.search.split(' ', 2);
if (searchTerms.length > 1) {
let searchTerm1 = `%${searchTerms[0]}%`;
let searchTerm2 = `%${searchTerms[1]}%`;
builder.andWhere(new Brackets(qb => {
qb.where('user.firstName LIKE :searchTerm1')
.orWhere('user.lastName LIKE :searchTerm2')
.orWhere('user.firstName LIKE :searchTerm2')
.orWhere('user.lastName LIKE :searchTerm1')
.orWhere('user.nickname LIKE :searchTerm2')
.orWhere('user.nickname LIKE :searchTerm1');
}), {
searchTerm1: searchTerm1,
searchTerm2: searchTerm2,
});
} else {
let searchTerm = `%${filters.search}%`;
builder.andWhere(new Brackets(qb => {
qb.where('user.firstName LIKE :search')
.orWhere('user.lastName LIKE :search')
.orWhere('user.nickname LIKE :search')
.orWhere('user.email LIKE :search');
}), {
search: searchTerm,
});
}
}
builder.orderBy('user.id', 'DESC');
const users = await builder.limit(take).offset(skip).getRawMany();
const count = await builder.getCount();
const records = users.map((u) => Bindings.Users.parseToResponse(u, true));
return {
_pagination: {
take, skip, count,
},
records,
};
}
/**
* Function for getting a single user based on ID
* @param id - ID of the user to return
* @returns User if exists
* @returns undefined if user does not exits
*/
public static async getSingleUser(id: number) {
const user = await this.getUsers({ id, deleted: false });
if (!user.records[0]) {
return undefined;
}
return user.records[0];
}
/**
* Function for creating a user
* @param createUserRequest - The user to create
* @returns The created user
*/
public static async createUser(createUserRequest: CreateUserRequest) {
// Check if user needs to accept TOS.
const acceptedToS = TOSRequired.includes(createUserRequest.type) ? TermsOfServiceStatus.NOT_ACCEPTED : TermsOfServiceStatus.NOT_REQUIRED;
const user = await User.save({
...createUserRequest,
lastName: createUserRequest.lastName || '',
acceptedToS,
} as User);
// Local users will receive a reset link.
if (LocalUserTypes.includes(user.type)) {
const resetTokenInfo = await new AuthenticationService().createResetToken(user);
Mailer.getInstance().send(user, new WelcomeWithReset({ email: user.email, resetTokenInfo })).then().catch((e) => {
throw e;
});
} else {
Mailer.getInstance().send(user, new WelcomeToSudosos({ })).then().catch((e) => {
throw e;
});
}
return Promise.resolve(this.getSingleUser(user.id));
}
/**
* Closes a user account by setting the user's status to deleted and inactive.
* Also, it sets canGoIntoDebt to false.
*
* @param {number} userId - The ID of the user to close the account for.
* @param deleted - Whether the user is being deleted or not.
* @throws Error if the user has a non-zero balance and is being deleted.
* @returns {Promise<void>} - A promise that resolves when the user account has been closed.
*/
public static async closeUser(userId: number, deleted = false): Promise<UserResponse> {
const user = await User.findOne({ where: { id: userId, deleted: false } });
if (!user) return undefined;
const balance = await new BalanceService().getBalance(userId);
const isZero = balance.amount.amount === 0;
if (deleted && !isZero) {
throw new Error('Cannot delete user with non-zero balance.');
}
user.deleted = deleted;
user.active = false;
user.canGoIntoDebt = false;
await user.save();
// Correctly parsed to expected response
return this.getUsers({ id: userId }).then((u) => u.records[0]);
}
/**
* Updates the user object with the new properties.
* @param userId - ID of the user to update.
* @param updateUserRequest - The update object.
*/
public static async updateUser(userId: number, updateUserRequest: UpdateUserRequest):
Promise<UserResponse> {
const user = await User.findOne({ where: { id: userId } });
if (!user) return undefined;
Object.assign(user, updateUserRequest);
await user.save();
return this.getSingleUser(userId);
}
/**
* Accept the ToS for the user with the given ID.
* @param userId - ID of the user to accept the ToS for.
* @param params
* @returns boolean - Whether the request has successfully been processed
*/
public static async acceptToS(userId: number, params: AcceptTosRequest): Promise<boolean> {
const user = await User.findOne({ where: { id: userId } });
if (!user) return false;
if (user.acceptedToS === TermsOfServiceStatus.ACCEPTED) return false;
user.acceptedToS = TermsOfServiceStatus.ACCEPTED;
user.extensiveDataProcessing = params.extensiveDataProcessing;
await user.save();
return true;
}
/**
* Combined query to return a users transfers and transactions from the database
* @param user - The user of which to get.
* @param filters - Filter parameters to adhere to
* @param paginationParameters - Pagination Parameters to adhere to.
*/
public static async getUserFinancialMutations(
user: User,
filters: FinancialMutationsFilterParams = {},
paginationParameters: PaginationParameters = {},
): Promise<PaginatedFinancialMutationResponse> {
// Since we are combining two different queries the pagination works a bit different.
const take = (paginationParameters.skip ?? 0) + (paginationParameters.take ?? 0);
const pagination: PaginationParameters = {
take,
skip: 0,
};
const transactions = await (new TransactionService()).getTransactions(filters, pagination, user);
const transfers = await (new TransferService()).getTransfers(filters, pagination, user);
const financialMutations: FinancialMutationResponse[] = [];
transactions.records.forEach((mutation) => {
financialMutations.push({ type: 'transaction', mutation });
});
transfers.records.forEach((mutation) => {
financialMutations.push({ type: 'transfer', mutation });
});
// Sort based on descending creation date.
financialMutations.sort((a, b) => (a.mutation.createdAt < b.mutation.createdAt ? 1 : -1));
// Apply pagination
const mutationRecords = financialMutations.slice(paginationParameters.skip,
paginationParameters.skip + paginationParameters.take);
return {
_pagination: {
take: paginationParameters.take ?? 0,
skip: paginationParameters.skip ?? 0,
// eslint-disable-next-line no-underscore-dangle
count: transactions._pagination.count + transfers._pagination.count,
},
records: mutationRecords,
};
}
/**
* Function that checks if the users have overlapping member authentications.
* @param left - User to check
* @param right - User to check
*/
public static async areInSameOrgan(left: number, right: number) {
const leftAuth = await MemberAuthenticator.find({ where: { user: { id: left } }, relations: ['authenticateAs'] });
const rightAuth = await MemberAuthenticator.find({ where: { user: { id: right } }, relations: ['authenticateAs'] });
const rightIds = leftAuth.map((u) => u.authenticateAs.id);
const overlap = rightAuth.map((u) => u.authenticateAs.id)
.filter((u) => rightIds.indexOf(u) !== -1);
return overlap.length > 0;
}
}