diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..2c002e37c49cd9ff6181e3576be165e168a3a2e1 100644 --- a/src/middleware/auth.ts +++ b/src/middleware/auth.ts @@ -0,0 +1,31 @@ +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