60 lines
2.2 KiB
JavaScript
60 lines
2.2 KiB
JavaScript
"use strict";
|
|
/**
|
|
* Express authentication middleware.
|
|
* Validates JWT bearer tokens and attaches the decoded payload to the request.
|
|
* Provides role-based access control via higher-order middleware factories.
|
|
*/
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.authMiddleware = authMiddleware;
|
|
exports.requireRoles = requireRoles;
|
|
exports.requireStaff = requireStaff;
|
|
const authService_1 = require("../services/authService");
|
|
const onlinePresence_1 = require("../realtime/redis/onlinePresence");
|
|
/**
|
|
* Verifies the Authorization bearer token and attaches the decoded user to the request.
|
|
* @param req Express request (extended as AuthRequest on success)
|
|
* @param res Express response; sends 401 when the token is missing, invalid, or expired
|
|
* @param next Calls next() when authentication succeeds
|
|
*/
|
|
async function authMiddleware(req, res, next) {
|
|
const authHeader = req.headers.authorization;
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
res.status(401).json({ error: 'Unauthorized' });
|
|
return;
|
|
}
|
|
const token = authHeader.slice(7);
|
|
try {
|
|
const payload = await (0, authService_1.verifyToken)(token);
|
|
req.user = payload;
|
|
if (payload.userId)
|
|
void (0, onlinePresence_1.touchAppPresence)(payload.userId);
|
|
next();
|
|
}
|
|
catch {
|
|
res.status(401).json({ error: 'Invalid or expired token' });
|
|
}
|
|
}
|
|
/**
|
|
* Returns middleware that restricts access to requests whose user role is in the allowed list.
|
|
* Must run after authMiddleware so req.user is populated.
|
|
* @param roles One or more role names that are permitted (e.g. 'admin')
|
|
* @returns Express middleware that responds 401 without a user or 403 when the role is not allowed
|
|
*/
|
|
function requireRoles(...roles) {
|
|
return (req, res, next) => {
|
|
if (!req.user) {
|
|
res.status(401).json({ error: 'Unauthorized' });
|
|
return;
|
|
}
|
|
if (!roles.includes(req.user.role)) {
|
|
res.status(403).json({ error: 'Forbidden' });
|
|
return;
|
|
}
|
|
next();
|
|
};
|
|
}
|
|
/** Admin or moderator — support desk and similar staff tools. */
|
|
function requireStaff() {
|
|
return requireRoles('admin', 'moderator');
|
|
}
|
|
//# sourceMappingURL=auth.js.map
|