2022-01-06 01:26:15 +00:00
|
|
|
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 => {
|
2024-02-21 20:47:23 +00:00
|
|
|
const authHeader = req.headers.authorization;
|
2022-01-06 01:26:15 +00:00
|
|
|
|
|
|
|
if (!authHeader) {
|
|
|
|
throw new AppError("ERR_SESSION_EXPIRED", 401);
|
|
|
|
}
|
|
|
|
|
2024-04-02 14:59:44 +00:00
|
|
|
const [, token] = authHeader.split(" ");
|
2024-02-21 20:47:23 +00:00
|
|
|
|
|
|
|
if (
|
2024-04-02 14:59:44 +00:00
|
|
|
(req.originalUrl == "/queue/remote/list" ||
|
|
|
|
req.originalUrl == "/tickets/remote/create") &&
|
2024-02-21 20:47:23 +00:00
|
|
|
token === process.env.TOKEN_REMOTE_TICKET_CREATION
|
|
|
|
) {
|
|
|
|
return next();
|
|
|
|
}
|
2022-01-06 01:26:15 +00:00
|
|
|
|
|
|
|
try {
|
2024-02-21 20:47:23 +00:00
|
|
|
const decoded = verify(token, authConfig.secret);
|
2023-09-19 12:41:15 +00:00
|
|
|
|
2022-01-06 01:26:15 +00:00
|
|
|
const { id, profile } = decoded as TokenPayload;
|
|
|
|
|
|
|
|
req.user = {
|
|
|
|
id,
|
|
|
|
profile
|
|
|
|
};
|
|
|
|
} catch (err) {
|
|
|
|
throw new AppError(
|
|
|
|
"Invalid token. We'll try to assign a new one on next request",
|
|
|
|
403
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return next();
|
|
|
|
};
|
|
|
|
|
|
|
|
export default isAuth;
|