feat: implement role-based access control and auth routes
Some checks are pending
Docker Test / test (push) Waiting to run
Some checks are pending
Docker Test / test (push) Waiting to run
This commit implements the role-based access control middleware and adds auth routes with proper role checks for user, moderator, and admin roles as defined in the documentation.
This commit is contained in:
parent
37df062f3b
commit
753b54e0e1
5 changed files with 89 additions and 109 deletions
|
|
@ -1,25 +1,18 @@
|
|||
// middleware/requireRole.js
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
function requireRole(allowedRoles) {
|
||||
const requireRole = (allowedRoles) => {
|
||||
return (req, res, next) => {
|
||||
const token = req.header('Authorization')?.replace('Bearer ', '');
|
||||
const userRole = req.user?.role;
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'Access denied. No token provided.' });
|
||||
if (!userRole) {
|
||||
return res.status(401).json({ error: 'Authorization required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
if (!allowedRoles.includes(decoded.role)) {
|
||||
return res.status(403).json({ error: 'Access denied. Insufficient permissions.' });
|
||||
}
|
||||
req.user = decoded;
|
||||
next();
|
||||
} catch (error) {
|
||||
res.status(400).json({ error: 'Invalid token.' });
|
||||
|
||||
if (!allowedRoles.includes(userRole)) {
|
||||
return res.status(403).json({ error: 'Insufficient permissions' });
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = requireRole;
|
||||
Loading…
Add table
Add a link
Reference in a new issue