Skip to content

Commit

Permalink
Use status code lib instead of constants
Browse files Browse the repository at this point in the history
  • Loading branch information
Timothy-Gonzalez committed Oct 22, 2023
1 parent 1347b61 commit 347e69d
Show file tree
Hide file tree
Showing 12 changed files with 107 additions and 110 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"passport-github": "^1.1.0",
"passport-google-oauth20": "^2.0.0",
"passport-strategy": "^1.0.0",
"status-code-enum": "^1.0.0",
"uuid": "^9.0.1"
},
"repository": "[email protected]:HackIllinois/adonix.git",
Expand Down
4 changes: 2 additions & 2 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { TEST } from "./env.js";
import morgan from "morgan";
import express, { Application, Request, Response } from "express";

import Constants from "./constants.js";
import authRouter from "./services/auth/auth-router.js";
import userRouter from "./services/user/user-router.js";
import eventRouter from "./services/event/event-router.js";
Expand All @@ -14,6 +13,7 @@ import versionRouter from "./services/version/version-router.js";

import { InitializeConfigReader } from "./middleware/config-reader.js";
import Models from "./database/models.js";
import { StatusCode } from "status-code-enum";

const app: Application = express();

Expand Down Expand Up @@ -46,7 +46,7 @@ app.get("/", (_: Request, res: Response) => {

// Throw an error if call is made to the wrong API endpoint
app.use("/", (_: Request, res: Response) => {
res.status(Constants.NOT_FOUND).end("API endpoint does not exist!");
res.status(StatusCode.ClientErrorNotFound).end("API endpoint does not exist!");
});

export function setupServer(): void {
Expand Down
12 changes: 0 additions & 12 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,4 @@
abstract class Constants {
// Status codes
static readonly SUCCESS: number = 200;
static readonly CREATED: number = 201;
static readonly NO_CONTENT: number = 204;
static readonly BAD_REQUEST: number = 400;
static readonly FAILURE: number = 400;
static readonly UNAUTHORIZED_REQUEST: number = 401;
static readonly FORBIDDEN: number = 403;
static readonly NOT_FOUND: number = 404;
static readonly OLD_API: number = 418;
static readonly INTERNAL_ERROR: number = 500;

// URLs
static readonly ADMIN_DEVICE: string = "admin";
static readonly DEV_DEVICE: string = "dev";
Expand Down
8 changes: 4 additions & 4 deletions src/middleware/verify-jwt.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Request, Response, NextFunction } from "express";
import Constants from "../constants.js";
import { decodeJwtToken } from "../services/auth/auth-lib.js";
import jsonwebtoken from "jsonwebtoken";
import { StatusCode } from "status-code-enum";

/**
* @apiDefine strongVerifyErrors
Expand All @@ -22,7 +22,7 @@ export function strongJwtVerification(req: Request, res: Response, next: NextFun
const token: string | undefined = req.headers.authorization;

if (!token) {
res.status(Constants.UNAUTHORIZED_REQUEST).send({ error: "NoToken" });
res.status(StatusCode.ClientErrorUnauthorized).send({ error: "NoToken" });
next("router");
return;
}
Expand All @@ -33,10 +33,10 @@ export function strongJwtVerification(req: Request, res: Response, next: NextFun
} catch (error) {
console.error(error);
if (error instanceof jsonwebtoken.TokenExpiredError) {
res.status(Constants.FORBIDDEN).send("TokenExpired");
res.status(StatusCode.ClientErrorForbidden).send("TokenExpired");
next("router");
} else {
res.status(Constants.UNAUTHORIZED_REQUEST).send({
res.status(StatusCode.ClientErrorUnauthorized).send({
error: "InvalidToken",
});
next("router");
Expand Down
49 changes: 25 additions & 24 deletions src/services/auth/auth-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import GitHubStrategy, { Profile as GithubProfile } from "passport-github";
import { Strategy as GoogleStrategy, Profile as GoogleProfile } from "passport-google-oauth20";

import Constants from "../../constants.js";
import { StatusCode } from "status-code-enum";
import { strongJwtVerification } from "../../middleware/verify-jwt.js";
import { SelectAuthProvider } from "../../middleware/select-auth.js";

Expand Down Expand Up @@ -56,10 +57,10 @@ authRouter.get("/test/", (_: Request, res: Response) => {
authRouter.get("/dev/", (req: Request, res: Response) => {
const token: string | undefined = req.query.token as string | undefined;
if (!token) {
res.status(Constants.BAD_REQUEST).send({ error: "NoToken" });
res.status(StatusCode.ClientErrorBadRequest).send({ error: "NoToken" });
}

res.status(Constants.SUCCESS).send({ token: token });
res.status(StatusCode.SuccessOK).send({ token: token });
});

/**
Expand All @@ -85,7 +86,7 @@ authRouter.get("/login/github/", (req: Request, res: Response, next: NextFunctio
const device: string = (req.query.device as string | undefined) ?? Constants.DEFAULT_DEVICE;

if (device && !Constants.REDIRECT_MAPPINGS.has(device)) {
return res.status(Constants.BAD_REQUEST).send({ error: "BadDevice" });
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "BadDevice" });
}
return SelectAuthProvider("github", device)(req, res, next);
});
Expand Down Expand Up @@ -113,7 +114,7 @@ authRouter.get("/login/google/", (req: Request, res: Response, next: NextFunctio
const device: string = (req.query.device as string | undefined) ?? Constants.DEFAULT_DEVICE;

if (device && !Constants.REDIRECT_MAPPINGS.has(device)) {
return res.status(Constants.BAD_REQUEST).send({ error: "BadDevice" });
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "BadDevice" });
}
return SelectAuthProvider("google", device)(req, res, next);
});
Expand All @@ -133,7 +134,7 @@ authRouter.get(
},
async (req: Request, res: Response) => {
if (!req.isAuthenticated()) {
return res.status(Constants.UNAUTHORIZED_REQUEST).send({ error: "FailedAuth" });
return res.status(StatusCode.ClientErrorUnauthorized).send({ error: "FailedAuth" });
}

const device: string = (res.locals.device ?? Constants.DEFAULT_DEVICE) as string;
Expand Down Expand Up @@ -162,7 +163,7 @@ authRouter.get(
return res.redirect(url);
} catch (error) {
console.error(error);
return res.status(Constants.BAD_REQUEST).send({ error: "InvalidData" });
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "InvalidData" });
}
},
);
Expand Down Expand Up @@ -199,17 +200,17 @@ authRouter.get("/roles/:USERID", strongJwtVerification, async (req: Request, res

// Cases: Target user already logged in, auth user is admin
if (payload.id == targetUser) {
return res.status(Constants.SUCCESS).send({ id: payload.id, roles: payload.roles });
return res.status(StatusCode.SuccessOK).send({ id: payload.id, roles: payload.roles });
} else if (hasElevatedPerms(payload)) {
try {
const roles: Role[] = await getRoles(targetUser);
return res.status(Constants.SUCCESS).send({ id: targetUser, roles: roles });
return res.status(StatusCode.SuccessOK).send({ id: targetUser, roles: roles });
} catch (error) {
console.error(error);
return res.status(Constants.BAD_REQUEST).send({ error: "UserNotFound" });
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "UserNotFound" });
}
} else {
return res.status(Constants.FORBIDDEN).send("Forbidden");
return res.status(StatusCode.ClientErrorForbidden).send("Forbidden");
}
});

Expand Down Expand Up @@ -239,31 +240,31 @@ authRouter.put("/roles/:OPERATION/", strongJwtVerification, async (req: Request,

// Not authenticated with modify roles perms
if (!hasElevatedPerms(payload)) {
return res.status(Constants.FORBIDDEN).send({ error: "Forbidden" });
return res.status(StatusCode.ClientErrorForbidden).send({ error: "Forbidden" });
}

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

// No operation - fail out
if (!op) {
return res.status(Constants.BAD_REQUEST).send({ error: "InvalidOperation" });
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "InvalidOperation" });
}

// Check if role to add/remove actually exists
const data: ModifyRoleRequest = req.body as ModifyRoleRequest;
const role: Role | undefined = Role[data.role.toUpperCase() as keyof typeof Role];
if (!role) {
return res.status(Constants.BAD_REQUEST).send({ error: "InvalidRole" });
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "InvalidRole" });
}

// Try to update roles, if possible
try {
const newRoles: Role[] = await updateRoles(data.id, role, op);
return res.status(Constants.SUCCESS).send({ id: data.id, roles: newRoles });
return res.status(StatusCode.SuccessOK).send({ id: data.id, roles: newRoles });
} catch (error) {
console.error(error);
return res.status(Constants.INTERNAL_ERROR).send({ error: "InternalError" });
return res.status(StatusCode.ServerErrorInternal).send({ error: "InternalError" });
}
});

Expand All @@ -289,15 +290,15 @@ authRouter.get("/list/roles/", strongJwtVerification, (_: Request, res: Response

// Check if current user should be able to access all roles
if (!hasElevatedPerms(payload)) {
return res.status(Constants.FORBIDDEN).send({ error: "Forbidden" });
return res.status(StatusCode.ClientErrorForbidden).send({ error: "Forbidden" });
}

// Filter enum to get all possible string keys
const roles: string[] = Object.keys(Role).filter((item: string) => {
return isNaN(Number(item));
});

return res.status(Constants.SUCCESS).send({ roles: roles });
return res.status(StatusCode.SuccessOK).send({ roles: roles });
});

/**
Expand All @@ -322,11 +323,11 @@ authRouter.get("/roles/", strongJwtVerification, async (_: Request, res: Respons

await getRoles(targetUser)
.then((roles: Role[]) => {
return res.status(Constants.SUCCESS).send({ id: targetUser, roles: roles });
return res.status(StatusCode.SuccessOK).send({ id: targetUser, roles: roles });
})
.catch((error: Error) => {
console.error(error);
return res.status(Constants.BAD_REQUEST).send({ error: "UserNotFound" });
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "UserNotFound" });
});
});

Expand All @@ -351,16 +352,16 @@ authRouter.get("/roles/list/:ROLE", async (req: Request, res: Response) => {

//Returns error if role parameter is empty
if (!role) {
return res.status(Constants.BAD_REQUEST).send({ error: "InvalidParams" });
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "InvalidParams" });
}

return await getUsersWithRole(role)
.then((users: string[]) => {
return res.status(Constants.SUCCESS).send({ userIds: users });
return res.status(StatusCode.SuccessOK).send({ userIds: users });
})
.catch((error: Error) => {
console.error(error);
return res.status(Constants.BAD_REQUEST).send({ error: "Unknown Error" });
return res.status(StatusCode.ClientErrorBadRequest).send({ error: "Unknown Error" });
});
});

Expand Down Expand Up @@ -392,10 +393,10 @@ authRouter.get("/token/refresh", strongJwtVerification, async (_: Request, res:

// Create and return a new token with the payload
const newToken: string = generateJwtToken(newPayload);
return res.status(Constants.SUCCESS).send({ token: newToken });
return res.status(StatusCode.SuccessOK).send({ token: newToken });
} catch (error) {
console.error(error);
return res.status(Constants.INTERNAL_ERROR).send({ error: "InternalError" });
return res.status(StatusCode.ServerErrorInternal).send({ error: "InternalError" });
}
});

Expand Down
Loading

0 comments on commit 347e69d

Please sign in to comment.