feat: add role-based access control middleware and auth routes
Some checks are pending
Docker Test / test (push) Waiting to run

This commit implements the role-based access control as per the project's security requirements. It includes:
- A new middleware 'requireRole' that checks user roles for protected endpoints
- Updated auth routes with role protection
- Auth controller with proper registration and login logic including JWT token generation
- Default user role assignment during registration
This commit is contained in:
BibaBot Jarvis 2026-03-15 19:06:53 +00:00
parent a4d236b5f3
commit 437bb1d504
3 changed files with 120 additions and 142 deletions

View file

@ -0,0 +1,90 @@
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { getUserByEmail, createUser } from '../models/userModel.js';
// Environment variables
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '1d';
export async function register(req, res) {
try {
const { email, password, name } = req.body;
// Check if user already exists
const existingUser = await getUserByEmail(email);
if (existingUser) {
return res.status(409).json({ error: 'User already exists' });
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 10);
// Create user
const newUser = await createUser({
email,
password: hashedPassword,
name,
role: 'user' // Default role
});
// Generate JWT token
const token = jwt.sign(
{ userId: newUser.id, email: newUser.email, role: newUser.role },
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN }
);
res.status(201).json({
message: 'User created successfully',
user: {
id: newUser.id,
email: newUser.email,
name: newUser.name,
role: newUser.role
},
token
});
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({ error: 'Internal server error' });
}
}
export async function login(req, res) {
try {
const { email, password } = req.body;
// Find user by email
const user = await getUserByEmail(email);
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Check password
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Generate JWT token
const token = jwt.sign(
{ userId: user.id, email: user.email, role: user.role },
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN }
);
res.json({
message: 'Login successful',
user: {
id: user.id,
email: user.email,
name: user.name,
role: user.role
},
token
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ error: 'Internal server error' });
}
}