-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgewis-authentication-controller.ts
245 lines (227 loc) · 8.55 KB
/
gewis-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
/**
* 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 gewis-authentication-controller.
*
* @module GEWIS
*/
import { Request, Response } from 'express';
import * as jwt from 'jsonwebtoken';
import log4js, { Logger } from 'log4js';
import * as util from 'util';
import BaseController, { BaseControllerOptions } from '../../controller/base-controller';
import Policy from '../../controller/policy';
import TokenHandler from '../../authentication/token-handler';
import GewisUser from '../entity/gewis-user';
import GewiswebToken from '../gewisweb-token';
import GewiswebAuthenticationRequest from './request/gewisweb-authentication-request';
import AuthenticationService from '../../service/authentication-service';
import GEWISAuthenticationPinRequest from './request/gewis-authentication-pin-request';
import AuthenticationLDAPRequest from '../../controller/request/authentication-ldap-request';
import AuthenticationController from '../../controller/authentication-controller';
import Gewis from '../gewis';
import UserService from '../../service/user-service';
import { webResponseToUpdate } from '../helpers/gewis-helper';
/**
* The GEWIS authentication controller is responsible for:
* - Verifying user authentications.
* - Handing out json web tokens.
*/
export default class GewisAuthenticationController extends BaseController {
/**
* Reference to the logger instance.
*/
private logger: Logger = log4js.getLogger('GewisAuthenticationController');
/**
* Reference to the token handler of the application.
*/
private tokenHandler: TokenHandler;
/**
* The secret key shared with gewisweb for JWT HMAC verification.
*/
private gewiswebSecret: string;
/**
* Creates a new authentication controller instance.
* @param options - The options passed to the base controller.
* @param tokenHandler - The token handler for creating signed tokens.
* @param gewiswebSecret - The shared JWT secret with gewisweb.
*/
public constructor(
options: BaseControllerOptions,
tokenHandler: TokenHandler,
gewiswebSecret: string,
) {
super(options);
this.logger.level = process.env.LOG_LEVEL;
this.tokenHandler = tokenHandler;
this.gewiswebSecret = gewiswebSecret;
}
/**
* @inheritdoc
*/
public getPolicy(): Policy {
return {
'/gewisweb': {
GET: {
policy: async () => true,
handler: this.getGEWISWebPublic.bind(this),
},
POST: {
body: { modelName: 'GewiswebAuthenticationRequest' },
policy: async () => true,
handler: this.gewiswebLogin.bind(this),
},
},
'/GEWIS/pin': {
POST: {
body: { modelName: 'GEWISAuthenticationPinRequest' },
policy: async () => true,
handler: this.gewisPINLogin.bind(this),
},
},
'/GEWIS/LDAP': {
POST: {
body: { modelName: 'AuthenticationLDAPRequest' },
policy: async () => true,
handler: this.ldapLogin.bind(this),
restrictions: { availableDuringMaintenance: true },
},
},
};
}
/**
* GET /authentication/gewisweb
* @summary Get the GEWISWeb public token used by SudoSOS
* @operationId getGEWISWebPublic
* @tags authenticate - Operations of authentication controller
* @returns {string} 200 - Public key
*/
public async getGEWISWebPublic(req: Request, res: Response): Promise<void> {
this.logger.trace('Get GEWISWeb public token by IP', req.ip);
res.json(process.env.GEWISWEB_PUBLIC_TOKEN);
}
/**
* POST /authentication/gewisweb
* @summary GEWIS login verification based on gewisweb JWT tokens.
* This method verifies the validity of the gewisweb JWT token, and returns a SudoSOS
* token if the GEWIS token is valid.
* @operationId gewisWebAuthentication
* @tags authenticate - Operations of authentication controller
* @param {GewiswebAuthenticationRequest} request.body.required - The mock login.
* @return {AuthenticationResponse} 200 - The created json web token.
* @return {MessageResponse} 403 - The created json web token.
* @return {string} 400 - Validation error.
*/
public async gewiswebLogin(req: Request, res: Response): Promise<void> {
const body = req.body as GewiswebAuthenticationRequest;
try {
let gewisweb: GewiswebToken;
try {
gewisweb = await util.promisify(jwt.verify)
.bind(null, body.token, this.gewiswebSecret, {
algorithms: ['HS512'],
complete: false,
})();
} catch (error) {
// Invalid token supplied.
res.status(403).json({
message: 'Invalid JWT signature',
});
return;
}
this.logger.trace('Gewisweb authentication for user with membership id', gewisweb.lidnr);
let gewisUser = await GewisUser.findOne({
where: { gewisId: gewisweb.lidnr },
relations: ['user'],
});
if (!gewisUser) {
// If
gewisUser = await new Gewis().createUserFromWeb(gewisweb);
} else {
//
const update = webResponseToUpdate(gewisweb);
await UserService.updateUser(gewisUser.user.id, update);
}
const response = await new AuthenticationService().getSaltedToken(
gewisUser.user,
{ roleManager: this.roleManager, tokenHandler: this.tokenHandler },
false,
body.nonce,
);
res.json(response);
} catch (error) {
this.logger.error('Could not create token:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /authentication/GEWIS/LDAP
* @summary LDAP login and hand out token
* If user has never signed in before this also creates an GEWIS account.
* @operationId gewisLDAPAuthentication
* @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('GEWIS LDAP authentication for user', body.accountName);
try {
const gewisService = new Gewis();
await AuthenticationController.LDAPLoginConstructor(this.roleManager, this.tokenHandler, gewisService.findOrCreateGEWISUserAndBind.bind(gewisService))(req, res);
} catch (error) {
this.logger.error('Could not authenticate using LDAP:', error);
res.status(500).json('Internal server error.');
}
}
/**
* POST /authentication/GEWIS/pin
* @summary PIN login and hand out token.
* @operationId gewisPinAuthentication
* @tags authenticate - Operations of authentication controller
* @param {GEWISAuthenticationPinRequest} 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 gewisPINLogin(req: Request, res: Response): Promise<void> {
const { pin, gewisId } = req.body as GEWISAuthenticationPinRequest;
this.logger.trace('GEWIS PIN authentication for user', gewisId);
try {
const gewisUser = await GewisUser.findOne({
where: { gewisId },
relations: ['user'],
});
if (!gewisUser) {
res.status(403).json({
message: `User ${gewisId} not registered`,
});
return;
}
await (AuthenticationController.PINLoginConstructor(this.roleManager, this.tokenHandler,
pin, gewisUser.user.id))(req, res);
} catch (error) {
this.logger.error('Could not authenticate using PIN:', error);
res.status(500).json('Internal server error.');
}
}
}