const Company = require('../models/Company'); const User = require('../models/User'); // Middleware to check if user has access to the company exports.checkCompanyAccess = async (req, res, next) => { try { const companyId = req.params.companyId || req.body.companyId; if (!companyId) { return res.status(400).json({ success: false, message: 'Company ID is required' }); } // Superadmin has access to all companies if (req.user.role === 'superadmin') { return next(); } // Check if user belongs to the requested company if (req.user.companyId && req.user.companyId.toString() === companyId) { return next(); } return res.status(403).json({ success: false, message: 'Not authorized to access data from this company' }); } catch (error) { next(error); } }; // Middleware to check if user can manage other users exports.checkUserManagementAccess = async (req, res, next) => { try { const targetUserId = req.params.id; if (!targetUserId) { return next(); } // Get the target user const targetUser = await User.findById(targetUserId); if (!targetUser) { return res.status(404).json({ success: false, message: 'User not found' }); } // Superadmin can manage any user if (req.user.role === 'superadmin') { return next(); } // Company admin can only manage employers in their company if (req.user.role === 'companyadmin') { // Check if target user is from the same company if (targetUser.companyId.toString() !== req.user.companyId.toString()) { return res.status(403).json({ success: false, message: 'Not authorized to manage users from other companies' }); } // Check if target user is not a company admin if (targetUser.role === 'companyadmin') { return res.status(403).json({ success: false, message: 'Company admin cannot manage other company admins' }); } return next(); } // Employers cannot manage users return res.status(403).json({ success: false, message: 'Not authorized to manage users' }); } catch (error) { next(error); } };