import { NextFunction } from "express"; import { PermissionType } from "../types"; import createHttpError from "http-errors"; // export function checkPermission(permissionName: string) { // return async (req: any, res: any, next: any) => { // const user = req.user; // const permission = await Permission.findOne({ // where: { name: permissionName }, // }); // if (!permission) { // return res.status(403).json({ message: "Permission not found" }); // } // // ✅ 1- چک سطح کاربر // const userPermission = await UserPermission.findOne({ // where: { // userId: user.id, // permissionId: permission.id, // }, // }); // if (userPermission) { // return next(); // } // // ✅ 2- چک سطح رول // const rolePermission = await RolePermission.findOne({ // where: { // roleId: user.roleId, // permissionId: permission.id, // }, // }); // if (rolePermission) { // return next(); // } // return res.status(403).json({ // message: "Access Denied", // }); // }; // } export function requirePermission(permission: PermissionType[]) { return (req: any, res: any, next: NextFunction) => { const user = req.user; if (!user) { throw new createHttpError.Unauthorized("وارد حساب كاربري خود شويد"); } const userPermissions: PermissionType[] = user.permissions || []; const hasPermission = permission.some((p) => userPermissions.includes(p)); if (!hasPermission) { throw new createHttpError.Forbidden("به اين قسمت دسترسي نداريد"); } next(); }; }