39647-vm/backend/middleware/authMiddleware.js
tornikegerantia 171fd243de Implement a fully functional user login and registration system
Refactor the authentication system to separate login and registration forms, implement password hashing, manage JWT tokens, and enable user data persistence in `backend/data/users.json`.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 375ec6d3-d5af-4f82-ab81-5c60fd4a86a3
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: 8d427c3d-aa60-488b-82c4-6cef148ba5d7
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/147e665c-8c0d-48ec-b0ad-fdc89cd4460f/375ec6d3-d5af-4f82-ab81-5c60fd4a86a3/e238nM8
Replit-Helium-Checkpoint-Created: true
2026-04-15 00:19:58 +00:00

69 lines
1.7 KiB
JavaScript

const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
// Protect routes - verify JWT token
exports.protect = async (req, res, next) => {
let token;
// Check for token in headers
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
token = req.headers.authorization.split(' ')[1];
}
// Check for token in cookies (if using cookies)
// else if (req.cookies.token) {
// token = req.cookies.token;
// }
if (!token) {
return res.status(401).json({ message: 'Not authorized to access this route' });
}
try {
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your_secret_key');
// Get user from token
const user = await User.findById(decoded.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
user.id = user._id;
req.user = user;
next();
} catch (error) {
return res.status(401).json({ message: 'Not authorized to access this route' });
}
};
// Authorize specific roles
exports.authorize =
(...allowedRoles) =>
(req, res, next) => {
if (!req.user) {
return res.status(401).json({ message: 'Not authorized to access this route' });
}
if (!allowedRoles.includes(req.user.role)) {
return res.status(403).json({
message: `User role '${req.user.role}' is not authorized to access this route`,
});
}
next();
};
// Check if user is admin only
exports.admin = (req, res, next) => {
if (!req.user) {
return res.status(401).json({ message: 'Not authorized to access this route' });
}
if (req.user.role !== 'admin') {
return res.status(403).json({ message: 'Only admin users can access this route' });
}
next();
};