Created the authentication middleware

This commit is contained in:
Mathias Wagner 2022-09-08 22:29:38 +02:00
parent b8c8fa700b
commit 227ae68555
Signed by: Mathias
GPG Key ID: B8DC354B0A1F5B44

View File

@ -0,0 +1,28 @@
import {IToken, Token} from "../../models/Token";
import {IUser, User} from "../../models/User";
import {NextFunction, Request, Response} from "express";
export interface AuthenticatedRequest extends Request {
token: IToken
user: IUser
}
module.exports.authenticate = async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
// Get the token header
const authHeader = req.headers["authorization"];
if (!authHeader) return res.status(400).json({message: "You need to provide the 'authorization' header"});
// Validate token header
const splitHeader = authHeader.split(" ");
if (splitHeader.length !== 2) return res.status(400).json({message: "You need to provide the token in the 'authorization' header"});
// Check if the provided token is wrong
req.token = await Token.findOne({token: splitHeader[1]}).exec() as IToken;
if (req.token == null) return res.status(401).json({message: "The provided token is wrong"});
// Check if the provided user exists
req.user = await User.findOne({clientId: req.token.clientId}) as IUser;
if (req.user == null) return res.status(401).json({message: "The provided token is wrong"});
next();
}