Created the authentication middleware

This commit is contained in:
Mathias Wagner 2023-01-15 20:34:07 +01:00
parent 76b2128320
commit da39af1888
Signed by: Mathias
GPG Key ID: B8DC354B0A1F5B44

20
src/middlewares/auth.ts Normal file
View File

@ -0,0 +1,20 @@
import { NextFunction, Request, Response } from "express";
import { ISession, Session } from "@models/Session";
import { encryptClearField } from "@utils/decryption";
import { Account, IAccount } from "@models/Account";
export const authenticate = async (req: Request, res: Response, next: NextFunction) => {
const authHeader = req.header("authorization");
if (!authHeader) return res.status(400).json({ message: "You need to provide the 'authorization' header" });
const headerTrimmed = authHeader.split(" ");
if (headerTrimmed.length !== 2) return res.status(400).json({ message: "You need to provide the token in the 'authorization' header" });
req.session = await Session.findOne({ token: encryptClearField(headerTrimmed[1]) }) as ISession;
if (req.session === null || !req?.session?.verified) return res.status(401).json({ message: "The provided token is wrong" });
req.user = await Account.findById(req.session.userId) as IAccount;
if (req.user === null || !req?.user?.verified) return res.status(401).json({ message: "The account associated to the token is not registered" });
next();
};