Skip to content

Commit 6583219

Browse files
committed
implemented middleware on all services
1 parent 2e18151 commit 6583219

File tree

7 files changed

+109
-102
lines changed

7 files changed

+109
-102
lines changed

src/services/admission/admission-router.ts

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import Models from "../../database/models.js";
77
import { hasElevatedPerms } from "../auth/auth-lib.js";
88
import { ApplicantDecisionFormat } from "./admission-formats.js";
99
import { StatusCode } from "status-code-enum";
10+
import { NextFunction } from "express-serve-static-core";
11+
import { RouterError } from "../../middleware/error-handler.js"
1012

1113
const admissionRouter: Router = Router();
1214

@@ -45,18 +47,17 @@ const admissionRouter: Router = Router();
4547
* @apiError (500: Internal Server Error) {String} InternalError occurred on the server.
4648
* @apiError (403: Forbidden) {String} Forbidden API accessed by user without valid perms.
4749
* */
48-
admissionRouter.get("/not-sent/", strongJwtVerification, async (_: Request, res: Response) => {
50+
admissionRouter.get("/not-sent/", strongJwtVerification, async (_: Request, res: Response, next: NextFunction) => {
4951
const token: JwtPayload = res.locals.payload as JwtPayload;
5052
if (!hasElevatedPerms(token)) {
51-
return res.status(StatusCode.ClientErrorForbidden).send({ error: "Forbidden" });
53+
return next(new RouterError(StatusCode.ClientErrorForbidden, "Forbidden"));
5254
}
5355
try {
5456
const filteredEntries: AdmissionDecision[] = await Models.AdmissionDecision.find({ emailSent: false });
5557
return res.status(StatusCode.SuccessOK).send(filteredEntries);
5658
} catch (error) {
57-
console.error(error);
59+
return next(new RouterError(undefined,undefined,undefined,error));
5860
}
59-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "InternalError" });
6061
});
6162

