-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathauth.ts
More file actions
382 lines (342 loc) · 10.4 KB
/
auth.ts
File metadata and controls
382 lines (342 loc) · 10.4 KB
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
/**
* Copyright 2026 GitProxy Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import express, { Request, Response, NextFunction } from 'express';
import bcrypt from 'bcryptjs';
import { getPassport, authStrategies } from '../passport';
import { getAuthMethods } from '../../config';
import * as db from '../../db';
import * as passportLocal from '../passport/local';
import * as passportAD from '../passport/activeDirectory';
import { User } from '../../db/types';
import { AuthenticationElement } from '../../config/generated/config';
import { isAdminUser, mustChangePassword, toPublicUser } from './utils';
import { handleErrorAndLog } from '../../utils/errors';
const router = express.Router();
const passport = getPassport();
const { GIT_PROXY_UI_HOST: uiHost = 'http://localhost', GIT_PROXY_UI_PORT: uiPort = 3000 } =
process.env;
const PASSWORD_MIN_LENGTH = 8;
const PASSWORD_CHANGE_ALLOWED_PATHS = new Set([
'/',
'/config',
'/login',
'/logout',
'/profile',
'/change-password',
'/openidconnect',
'/openidconnect/callback',
]);
router.use((req: Request, res: Response, next: NextFunction) => {
if (!mustChangePassword(req.user)) {
return next();
}
if (PASSWORD_CHANGE_ALLOWED_PATHS.has(req.path)) {
return next();
}
return res.status(428).send({
message: 'Password change required before accessing this endpoint',
});
});
router.get('/', (_req: Request, res: Response) => {
res.status(200).json({
login: {
action: 'post',
uri: '/api/auth/login',
},
profile: {
action: 'get',
uri: '/api/auth/profile',
},
logout: {
action: 'post',
uri: '/api/auth/logout',
},
});
});
// login strategies that will work with /login e.g. take username and password
const appropriateLoginStrategies = [passportLocal.type, passportAD.type];
// getLoginStrategy fetches the enabled auth methods and identifies if there's an appropriate
// auth method for username and password login. If there isn't it returns null, if there is it
// returns the first.
const getLoginStrategy = () => {
// returns only enabled auth methods
// returns at least one enabled auth method
const enabledAppropriateLoginStrategies = getAuthMethods().filter((am: AuthenticationElement) =>
appropriateLoginStrategies.includes(am.type.toLowerCase()),
);
// for where no login strategies which work for /login are enabled
// just return null
if (enabledAppropriateLoginStrategies.length === 0) {
return null;
}
// return the first enabled auth method
return enabledAppropriateLoginStrategies[0].type.toLowerCase();
};
const loginSuccessHandler = () => async (req: Request, res: Response) => {
try {
const currentUser = toPublicUser({ ...req.user } as User);
console.log(
`serivce.routes.auth.login: user logged in, username=${
currentUser.username
} profile=${JSON.stringify(currentUser)}`,
);
res.send({
message: 'success',
user: currentUser,
});
} catch (error: unknown) {
const msg = handleErrorAndLog(error, 'Error logging user in');
res.status(500).send(`Failed to login: ${msg}`).end();
}
};
router.get('/config', (req, res) => {
const usernamePasswordMethod = getLoginStrategy();
res.send({
// enabled username /password auth method
usernamePasswordMethod: usernamePasswordMethod,
// other enabled auth methods
otherMethods: getAuthMethods()
.map((am) => am.type.toLowerCase())
.filter((authType) => authType !== usernamePasswordMethod),
});
});
// TODO: provide separate auth endpoints for each auth strategy or chain compatibile auth strategies
// TODO: if providing separate auth methods, inform the frontend so it has relevant UI elements and appropriate client-side behavior
router.post(
'/login',
(req: Request, res: Response, next: NextFunction) => {
const authType = getLoginStrategy();
if (authType === null) {
res.status(403).send('Username and Password based Login is not enabled at this time').end();
return;
}
console.log('going to auth with', authType);
return passport.authenticate(authType)(req, res, next);
},
loginSuccessHandler(),
);
router.get('/openidconnect', passport.authenticate(authStrategies['openidconnect'].type));
router.get('/openidconnect/callback', (req: Request, res: Response, next: NextFunction) => {
passport.authenticate(
authStrategies['openidconnect'].type,
(err: unknown, user: Partial<db.User>, info: unknown) => {
if (err) {
console.error('Authentication error:', err);
return res.status(500).end();
}
if (!user) {
console.error('No user found:', info);
return res.status(401).end();
}
req.logIn(user, (err) => {
if (err) {
console.error('Login error:', err);
return res.status(500).end();
}
console.log('Logged in successfully. User:', user);
return res.redirect(`${uiHost}:${uiPort}/dashboard/profile`);
});
},
)(req, res, next);
});
router.post('/logout', (req: Request, res: Response, next: NextFunction) => {
req.logout((err: unknown) => {
if (err) return next(err);
});
res.clearCookie('connect.sid');
res.send({ isAuth: req.isAuthenticated(), user: req.user });
});
router.post('/change-password', async (req: Request, res: Response) => {
if (!req.user) {
res
.status(401)
.send({
message: 'Not logged in',
})
.end();
return;
}
const { currentPassword, newPassword } = req.body ?? {};
if (
typeof currentPassword !== 'string' ||
typeof newPassword !== 'string' ||
currentPassword.trim().length === 0 ||
newPassword.trim().length < PASSWORD_MIN_LENGTH
) {
res
.status(400)
.send({
message: `currentPassword and newPassword are required, and newPassword must be at least ${PASSWORD_MIN_LENGTH} characters`,
})
.end();
return;
}
if (currentPassword === newPassword) {
res
.status(400)
.send({
message: 'newPassword must be different from currentPassword',
})
.end();
return;
}
try {
const user = await db.findUser((req.user as User).username);
if (!user) {
res.status(404).send({ message: 'User not found' }).end();
return;
}
if (!user.password) {
res
.status(400)
.send({ message: 'Password changes are not supported for this account' })
.end();
return;
}
const currentPasswordCorrect = await bcrypt.compare(currentPassword, user.password ?? '');
if (!currentPasswordCorrect) {
res.status(401).send({ message: 'Current password is incorrect' }).end();
return;
}
const hashedPassword = await bcrypt.hash(newPassword, 10);
await db.updateUser({
username: user.username,
password: hashedPassword,
mustChangePassword: false,
});
(req.user as User).mustChangePassword = false;
res.status(200).send({ message: 'Password updated successfully' }).end();
} catch (error: unknown) {
const msg = handleErrorAndLog(error, 'Failed to update password');
res
.status(500)
.send({
message: msg,
})
.end();
}
});
router.get('/profile', async (req: Request, res: Response) => {
if (!req.user) {
res
.status(401)
.send({
message: 'Not logged in',
})
.end();
return;
}
const userVal = await db.findUser((req.user as User).username);
if (!userVal) {
res.status(404).send({ message: 'User not found' }).end();
return;
}
res.send(toPublicUser(userVal));
});
router.post('/gitAccount', async (req: Request, res: Response) => {
if (!req.user) {
res
.status(401)
.send({
message: 'Not logged in',
})
.end();
return;
}
try {
let username =
req.body.username == null || req.body.username === 'undefined'
? req.body.id
: req.body.username;
username = username?.split('@')[0];
if (!username) {
res
.status(400)
.send({
message: 'Missing username. Git account not updated',
})
.end();
return;
}
const reqUser = await db.findUser((req.user as User).username);
if (username !== reqUser?.username && !reqUser?.admin) {
res
.status(403)
.send({
message: 'Must be an admin to update a different account',
})
.end();
return;
}
const user = await db.findUser(username);
if (!user) {
res
.status(404)
.send({
message: 'User not found',
})
.end();
return;
}
user.gitAccount = req.body.gitAccount;
await db.updateUser(user);
return res.status(200).send({ message: 'Git account updated successfully' }).end();
} catch (error: unknown) {
const msg = handleErrorAndLog(error, 'Failed to update git account');
return res.status(500).send({ message: msg }).end();
}
});
router.post('/create-user', async (req: Request, res: Response) => {
if (!isAdminUser(req.user)) {
res
.status(403)
.send({
message: 'Not authorized to create users',
})
.end();
return;
}
try {
const { username, password, email, gitAccount, admin: isAdmin = false } = req.body;
if (!username || !password || !email || !gitAccount) {
res
.status(400)
.send({
message:
'Missing required fields: username, password, email, and gitAccount are required',
})
.end();
return;
}
await db.createUser(username, password, email, gitAccount, isAdmin);
res
.status(201)
.send({
message: 'User created successfully',
username,
})
.end();
} catch (error: unknown) {
const msg = handleErrorAndLog(error, 'Failed to create user');
res
.status(500)
.send({
message: msg,
})
.end();
}
});
export default { router, loginSuccessHandler };