This example shows how Express middleware first checks if the user is authenticated, then if they are authorized to access the admin page.
import express from 'express';
const app = express();
function authenticate(req, res, next) {
if (req.headers.authorization === 'valid-token') {
req.user = { id: 1, role: 'admin' };
next();
} else {
res.status(401).send('Not authenticated');
}
}
function authorize(req, res, next) {
if (req.user.role === 'admin') {
next();
} else {
res.status(403).send('Not authorized');
}
}
app.use(authenticate);
app.get('/admin', authorize, (req, res) => {
res.send('Welcome Admin');
});
// Simulate a request with valid token
const req = { headers: { authorization: 'valid-token' } };
const res = {
status(code) { this.statusCode = code; return this; },
send(message) { this.message = message; }
};
let nextCalled = false;
function next() { nextCalled = true; }
// Run authenticate
authenticate(req, res, () => {
// Run authorize
authorize(req, res, () => {
res.send('Welcome Admin');
});
});
console.log(res.message || res.statusCode);