6263
/**
@@ -91,10 +92,10 @@ admissionRouter.get("/not-sent/", strongJwtVerification, async (_: Request, res:
9192
* @apiError (500: Internal Server Error) {String} InternalError occurred on the server.
9293
* @apiError (403: Forbidden) {String} Forbidden API accessed by user without valid perms.
9394
* */
94-
admissionRouter.put("/", strongJwtVerification, async (req: Request, res: Response) => {
95+
admissionRouter.put("/", strongJwtVerification, async (req: Request, res: Response, next: NextFunction) => {
9596
const token: JwtPayload = res.locals.payload as JwtPayload;
9697
if (!hasElevatedPerms(token)) {
97-
return res.status(StatusCode.ClientErrorForbidden).send({ error: "Forbidden" });
98+
return next(new RouterError(StatusCode.ClientErrorForbidden, "Forbidden"));
9899
}
99100
const updateEntries: ApplicantDecisionFormat[] = req.body as ApplicantDecisionFormat[];
100101
const ops = updateEntries.map((entry) => {
@@ -104,9 +105,8 @@ admissionRouter.put("/", strongJwtVerification, async (req: Request, res: Respon
104105
await Promise.all(ops);
105106
return res.status(StatusCode.SuccessOK).send({ message: "StatusSuccess" });
106107
} catch (error) {
107-
console.log(error);
108+
return next(new RouterError(undefined,undefined,undefined,error))
108109
}
109-
return res.status(StatusCode.ClientErrorBadRequest).send("InternalError");
110110
});
111111

112112
/**
@@ -133,21 +133,21 @@ admissionRouter.put("/", strongJwtVerification, async (req: Request, res: Respon
133133
*
134134
* @apiUse strongVerifyErrors
135135
*/
136-
admissionRouter.get("/rsvp/:USERID", strongJwtVerification, async (req: Request, res: Response) => {
136+
admissionRouter.get("/rsvp/:USERID", strongJwtVerification, async (req: Request, res: Response, next: NextFunction) => {
137137
const userId: string | undefined = req.params.USERID;
138138

139139
const payload: JwtPayload = res.locals.payload as JwtPayload;
140140

141141
//Sends error if caller doesn't have elevated perms
142142
if (!hasElevatedPerms(payload)) {
143-
return res.status(StatusCode.ClientErrorForbidden).send({ error: "Forbidden" });
143+
return next(new RouterError(StatusCode.ClientErrorForbidden, "Forbidden"));
144144
}
145145

146146
const queryResult: AdmissionDecision | null = await Models.AdmissionDecision.findOne({ userId: userId });
147147

148148
//Returns error if query is empty
149149
if (!queryResult) {
150-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "UserNotFound" });
150+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "UserNotFound"));
151151
}
152152

153153
return res.status(StatusCode.SuccessOK).send(queryResult);
@@ -182,7 +182,7 @@ admissionRouter.get("/rsvp/:USERID", strongJwtVerification, async (req: Request,
182182
*
183183
* @apiUse strongVerifyErrors
184184
*/
185-
admissionRouter.get("/rsvp", strongJwtVerification, async (_: Request, res: Response) => {
185+
admissionRouter.get("/rsvp", strongJwtVerification, async (_: Request, res: Response, next: NextFunction) => {
186186
const payload: JwtPayload = res.locals.payload as JwtPayload;
187187

188188
const userId: string = payload.id;
@@ -191,7 +191,7 @@ admissionRouter.get("/rsvp", strongJwtVerification, async (_: Request, res: Resp
191191

192192
//Returns error if query is empty
193193
if (!queryResult) {
194-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "UserNotFound" });
194+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "UserNotFound"));
195195
}
196196

197197
//Filters data if caller doesn't have elevated perms
@@ -232,12 +232,12 @@ admissionRouter.get("/rsvp", strongJwtVerification, async (_: Request, res: Resp
232232
*
233233
* @apiUse strongVerifyErrors
234234
*/
235-
admissionRouter.put("/rsvp/", strongJwtVerification, async (req: Request, res: Response) => {
235+
admissionRouter.put("/rsvp/", strongJwtVerification, async (req: Request, res: Response, next: NextFunction) => {
236236
const rsvp: boolean | undefined = req.body.isAttending;
237237

238238
//Returns error if request body has no isAttending parameter
239239
if (rsvp === undefined) {
240-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "InvalidParams" });
240+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "InvalidParams"));
241241
}
242242

243243
const payload: JwtPayload = res.locals.payload as JwtPayload;
@@ -248,12 +248,12 @@ admissionRouter.put("/rsvp/", strongJwtVerification, async (req: Request, res: R
248248

249249
//Returns error if query is empty
250250
if (!queryResult) {
251-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "UserNotFound" });
251+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "UserNotFound"));
252252
}
253253

254254
//If the current user has not been accepted, send an error
255255
if (queryResult.status != DecisionStatus.ACCEPTED) {
256-
return res.status(StatusCode.ClientErrorForbidden).send({ error: "NotAccepted" });
256+
return next(new RouterError(StatusCode.ClientErrorForbidden, "NotAccepted"));
257257
}
258258

259259
//If current user has been accepted, update their RSVP decision to "ACCEPTED"/"DECLINED" acoordingly
@@ -270,7 +270,7 @@ admissionRouter.put("/rsvp/", strongJwtVerification, async (req: Request, res: R
270270
//return res.status(StatusCode.SuccessOK).send(updatedDecision.toObject());
271271
return res.status(StatusCode.SuccessOK).send(updatedDecision);
272272
} else {
273-
return res.status(StatusCode.ServerErrorInternal).send({ error: "InternalError" });
273+
return next(new RouterError());
274274
}
275275
});
276276

src/services/auth/auth-router.ts

Lines changed: 26 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
getUsersWithRole,
2222
} from "./auth-lib.js";
2323
import Models from "../../database/models.js";
24+
import { RouterError } from "../../middleware/error-handler.js";
2425

2526
passport.use(
2627
Provider.GITHUB,
@@ -53,10 +54,10 @@ authRouter.get("/test/", (_: Request, res: Response) => {
5354
res.end("Auth endpoint is working!");
5455
});
5556

56-
authRouter.get("/dev/", (req: Request, res: Response) => {
57+
authRouter.get("/dev/", (req: Request, res: Response, next: NextFunction) => {
5758
const token: string | undefined = req.query.token as string | undefined;
5859
if (!token) {
59-
res.status(StatusCode.ClientErrorBadRequest).send({ error: "NoToken" });
60+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "NoToken"));
6061
}
6162

6263
res.status(StatusCode.SuccessOK).send({ token: token });
@@ -85,7 +86,7 @@ authRouter.get("/login/github/", (req: Request, res: Response, next: NextFunctio
8586
const device: string = (req.query.device as string | undefined) ?? Config.DEFAULT_DEVICE;
8687

8788
if (device && !Config.REDIRECT_URLS.has(device)) {
88-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "BadDevice" });
89+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "BadDevice"));
8990
}
9091
return SelectAuthProvider("github", device)(req, res, next);
9192
});
@@ -113,7 +114,7 @@ authRouter.get("/login/google/", (req: Request, res: Response, next: NextFunctio
113114
const device: string = (req.query.device as string | undefined) ?? Config.DEFAULT_DEVICE;
114115

115116
if (device && !Config.REDIRECT_URLS.has(device)) {
116-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "BadDevice" });
117+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "BadDevice"));
117118
}
118119
return SelectAuthProvider("google", device)(req, res, next);
119120
});
@@ -127,18 +128,18 @@ authRouter.get(
127128
const device = req.params.DEVICE;
128129

129130
if (!device || !Config.REDIRECT_URLS.has(device)) {
130-
throw Error(`Bad device ${device}`);
131+
throw Error(`${device}`);
131132
}
132133

133134
res.locals.device = device;
134135
SelectAuthProvider(provider, device)(req, res, next);
135136
} catch (error) {
136-
console.error(error);
137+
return next(new RouterError(StatusCode.ClientErrorBadRequest, `Bad device ${error}`))
137138
}
138139
},
139-
async (req: Request, res: Response) => {
140+
async (req: Request, res: Response, next: NextFunction) => {
140141
if (!req.isAuthenticated()) {
141-
return res.status(StatusCode.ClientErrorUnauthorized).send({ error: "FailedAuth" });
142+
return next(new RouterError(StatusCode.ClientErrorUnauthorized, "FailedAuth"));
142143
}
143144

144145
const device: string = (res.locals.device ?? Config.DEFAULT_DEVICE) as string;
@@ -166,8 +167,7 @@ authRouter.get(
166167
const url: string = `${redirect}?token=${token}`;
167168
return res.redirect(url);
168169
} catch (error) {
169-
console.error(error);
170-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "InvalidData" });
170+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "InvalidData"));
171171
}
172172
},
173173
);
@@ -192,7 +192,7 @@ authRouter.get(
192192
* @apiError (400: Bad Request) {String} UserNotFound User doesn't exist in the database.
193193
* @apiError (403: Forbidden) {String} Forbidden API accessed by user without valid perms.
194194
*/
195-
authRouter.get("/roles/:USERID", strongJwtVerification, async (req: Request, res: Response) => {
195+
authRouter.get("/roles/:USERID", strongJwtVerification, async (req: Request, res: Response, next: NextFunction) => {
196196
const targetUser: string | undefined = req.params.USERID;
197197

198198
// Check if we have a user to get roles for - if not, get roles for current user
@@ -210,11 +210,10 @@ authRouter.get("/roles/:USERID", strongJwtVerification, async (req: Request, res
210210
const roles: Role[] = await getRoles(targetUser);
211211
return res.status(StatusCode.SuccessOK).send({ id: targetUser, roles: roles });
212212
} catch (error) {
213-
console.error(error);
214-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "UserNotFound" });
213+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "UserNotFound"));
215214
}
216215
} else {
217-
return res.status(StatusCode.ClientErrorForbidden).send("Forbidden");
216+
return next(new RouterError(StatusCode.ClientErrorForbidden, "Forbidden"));
218217
}
219218
});
220219

