( requiredPermissions: Permission | Permission[], requireAll: boolean = true )
| 66 | * @param requireAll - If true, user must have ALL permissions. If false, only ONE permission is required |
| 67 | */ |
| 68 | export function requirePermission( |
| 69 | requiredPermissions: Permission | Permission[], |
| 70 | requireAll: boolean = true |
| 71 | ) { |
| 72 | return async (req: any, res: any, next: any) => { |
| 73 | try { |
| 74 | const user = await checkSession(req); |
| 75 | const config = await prisma.config.findFirst(); |
| 76 | |
| 77 | if (config?.roles_active) { |
| 78 | const userWithRoles = user |
| 79 | ? await prisma.user.findUnique({ |
| 80 | where: { id: user.id }, |
| 81 | include: { |
| 82 | roles: true, |
| 83 | }, |
| 84 | }) |
| 85 | : null; |
| 86 | |
| 87 | if (!userWithRoles) { |
| 88 | return res.status(401).send({ |
| 89 | message: "Unauthorized", |
| 90 | success: false, |
| 91 | }); |
| 92 | } |
| 93 | |
| 94 | if (!hasPermission(userWithRoles, requiredPermissions, requireAll)) { |
| 95 | return res.status(401).send({ |
| 96 | message: |
| 97 | "You do not have the required permission to access this resource.", |
| 98 | success: false, |
| 99 | status: 403, |
| 100 | }); |
| 101 | } |
| 102 | |
| 103 | return; |
| 104 | } else { |
| 105 | return; |
| 106 | } |
| 107 | } catch (error) { |
| 108 | next(error); |
| 109 | } |
| 110 | }; |
| 111 | } |
| 112 | |
| 113 | // Usage examples: |
| 114 | /* |
no test coverage detected