From 14f08f05ac6960be10251777de9fbb1169ad00bd Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Sat, 30 Jan 2021 19:57:07 +0100 Subject: [PATCH] :sparkles: Authentication --- src/middlewares/Authentication.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/middlewares/Authentication.ts diff --git a/src/middlewares/Authentication.ts b/src/middlewares/Authentication.ts new file mode 100644 index 00000000..5a1241f3 --- /dev/null +++ b/src/middlewares/Authentication.ts @@ -0,0 +1,30 @@ +import jwt from "jsonwebtoken"; +import { NextFunction, Request, Response } from "express"; +import { HTTPError } from "lambert-server"; +import Config from "../util/Config"; +import { JWTOptions } from "../util/Constants"; + +export const NO_AUTHORIZATION_ROUTES = ["/api/v8/auth/login", "/api/v8/auth/register"]; + +declare global { + namespace Express { + interface Request { + userid: any; + token: any; + } + } +} + +export function Authentication(req: Request, res: Response, next: NextFunction) { + if (NO_AUTHORIZATION_ROUTES.includes(req.url)) return next(); + if (!req.headers.authorization) return next(new HTTPError("Missing Authorization Header", 401)); + + return jwt.verify(req.headers.authorization, Config.get().server.jwtSecret, JWTOptions, (err, decoded: any) => { + if (err || !decoded) return next(new HTTPError("Invalid Token", 401)); + + req.token = decoded; + req.userid = decoded.id; + + return next(); + }); +}