@@ -239,36 +238,35 @@ authRouter.get("/roles/:USERID", strongJwtVerification, async (req: Request, res
239238
* @apiError (400: Bad Request) {String} InvalidRole Nonexistent role passed in.
240239
* @apiUse strongVerifyErrors
241240
*/
242-
authRouter.put("/roles/:OPERATION/", strongJwtVerification, async (req: Request, res: Response) => {
241+
authRouter.put("/roles/:OPERATION/", strongJwtVerification, async (req: Request, res: Response, next: NextFunction) => {
243242
const payload: JwtPayload = res.locals.payload as JwtPayload;
244243

245244
// Not authenticated with modify roles perms
246245
if (!hasElevatedPerms(payload)) {
247-
return res.status(StatusCode.ClientErrorForbidden).send({ error: "Forbidden" });
246+
return next(new RouterError(StatusCode.ClientErrorForbidden, "Forbidden"));
248247
}
249248

250249
// Parse to get operation type
251250
const op: RoleOperation | undefined = RoleOperation[req.params.operation as keyof typeof RoleOperation];
252251

253252
// No operation - fail out
254253
if (!op) {
255-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "InvalidOperation" });
254+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "InvalidOperation"));
256255
}
257256

258257
// Check if role to add/remove actually exists
259258
const data: ModifyRoleRequest = req.body as ModifyRoleRequest;
260259
const role: Role | undefined = Role[data.role.toUpperCase() as keyof typeof Role];
261260
if (!role) {
262-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "InvalidRole" });
261+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "InvalidRole"));
263262
}
264263

