// FILE: src/middleware/permissions.js // Permission calculation and enrichment middleware // - Computes effective permissions for a user based on their roles // - Attaches permissions to req.user.permissions import { Role, Permission, UserRole, RolePermission } from "../db/sequelize.js"; /** * คืนชุด permission (string[]) ของ user_id */ export async function computeEffectivePermissions(user_id) { // ดึง roles ของผู้ใช้ const userRoles = await UserRole.findAll({ where: { user_id } }); const roleIds = userRoles.map((r) => r.role_id); if (!roleIds.length) return []; // ดึง permission ผ่าน role_permissions const rp = await RolePermission.findAll({ where: { role_id: roleIds } }); const permIds = [...new Set(rp.map((x) => x.permission_id))]; if (!permIds.length) return []; const perms = await Permission.findAll({ where: { permission_id: permIds } }); return [...new Set(perms.map((p) => p.permission_name))]; } /** * middleware: เติม permissions ลง req.user.permissions */ export function enrichPermissions() { return async (req, _res, next) => { if (!req.user?.user_id) return next(); try { const perms = await computeEffectivePermissions(req.user.user_id); req.user.permissions = perms; } catch (e) { req.user.permissions = []; } next(); }; }