mirror of
https://github.com/cheveguerra/whaticket-community.git
synced 2026-04-18 11:49:19 +00:00
40 lines
824 B
TypeScript
40 lines
824 B
TypeScript
import { verify } from "jsonwebtoken";
|
|
import { Request, Response, NextFunction } from "express";
|
|
|
|
import AppError from "../errors/AppError";
|
|
import authConfig from "../config/auth";
|
|
|
|
interface TokenPayload {
|
|
id: string;
|
|
username: string;
|
|
profile: string;
|
|
iat: number;
|
|
exp: number;
|
|
}
|
|
|
|
const isAuth = (req: Request, res: Response, next: NextFunction): void => {
|
|
const authHeader = req.headers.authorization;
|
|
|
|
if (!authHeader) {
|
|
throw new AppError("Token was not provided.", 403);
|
|
}
|
|
|
|
const [, token] = authHeader.split(" ");
|
|
|
|
try {
|
|
const decoded = verify(token, authConfig.secret);
|
|
const { id, profile } = decoded as TokenPayload;
|
|
|
|
req.user = {
|
|
id,
|
|
profile
|
|
};
|
|
} catch (err) {
|
|
throw new AppError("Invalid token.", 403);
|
|
}
|
|
|
|
return next();
|
|
};
|
|
|
|
export default isAuth;
|