Tidy auth middleware

Signed-off-by: Fred Boniface <fred@fjla.uk>
This commit is contained in:
Fred Boniface 2024-03-10 21:01:00 +00:00
parent 236d85648d
commit 87532b001d

View File

@ -1,46 +1,45 @@
import { NextFunction, Request, Response } from "express"; import type { NextFunction, Request, Response } from "express";
import { logger } from "../utils/logger.utils";
const utils = require("../utils/auth.utils"); import { isAuthed } from "../utils/auth.utils";
const logger = require("../utils/logger.utils");
module.exports = async function authCheck( module.exports = async function authCheck(
req: Request, req: Request,
res: Response, res: Response,
next: NextFunction next: NextFunction
) { ) {
logger.logger.debug("auth.middleware: Auth check begun"); logger.debug("auth.middleware: Auth check begun");
if (process.env.NODE_ENV === "development") { if (process.env.NODE_ENV === "development") {
req.isAuthed = true; req.isAuthed = true;
logger.logger.warn("auth.middleware: DEV MODE - Access Granted"); logger.warn("auth.middleware: DEV MODE - Access Granted");
next(); next();
} else { } else {
const id: string | string[] | undefined = req.headers.uuid; const id: string | string[] | undefined = req.headers.uuid;
if (typeof id === "undefined") { if (typeof id === "undefined") {
req.isAuthed = false; req.isAuthed = false;
logger.logger.info("auth.middleware: Authentication failed"); logger.info("auth.middleware: Authentication failed");
next(); next();
} else if (typeof id === "string") { } else if (typeof id === "string") {
const authCheck = (await utils.isAuthed(id)) || false; const authCheck = (await isAuthed(id)) || false;
if (authCheck) { if (authCheck) {
req.isAuthed = true; req.isAuthed = true;
logger.logger.info("auth.middleware: Authentication Successful"); logger.info("auth.middleware: Authentication Successful");
next(); next();
} else { } else {
req.isAuthed = false; req.isAuthed = false;
logger.logger.info("auth.middleware: Authentication Failed"); logger.info("auth.middleware: Authentication Failed");
next(); next();
} }
} else if (Array.isArray(id)) { } else if (Array.isArray(id)) {
const authCheck = (await utils.isAuthed(id[0])) || false; const authCheck = (await isAuthed(id[0])) || false;
if (authCheck) { if (authCheck) {
req.isAuthed = true; req.isAuthed = true;
logger.logger.warn( logger.warn(
"auth.middleware: UUID Passed as Array - Authentication Successful" "auth.middleware: UUID Passed as Array - Authentication Successful"
); );
next(); next();
} else { } else {
req.isAuthed = false; req.isAuthed = false;
logger.logger.warn( logger.warn(
"auth.middleware: UUID Passed as Array - Authentication Failed" "auth.middleware: UUID Passed as Array - Authentication Failed"
); );
next(); next();