Implementar modulo de Auth
This commit is contained in:
43
backend/src/modules/auth/auth.middleware.ts
Normal file
43
backend/src/modules/auth/auth.middleware.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
export const authMiddleware = (
|
||||
req:Request,
|
||||
res:Response,
|
||||
next:NextFunction
|
||||
) => {
|
||||
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if(!authHeader){
|
||||
return res.status(401).json({
|
||||
message:"Token requerido"
|
||||
});
|
||||
}
|
||||
|
||||
const token = authHeader.split(" ")[1];
|
||||
|
||||
if (!token)
|
||||
{
|
||||
return res.status(401).json({
|
||||
message:"Token invalido"
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
const decoded = jwt.verify (
|
||||
token,
|
||||
process.env.JWT_SECRET as string,
|
||||
);
|
||||
|
||||
(req as any).user =
|
||||
decoded;
|
||||
|
||||
next();
|
||||
} catch{
|
||||
return res.status(401).json({
|
||||
message:"Token invalido"
|
||||
});
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user