Junior — Middle
Describe the approach to implementing an authentication and access control system for three user levels: regular users, managers, and administrators.
sobes.tech AI
Answer from AI
To implement an authentication and access restriction system with three user levels (regular users, managers, administrators), the following approach can be used:
-
Authentication:
- Use JWT (JSON Web Tokens) or sessions to verify the user's identity.
- During login, verify credentials and issue a token with user role information.
-
Access restriction (authorization):
- Store the user role in the token or session.
- At the middleware level, check the role and allow or deny access to certain routes or operations.
-
Example role structure:
user— basic rights, access to personal account and main functions.manager— extended rights, such as managing a group of users or viewing reports.admin— full access, including system management and settings.
Example middleware in Node.js using Express and JWT:
const jwt = require('jsonwebtoken');
function authorize(allowedRoles) {
return (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).send('Unauthorized');
try {
const payload = jwt.verify(token, 'your_secret_key');
if (!allowedRoles.includes(payload.role)) {
return res.status(403).send('Forbidden');
}
req.user = payload;
next();
} catch (e) {
return res.status(401).send('Invalid token');
}
};
}
// Usage:
// app.get('/admin', authorize(['admin']), (req, res) => { ... });
Thus, the system will control access based on roles, ensuring security and convenience.