-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathauthentication-controller.ts
585 lines (527 loc) · 19.6 KB
/
authentication-controller.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/**
* 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 authentication-controller.
*
* @module authentication
*/
import { Request, Response } from 'express';
import log4js, { Logger } from 'log4js';
import BaseController, { BaseControllerOptions } from './base-controller';
import Policy from './policy';
import User, { UserType } from '../entity/user/user';
import AuthenticationMockRequest from './request/authentication-mock-request';
import TokenHandler from '../authentication/token-handler';
import AuthenticationService, { AuthenticationContext } from '../service/authentication-service';
import AuthenticationLDAPRequest from './request/authentication-ldap-request';
import RoleManager from '../rbac/role-manager';
import { LDAPUser } from '../helpers/ad';
import AuthenticationLocalRequest from './request/authentication-local-request';
import PinAuthenticator from '../entity/authenticator/pin-authenticator';
import AuthenticationPinRequest from './request/authentication-pin-request';
import LocalAuthenticator from '../entity/authenticator/local-authenticator';
import ResetLocalRequest from './request/reset-local-request';
import AuthenticationResetTokenRequest from './request/authentication-reset-token-request';
import AuthenticationEanRequest from './request/authentication-ean-request';
import EanAuthenticator from '../entity/authenticator/ean-authenticator';
import Mailer from '../mailer';
import PasswordReset from '../mailer/messages/password-reset';
import AuthenticationNfcRequest from './request/authentication-nfc-request';
import NfcAuthenticator from '../entity/authenticator/nfc-authenticator';
import AuthenticationKeyRequest from './request/authentication-key-request';
import KeyAuthenticator from '../entity/authenticator/key-authenticator';
import { AppDataSource } from '../database/database';
/**
* The authentication controller is responsible for:
* - Verifying user authentications.
* - Handing out json web tokens.
*/
export default class AuthenticationController extends BaseController {
/**
* Reference to the logger instance.
*/
private logger: Logger = log4js.getLogger('AuthenticationController');
/**
* Reference to the token handler of the application.
*/
protected tokenHandler: TokenHandler;
/**
* Creates a new authentication controller instance.
* @param options - The options passed to the base controller.
* @param tokenHandler - The token handler for creating signed tokens.
*/
public constructor(
options: BaseControllerOptions,
tokenHandler: TokenHandler,
) {
super(options);
this.logger.level = process.env.LOG_LEVEL;
this.tokenHandler = tokenHandler;
}
/**
* @inheritdoc
*/
public getPolicy(): Policy {
return {
'/mock': {
POST: {
body: { modelName: 'AuthenticationMockRequest' },
policy: AuthenticationController.canPerformMock.bind(this),
handler: this.mockLogin.bind(this),
},
},
'/LDAP': {
POST: {
body: { modelName: 'AuthenticationLDAPRequest' },
policy: async () => true,
handler: this.LDAPLogin.bind(this),
},
},
'/pin': {
POST: {
body: { modelName: 'AuthenticationPinRequest' },
policy: async () => true,
handler: this.PINLogin.bind(this),
},
},
'/nfc': {
POST: {
body: { modelName: 'AuthenticationNfcRequest' },
policy: async () => true,
handler: this.nfcLogin.bind(this),
},
},
'/key': {
POST: {
body: { modelName: 'AuthenticationKeyRequest' },
policy: async () => true,
handler: this.keyLogin.bind(this),
},
},
'/local': {
POST: {
body: { modelName: 'AuthenticationLocalRequest' },
policy: async () => true,
handler: this.LocalLogin.bind(this),
restrictions: { availableDuringMaintenance: true },
},
PUT: {
body: { modelName: 'AuthenticationResetTokenRequest' },
policy: async () => true,
handler: this.resetLocalUsingToken.bind(this),
},
},
'/local/reset': {
POST: {
body: { modelName: 'ResetLocalRequest' },
policy: async () => true,
handler: this.createResetToken.bind(this),
},
},
'/ean': {
POST: {
body: { modelName: 'AuthenticationEanRequest' },
policy: async () => true,
handler: this.eanLogin.bind(this),
},
},
};
}
/**
* Validates that the request is authorized by the policy.
* @param req - The incoming request.
*/
static async canPerformMock(req: Request): Promise<boolean> {
const body = req.body as AuthenticationMockRequest;
// Only allow in development setups
if (process.env.NODE_ENV !== 'development' && process.env.NODE_ENV !== 'test') return false;
// Check the existence of the user
const user = await User.findOne({ where: { id: body.userId } });
if (!user) return false;
return true;
}
/**
* POST /authentication/pin
* @summary PIN login and hand out token
* @operationId pinAuthentication
* @tags authenticate - Operations of authentication controller
* @param {AuthenticationPinRequest} request.body.required - The PIN login.
* @return {AuthenticationResponse} 200 - The created json web token.
* @return {string} 400 - Validation error.
* @return {string} 403 - Authentication error.
*/
public async PINLogin(req: Request, res: Response): Promise<void> {
const body = req.body as AuthenticationPinRequest;
this.logger.trace('PIN authentication for user', body.userId);
try {
await (AuthenticationController.PINLoginConstructor(this.roleManager,
this.tokenHandler, body.pin, body.userId))(req, res);
} catch (error) {
this.logger.error('Could not authenticate using PIN:', error);
res.status(500).json('Internal server error.');
}
}
/**
* Construct a login function for PIN.
* This was done such that it is easily adaptable.
* @param roleManager
* @param tokenHandler
* @param pin - Provided PIN code
* @param userId - Provided User
* @constructor
*/
public static PINLoginConstructor(roleManager: RoleManager, tokenHandler: TokenHandler,
pin: string, userId: number) {
return async (req: Request, res: Response) => {
const user = await User.findOne({
where: { id: userId, deleted: false },
});
if (!user) {
res.status(403).json({
message: 'Invalid credentials.',
});
return;
}
const pinAuthenticator = await PinAuthenticator.findOne({ where: { user: { id: user.id } }, relations: ['user'] });
if (!pinAuthenticator) {
res.status(403).json({
message: 'Invalid credentials.',
});
return;
}
const context: AuthenticationContext = {
roleManager,
tokenHandler,
};
const result = await new AuthenticationService().HashAuthentication(pin,
pinAuthenticator, context, true);
if (!result) {
res.status(403).json({
message: 'Invalid credentials.',
});
}
res.json(result);
};
}
/**
* POST /authentication/LDAP
* @summary LDAP login and hand out token
* If user has never signed in before this also creates an account.
* @operationId ldapAuthentication
* @tags authenticate - Operations of authentication controller
* @param {AuthenticationLDAPRequest} request.body.required - The LDAP login.
* @return {AuthenticationResponse} 200 - The created json web token.
* @return {string} 400 - Validation error.
* @return {string} 403 - Authentication error.
*/
public async LDAPLogin(req: Request, res: Response): Promise<void> {
const body = req.body as AuthenticationLDAPRequest;
this.logger.trace('LDAP authentication for user', body.accountName);
try {
await AppDataSource.transaction(async (manager) => {
const service = new AuthenticationService(manager);
await AuthenticationController.LDAPLoginConstructor(this.roleManager, this.tokenHandler, service.createUserAndBind.bind(service))(req, res);
});
} catch (error) {
this.logger.error('Could not authenticate using LDAP:', error);
res.status(500).json('Internal server error.');
}
}
/**
* Constructor for the LDAP function to make it easily adaptable.
* @constructor
*/
public static LDAPLoginConstructor(roleManager: RoleManager, tokenHandler: TokenHandler,
onNewUser: (ADUser: LDAPUser) => Promise<User>) {
return async (req: Request, res: Response) => {
const service = new AuthenticationService();
const body = req.body as AuthenticationLDAPRequest;
const user = await service.LDAPAuthentication(
body.accountName, body.password, onNewUser,
);
// If user is undefined something went wrong.
if (!user) {
res.status(403).json({
message: 'Invalid credentials.',
});
return;
}
const context: AuthenticationContext = {
roleManager,
tokenHandler,
};
// AD login gives full access.
const token = await service.getSaltedToken(user, context, false);
res.json(token);
};
}
/**
* POST /authentication/local
* @summary Local login and hand out token
* @operationId localAuthentication
* @tags authenticate - Operations of authentication controller
* @param {AuthenticationLocalRequest} request.body.required - The local login.
* @return {AuthenticationResponse} 200 - The created json web token.
* @return {string} 400 - Validation error.
* @return {string} 403 - Authentication error.
*/
public async LocalLogin(req: Request, res: Response): Promise<void> {
const body = req.body as AuthenticationLocalRequest;
this.logger.trace('Local authentication for user', body.accountMail);
try {
const user = await User.findOne({
where: { email: body.accountMail, deleted: false },
});
if (!user) {
res.status(403).json({
message: 'Invalid credentials.',
});
return;
}
const localAuthenticator = await LocalAuthenticator.findOne({ where: { user: { id: user.id } }, relations: ['user'] });
if (!localAuthenticator) {
res.status(403).json({
message: 'Invalid credentials.',
});
return;
}
const context: AuthenticationContext = {
roleManager: this.roleManager,
tokenHandler: this.tokenHandler,
};
const result = await new AuthenticationService().HashAuthentication(body.password,
localAuthenticator, context, false);
if (!result) {
res.status(403).json({
message: 'Invalid credentials.',
});
}
res.json(result);
} catch (error) {
this.logger.error('Could not authenticate using Local:', error);
res.status(500).json('Internal server error.');
}
}
/**
* PUT /authentication/local
* @summary Reset local authentication using the provided token
* @operationId resetLocalWithToken
* @tags authenticate - Operations of authentication controller
* @param {AuthenticationResetTokenRequest} request.body.required - The reset token.
* @return 204 - Successfully reset
* @return {string} 403 - Authentication error.
*/
public async resetLocalUsingToken(req: Request, res: Response): Promise<void> {
const body = req.body as AuthenticationResetTokenRequest;
this.logger.trace('Reset using token for user', body.accountMail);
try {
const service = new AuthenticationService();
const resetToken = await service.isResetTokenRequestValid(body);
if (!resetToken) {
res.status(403).json({
message: 'Invalid request.',
});
return;
}
if (AuthenticationService.isTokenExpired(resetToken)) {
res.status(403).json({
message: 'Token expired.',
});
return;
}
await service.resetLocalUsingToken(resetToken, body.token, body.password);
res.status(204).send();
return;
} catch (error) {
this.logger.error('Could not reset using token:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /authentication/local/reset
* @summary Creates a reset token for the local authentication
* @operationId resetLocal
* @tags authenticate - Operations of authentication controller
* @param {ResetLocalRequest} request.body.required - The reset info.
* @return 204 - Creation success
*/
public async createResetToken(req: Request, res: Response): Promise<void> {
const body = req.body as ResetLocalRequest;
this.logger.trace('Reset request for user', body.accountMail);
try {
const user = await User.findOne({
where: { email: body.accountMail, deleted: false, type: UserType.LOCAL_USER },
});
// If the user does not exist we simply return a success code as to not leak info.
if (!user) {
res.status(204).send();
return;
}
const resetTokenInfo = await new AuthenticationService().createResetToken(user);
Mailer.getInstance().send(user, new PasswordReset({ email: user.email, resetTokenInfo }))
.then()
.catch((error) => this.logger.error(error));
// send email with link.
res.status(204).send();
return;
} catch (error) {
this.logger.error('Could not create reset token:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /authentication/nfc
* @summary NFC login and hand out token
* @operationId nfcAuthentication
* @tags authenticate - Operations of authentication controller
* @param {AuthenticationNfcRequest} request.body.required - The NFC login.
* @return {AuthenticationResponse} 200 - The created json web token.
* @return {string} 403 - Authentication error.
*/
public async nfcLogin(req: Request, res: Response): Promise<void> {
const body = req.body as AuthenticationNfcRequest;
this.logger.trace('Atempted NFC authentication with NFC length, ', body.nfcCode.length);
try {
const { nfcCode } = body;
const authenticator = await NfcAuthenticator.findOne({ where: { nfcCode: nfcCode } });
if (authenticator == null || authenticator.user == null) {
res.status(403).json({
message: 'Invalid credentials.',
});
return;
}
const context: AuthenticationContext = {
roleManager: this.roleManager,
tokenHandler: this.tokenHandler,
};
this.logger.trace('Succesfull NFC authentication for user ', authenticator.user);
const token = await new AuthenticationService().getSaltedToken(authenticator.user, context, true);
res.json(token);
} catch (error) {
this.logger.error('Could not authenticate using NFC:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /authentication/ean
* @summary EAN login and hand out token
* @operationId eanAuthentication
* @tags authenticate - Operations of authentication controller
* @param {AuthenticationEanRequest} request.body.required - The EAN login.
* @return {AuthenticationResponse} 200 - The created json web token.
* @return {string} 403 - Authentication error.
*/
public async eanLogin(req: Request, res: Response): Promise<void> {
const body = req.body as AuthenticationEanRequest;
this.logger.trace('EAN authentication for ean', body.eanCode);
try {
const { eanCode } = body;
const authenticator = await EanAuthenticator.findOne({ where: { eanCode } });
if (authenticator == null || authenticator.user == null) {
res.status(403).json({
message: 'Invalid credentials.',
});
return;
}
const context: AuthenticationContext = {
roleManager: this.roleManager,
tokenHandler: this.tokenHandler,
};
const token = await new AuthenticationService().getSaltedToken(authenticator.user, context, true);
res.json(token);
} catch (error) {
this.logger.error('Could not authenticate using EAN:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /authentication/key
* @summary Key login and hand out token.
* @operationId keyAuthentication
* @tags authenticate - Operations of authentication controller
* @param {AuthenticationKeyRequest} request.body.required - The key login.
* @return {AuthenticationResponse} 200 - The created json web token.
* @return {string} 400 - Validation error.
* @return {string} 403 - Authentication error.
*/
public async keyLogin(req: Request, res: Response): Promise<void> {
const body = req.body as AuthenticationKeyRequest;
this.logger.trace('key authentication for user', body.userId);
try {
const user = await User.findOne({
where: { id: body.userId, deleted: false },
});
if (!user) {
res.status(403).json({
message: 'Invalid credentials.',
});
return;
}
const keyAuthenticator = await KeyAuthenticator.findOne({ where: { user: { id: body.userId } }, relations: ['user'] });
if (!keyAuthenticator) {
res.status(403).json({
message: 'Invalid credentials.',
});
return;
}
const context: AuthenticationContext = {
roleManager: this.roleManager,
tokenHandler: this.tokenHandler,
};
const result = await new AuthenticationService().HashAuthentication(body.key,
keyAuthenticator, context, false);
if (!result) {
res.status(403).json({
message: 'Invalid credentials.',
});
}
res.json(result);
} catch (error) {
this.logger.error('Could not authenticate using key:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /authentication/mock
* @summary Mock login and hand out token.
* @operationId mockAuthentication
* @tags authenticate - Operations of authentication controller
* @param {AuthenticationMockRequest} request.body.required - The mock login.
* @return {AuthenticationResponse} 200 - The created json web token.
* @return {string} 400 - Validation error.
*/
public async mockLogin(req: Request, res: Response): Promise<void> {
const body = req.body as AuthenticationMockRequest;
this.logger.trace('Mock authentication for user', body.userId);
try {
const user = await User.findOne({ where: { id: body.userId } });
const response = await new AuthenticationService().getSaltedToken(
user,
{ tokenHandler: this.tokenHandler, roleManager: this.roleManager },
false,
body.nonce,
);
res.json(response);
} catch (error) {
this.logger.error('Could not create token:', error);
res.status(500).json('Internal server error.');
}
}
}