2022-03-05 22:57:23 +04:00
|
|
|
import { NextFunction, Request, Response } from 'express';
|
|
|
|
import jwt from 'jsonwebtoken';
|
2022-09-29 06:41:24 +08:00
|
|
|
import appConfig from "../../utils/appConfig.js";
|
2022-03-05 22:57:23 +04:00
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Middleware for checking jwt token
|
|
|
|
*
|
|
|
|
* @param req - request object
|
|
|
|
* @param res - response object
|
|
|
|
* @param next - next function
|
|
|
|
*/
|
|
|
|
export default async function verifyToken(req: Request, res: Response, next: NextFunction): Promise<void> {
|
|
|
|
const token = req.cookies.authToken;
|
|
|
|
|
|
|
|
try {
|
2022-09-29 06:41:24 +08:00
|
|
|
if (!appConfig.password) {
|
2022-03-05 22:57:23 +04:00
|
|
|
res.locals.isAuthorized = false;
|
|
|
|
next();
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-09-29 06:41:24 +08:00
|
|
|
const decodedToken = jwt.verify(token, appConfig.password + appConfig.auth.secret);
|
2022-03-05 22:57:23 +04:00
|
|
|
|
|
|
|
res.locals.isAuthorized = !!decodedToken;
|
|
|
|
|
|
|
|
next();
|
|
|
|
} catch (err) {
|
|
|
|
res.locals.isAuthorized = false;
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
}
|