Skip to content
Snippets Groups Projects
Commit c5f2c84a authored by Ricardo's avatar Ricardo
Browse files

Issue#12 ADD middleware authenticator

parent 9c4f1ca5
No related branches found
No related tags found
1 merge request!14Issue#12 ADD middleware authenticator
import { type Request, type Response, type NextFunction } from "express";
import jwt, { type JwtPayload } from "jsonwebtoken";
interface AuthenticatedRequest extends Request {
user?: JwtPayload | string;
}
export const tokenAuthenticator = async ( req: Request, res: Response, next: NextFunction): Promise<void> => {
if (!req.headers.authorization)
{
res.status(401).json({ message: "Unauthorized"});
return;
}
const token = req.headers.authorization?.split(" ")[1]; //pega o token do cabecalho da requisicao, undefined se nao achar
if (!token)
{
res.status(401).json({ message: "Token Not Found"});
return;
}
try{
const decoded = jwt.verify(token, process.env["APP_SECRET"] as string) as JwtPayload; //valida o token com app_secret, e atribui como jwtpayload
const reqAuth = req as AuthenticatedRequest;
reqAuth.user = decoded; //req recebe o jwtpayload da validacao
next();
} catch (error) {
res.status(403).json({ message: "Invalid Token"});
}
};
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment