Files
Zumri-Backend/app/middleware/permission.middleware.js
Sathira Sri Sathara 9d3d431416 feat: implement identity and security features
- Added account types and privileged account types constants.
- Created admin user controller for updating user security fields.
- Developed role assignment controller for managing user roles.
- Implemented validation middleware for request schemas.
- Defined user role and auth session models for database interactions.
- Created services for authentication, email notifications, and OTP handling.
- Developed OAuth service for Google and Apple authentication.
- Added JWT utility functions for token generation and verification.
- Implemented comprehensive tests for authentication, session management, and password policies.
- Created migration for updating user schema and adding new tables for auth sessions and user identities.
2026-09-03 13:56:18 +05:30

26 lines
1.8 KiB
JavaScript

const { ACCOUNT_TYPES } = require("../constants/accountTypes");
const authorizedAccountType = (allowedTypes) => (req, res, next) => {
if (!req.user) return res.status(401).json({ success: false, error: { code: "UNAUTHORIZED", message: "Authentication required" } });
if (req.user.accountType !== ACCOUNT_TYPES.SUPER_ADMIN && !allowedTypes.includes(req.user.accountType)) return res.status(403).json({ success: false, error: { code: "FORBIDDEN", message: "Access denied" } });
next();
};
const checkPermission = (baseOrFull, options = {}) => (req, res, next) => {
if (!req.user) return res.status(401).json({ success: false, error: { code: "UNAUTHORIZED", message: "Authentication required" } });
if (req.user.accountType === ACCOUNT_TYPES.SUPER_ADMIN) return next();
const actions = { GET: "view", POST: "create", PUT: "update", PATCH: "update", DELETE: "delete" };
const required = options.custom ? baseOrFull : `${baseOrFull}.${actions[req.method]}`;
const permissions = req.user.permissions || [];
const allowed = permissions.includes(required) || permissions.some((value) => value.endsWith(".*") && required.startsWith(value.slice(0, -1)));
if (!allowed) return res.status(403).json({ success: false, error: { code: "FORBIDDEN", message: "Access denied" } });
next();
};
const requireOwnership = (param = "id") => (req, res, next) => {
if (req.user.accountType === ACCOUNT_TYPES.SUPER_ADMIN || req.user.accountType === ACCOUNT_TYPES.ADMIN || req.user.id === req.params[param]) return next();
return res.status(403).json({ success: false, error: { code: "FORBIDDEN", message: "Access denied" } });
};
module.exports = { authorizedAccountType, requireAccountType: authorizedAccountType, checkPermission, requirePermission: checkPermission, requireOwnership };