-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.ts
More file actions
369 lines (335 loc) · 9.83 KB
/
auth.ts
File metadata and controls
369 lines (335 loc) · 9.83 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
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { MicrosoftGraphClient, MsAuthClient } from './MsApiClient';
import {
academicYear,
generateCookieHeader,
grantAccessTo,
isFresherOrParent,
newToken
} from './jwt';
import factory from '../factory';
import { apiLogger } from '../logger';
import { db } from '../db';
import { students } from '../family/schema';
import { and, eq, gt } from 'drizzle-orm';
import { states } from '../admin/schema';
import { sendEmail } from '../mailer';
import { randomBytes } from 'crypto';
import {
oauthCallbackSchema,
emailCallbackSchema,
loginSchema,
authTokens
} from './schema';
const stateManager = {
newState: async (state: string) => {
// State expires 10 minutes from now
const expiresAt = new Date(Date.now() + 10 * 60 * 1000);
await db.insert(states).values({
state: state,
expiresAt: expiresAt
});
},
stateExists: async (state: string) => {
const statesInDb = await db
.select()
.from(states)
.where(and(eq(states.state, state), gt(states.expiresAt, new Date())));
return statesInDb.length > 0;
},
removeState: async (state: string) => {
await db.delete(states).where(eq(states.state, state));
}
};
const msAuth = new MsAuthClient(
['User.Read'],
{
tenantId: process.env.TENANT_ID!,
clientId: process.env.CLIENT_ID!,
clientSecret: process.env.CLIENT_SECRET!
},
`${process.env.BASE_URL}/finish-oauth`,
stateManager
);
const abcApi = {
baseUrl: process.env.ABC_API_BASE,
auth: `Basic ${btoa(`${process.env.ABC_API_USER}:${process.env.ABC_API_PASS}`)}`,
identity: async (shortcode: string, year: number) => {
const url = `${abcApi.baseUrl}/${year - 1}${year}/identity?login=${shortcode}`;
const abcReq = await fetch(url, {
headers: {
Authorization: abcApi.auth
}
});
return abcReq;
}
};
const auth = factory
.createApp()
.get('/signIn', grantAccessTo('unauthenticated'), async ctx => {
// Redirect the user to the Microsoft oAuth sign in.
return ctx.redirect(msAuth.getRedirectUrl());
})
.get(
'/signOut',
zValidator(
'query',
z.object({
redirect: z.string().optional()
})
),
grantAccessTo('authenticated'),
async ctx => {
// Delete their JWT cookie.
ctx.header('Set-Cookie', generateCookieHeader('', 0));
const query = ctx.req.valid('query');
const path = query.redirect || '';
const redirectUrl = process.env.BASE_URL! + path + '?loggedOut=true';
return ctx.redirect(redirectUrl);
}
)
.post(
'/callback-oauth',
grantAccessTo('unauthenticated'),
zValidator('json', oauthCallbackSchema, async (zRes, ctx) => {
if (!zRes.success || zRes.data.error_description) {
apiLogger.warn(
ctx,
'Microsoft Entra Error:',
zRes.data.error_description
);
return ctx.text('Invalid request.', 400);
}
}),
async ctx => {
const { code, state } = ctx.req.valid('json');
let client: MicrosoftGraphClient;
try {
client = await msAuth.verifyAndConsumeCode(code, state);
} catch (e) {
apiLogger.error(ctx, 'Microsoft auth error:', e);
return ctx.text('Internal server error.', 500);
}
// Get their department, short, and long email.
const res = await client.get('/me', [
'department',
'userPrincipalName',
'mail'
]);
const shortcode = res.userPrincipalName.match(/.*(?=@)/g);
if (shortcode == null) {
return ctx.json(
{
error: 'User has no shortcode.'
},
400
);
}
const studentInDb = await db
.select()
.from(students)
.where(eq(students.shortcode, shortcode[0]));
// We allow them to pass even as non-Computing students if they
// exist in the DB. This is done for cases where there is a
// non Computing member on committee who needs access to the
// admin portal, or a non computing member who is eligible to
// be a parent or student, somehow.
if (studentInDb.length == 0 && res.department != 'Computing') {
return ctx.json(
{
error: 'You are not a Computing student :('
},
403
);
}
let token: string;
try {
token = await newToken(res.mail, shortcode[0]);
} catch (e) {
// The only error we can get is that it fails to get an entry year.
return ctx.json(
{
error: 'User has no entry year. Are you a professor?'
},
400
);
}
const user_is = isFresherOrParent(res.mail);
// Expire the JWT after 4 weeks.
// Should be long enough for MaDs to only sign in once.
const maxAge = 28 * 24 * 60 * 60;
ctx.header('Set-Cookie', generateCookieHeader(token, maxAge));
let completedSurvey = false;
if (studentInDb.length == 1 && studentInDb[0]?.completedSurvey)
completedSurvey = true;
else if (studentInDb.length == 0) {
await db.insert(students).values({
shortcode: shortcode[0],
role: user_is,
completedSurvey: false
});
}
return ctx.json(
{
user_is: user_is,
done_survey: completedSurvey
},
200
);
}
)
.post(
'/login',
grantAccessTo('unauthenticated'),
zValidator('json', loginSchema, async (zRes, ctx) => {
if (!zRes.success) {
return ctx.json(
{
error: 'No valid Imperial email provided.'
},
400
);
}
}),
async ctx => {
// Valid Imperial shortcode email by login schema
const { email } = ctx.req.valid('json');
// Generate sign in token
const token = randomBytes(16).toString('hex');
const issuedAt = new Date();
const expiresAt = new Date(Date.now() + 15 * 60 * 1000); // 15 minutes
await db.insert(authTokens).values({
token,
email,
issuedAt,
expiresAt
});
const link = `${process.env.BASE_URL}/finish-email?token=${token}`;
const user_is = isFresherOrParent(email);
const warmWelcome =
user_is === 'parent'
? 'Thanks for your interest in being a parent :>'
: 'Welcome to DoCSoc!';
await sendEmail(
ctx,
email,
'[Mums and Dads] Sign in link',
'Use the following link to sign in: ' + link,
`<p>Hey! ${warmWelcome} <br> Click <a href="${link}">here</a> to complete your sign in.</p>`
);
return ctx.json({}, 200);
}
)
.post(
'/callback-email',
grantAccessTo('unauthenticated'),
zValidator('json', emailCallbackSchema, async (zRes, ctx) => {
if (!zRes.success) {
return ctx.json(
{
error: 'No valid token provided.'
},
400
);
}
}),
async ctx => {
const { token } = ctx.req.valid('json');
const tokenInDb = await db
.delete(authTokens)
.where(
and(eq(authTokens.token, token), gt(authTokens.expiresAt, new Date()))
)
.returning();
if (tokenInDb.length == 0) {
return ctx.json(
{
error: 'Invalid or expired token.'
},
400
);
}
const email = tokenInDb[0]!.email;
const shortcode = email.match(/.*(?=@)/g);
// Should not happen
if (shortcode == null) {
return ctx.json(
{
error: 'User has no shortcode.'
},
400
);
}
// Allow if in db - this will be freshers, plus anyone manually added
const studentInDb = await db
.select()
.from(students)
.where(eq(students.shortcode, shortcode[0]));
// Else check via ABC API for last academic year - eligible parents
if (studentInDb.length == 0) {
const abcReq = await abcApi.identity(shortcode[0], academicYear);
if (abcReq.status != 200) {
return ctx.json(
{
error: 'You are not a Computing student :('
},
403
);
}
}
// Now we know they're eligible to sign in, create and return a JWT
let jwt: string;
try {
jwt = await newToken(email, shortcode[0]);
} catch (e) {
// The only error we can get is that it fails to get an entry year.
return ctx.json(
{
error: 'User has no entry year. Are you a professor?'
},
400
);
}
const user_is = studentInDb[0]?.role ?? isFresherOrParent(email);
// Expire the JWT after 4 weeks.
// Should be long enough for MaDs to only sign in once.
const maxAge = 28 * 24 * 60 * 60;
ctx.header('Set-Cookie', generateCookieHeader(jwt, maxAge));
let completedSurvey = false;
if (studentInDb.length == 1 && studentInDb[0]?.completedSurvey) {
completedSurvey = true;
} else if (studentInDb.length == 0) {
await db.insert(students).values({
shortcode: shortcode[0],
role: user_is,
completedSurvey: false
});
}
return ctx.json(
{
user_is: user_is,
done_survey: completedSurvey
},
200
);
}
)
.get('/details', grantAccessTo('authenticated'), async ctx => {
// Mostly a test route but doesn't hurt to keep.
const shortcode = ctx.get('shortcode')!;
const user_is = ctx.get('user_is')!;
const studentInDb = await db
.select()
.from(students)
.where(eq(students.shortcode, shortcode));
return ctx.json(
{
shortcode: shortcode,
user_is: user_is,
doneSurvey: studentInDb[0]?.completedSurvey || false
},
200
);
});
export default auth;