-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadmin.js
More file actions
43 lines (37 loc) · 1.23 KB
/
admin.js
File metadata and controls
43 lines (37 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Admin authentication middleware.
* Verifies that the authenticated user has admin role or admin scope.
*/
import { authenticateJWT } from './jwt.js';
import { throwUnauthorized, throwForbidden } from '../middleware/responseHelpers.js';
import { isAdmin } from './permissions.js';
import logger from '../logging/logger.js';
/**
* Middleware to require admin authentication.
* Must be used after authenticateJWT middleware.
*
* Checks if the authenticated user has role='admin' or scope='admin'.
*/
export const requireAdmin = (req, res, next) => {
// authenticateJWT should have already set req.user
if (!req.user) {
logger.warn('Admin access attempted without authentication', { ip: req.ip });
throwUnauthorized('Authentication required');
}
if (!isAdmin(req.user)) {
logger.warn('Non-admin user attempted admin access', {
username: req.user.username,
role: req.user.role,
scopes: req.user.scopes || req.user.scope,
ip: req.ip,
path: req.path,
});
throwForbidden('Admin access required');
}
next();
};
/**
* Combined middleware: authenticate JWT and require admin.
* Use this for admin-only endpoints.
*/
export const authenticateAdmin = [authenticateJWT, requireAdmin];