generated from li0nhunter/Website-template
65 lines
2.9 KiB
JavaScript
65 lines
2.9 KiB
JavaScript
import jwt from "jsonwebtoken";
|
|
/** @typedef {import("@types/express").Request} Request */
|
|
/** @typedef {import("@types/express").Response} Response */
|
|
/** @typedef {import("@types/express").NextFunction} NextFunction */
|
|
|
|
export default {
|
|
/**
|
|
* Express middleware to verify JWT and check for the admin role.
|
|
* @param {Request} req
|
|
* @param {Response} res
|
|
* @param {NextFunction} next
|
|
* @returns {Promise<e.Response<any, Record<string, any>> | void>}
|
|
*/
|
|
authenticateAdmin: async (req, res, next) => {
|
|
const token = req.headers.authorization;
|
|
|
|
if (!token) return res.status(401).send({data: null, error: "Token missing"});
|
|
try {
|
|
const payload = await new Promise((resolve, reject) => {
|
|
jwt.verify(token, process.env.JWT_SECRET || "super-secret-key", (err, decoded) => {
|
|
if (err) return reject(err);
|
|
return resolve(decoded);
|
|
});
|
|
});
|
|
// Check if payload has id and role and if the role is admin
|
|
if (!payload || !payload.id || !payload.role) return res.status(401).json({data: null, error: "Invalid token"});
|
|
if (payload.role !== "admin") return res.status(403).json({data: null, error: "admins only"});
|
|
next();
|
|
} catch (err) {
|
|
if (err instanceof Error && err.message === 'jwt expired') return res.status(401).json({data: null, message: "Token expired", error: err});
|
|
res.status(401).json({data: null, message: "Invalid token", error: err});
|
|
}
|
|
},
|
|
/**
|
|
* Express middleware to verify JWT and check for the user role.
|
|
* @param {Request} req
|
|
* @param {Response} res
|
|
* @param {NextFunction} next
|
|
* @returns {Promise<e.Response<any, Record<string, any>> | void>}
|
|
*/
|
|
authenticateUser: async (req, res, next) => {
|
|
const token = req.headers.authorization;
|
|
|
|
if (!token) {
|
|
return res.status(401).send({data: null, error: "Token missing"});
|
|
}
|
|
try {
|
|
const payload = jwt.verify(token, process.env.JWT_SECRET || "super-secret-key");
|
|
// Check if payload has id and role
|
|
if (!payload || !payload.id || !payload.role) {
|
|
return res.status(401).json({data: null, error: "Invalid token"});
|
|
}
|
|
// check if the user id matches the id in the token
|
|
else if (payload.role !== "admin" && req.params.id && req.params.id !== payload.id.toString()) {
|
|
return res.status(403).json({data: null, error: "Forbidden"});
|
|
}
|
|
next();
|
|
} catch (err) {
|
|
if (err instanceof Error && err.message === 'jwt expired') {
|
|
return res.status(401).json({data: null, message: "Token expired", error: err});
|
|
}
|
|
res.status(401).json({data: null, message: "Invalid token", error: err});
|
|
}
|
|
}
|
|
} |