Created the authentication middleware
This commit is contained in:
parent
b8c8fa700b
commit
227ae68555
28
api/middlewares/authenticate.ts
Normal file
28
api/middlewares/authenticate.ts
Normal 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();
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user