265264
// Try to update roles, if possible
266265
try {
267266
const newRoles: Role[] = await updateRoles(data.id, role, op);
268267
return res.status(StatusCode.SuccessOK).send({ id: data.id, roles: newRoles });
269268
} catch (error) {
270-
console.error(error);
271-
return res.status(StatusCode.ServerErrorInternal).send({ error: "InternalError" });
269+
return next(new RouterError());
272270
}
273271
});
274272

@@ -289,12 +287,12 @@ authRouter.put("/roles/:OPERATION/", strongJwtVerification, async (req: Request,
289287
* @apiError (400: Bad Request) {String} UserNotFound User doesn't exist in the database
290288
* @apiError (403: Forbidden) {String} Forbidden API accessed by user without valid perms
291289
*/
292-
authRouter.get("/list/roles/", strongJwtVerification, (_: Request, res: Response) => {
290+
authRouter.get("/list/roles/", strongJwtVerification, (_: Request, res: Response, next: NextFunction) => {
293291
const payload: JwtPayload = res.locals.payload as JwtPayload;
294292

295293
// Check if current user should be able to access all roles
296294
if (!hasElevatedPerms(payload)) {
297-
return res.status(StatusCode.ClientErrorForbidden).send({ error: "Forbidden" });
295+
return next(new RouterError(StatusCode.ClientErrorForbidden, "Forbidden"));
298296
}
299297

300298
// Filter enum to get all possible string keys
@@ -321,7 +319,7 @@ authRouter.get("/list/roles/", strongJwtVerification, (_: Request, res: Response
321319
*
322320
* @apiUse strongVerifyErrors
323321
*/
324-
authRouter.get("/roles/", strongJwtVerification, async (_: Request, res: Response) => {
322+
authRouter.get("/roles/", strongJwtVerification, async (_: Request, res: Response, next: NextFunction) => {
325323
const payload: JwtPayload = res.locals.payload as JwtPayload;
326324
const targetUser: string = payload.id;
327325

@@ -330,8 +328,7 @@ authRouter.get("/roles/", strongJwtVerification, async (_: Request, res: Respons
330328
return res.status(StatusCode.SuccessOK).send({ id: targetUser, roles: roles });
331329
})
332330
.catch((error: Error) => {
333-
console.error(error);
334-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "UserNotFound" });
331+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "UserNotFound", undefined, error.message));
335332
});
336333
});
337334

@@ -351,7 +348,7 @@ authRouter.get("/roles/", strongJwtVerification, async (_: Request, res: Respons
351348
*
352349
* @apiUse strongVerifyErrors
353350
*/
354-
authRouter.get("/roles/list/:ROLE", async (req: Request, res: Response) => {
351+
authRouter.get("/roles/list/:ROLE", async (req: Request, res: Response, next: NextFunction) => {
355352
const role: string | undefined = req.params.ROLE;
356353

357354
//Returns error if role parameter is empty
@@ -365,7 +362,7 @@ authRouter.get("/roles/list/:ROLE", async (req: Request, res: Response) => {
365362
})
366363
.catch((error: Error) => {
367364
console.error(error);
368-
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "Unknown Error" });
365+
return next(new RouterError(StatusCode.ClientErrorBadRequest, "Unknown Error"));
369366
});
370367
});
371368

@@ -383,7 +380,7 @@ authRouter.get("/roles/list/:ROLE", async (req: Request, res: Response) => {
383380
*
384381
* @apiUse strongVerifyErrors
385382
*/
386-
authRouter.get("/token/refresh", strongJwtVerification, async (_: Request, res: Response) => {
383+
authRouter.get("/token/refresh", strongJwtVerification, async (_: Request, res: Response, next: NextFunction) => {
387384
// Get old data from token
388385
const oldPayload: JwtPayload = res.locals.payload as JwtPayload;
389386
const data: ProfileData = {
@@ -399,8 +396,7 @@ authRouter.get("/token/refresh", strongJwtVerification, async (_: Request, res:
399396
const newToken: string = generateJwtToken(newPayload);
400397
return res.status(StatusCode.SuccessOK).send({ token: newToken });
401398
} catch (error) {
402-
console.error(error);
403-
return res.status(StatusCode.ServerErrorInternal).send({ error: "InternalError" });
399+
return next(new RouterError());
404400
}
405401
});
406402

0 commit comments

Comments
 (0)