helpyourneighbour/backend/routes/roles.js

79 lines
2.3 KiB
JavaScript
Raw Normal View History

const express = require('express');
const router = express.Router();
const db = require('../db');
const requireRole = require('../middleware/requireRole');
// Get all users (admin only)
router.get('/', requireRole(['admin']), async (req, res) => {
try {
const users = await db.query('SELECT id, email, name, role FROM users ORDER BY created_at DESC');
res.json({ users: users.rows });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
}
});
// Suspend a user (admin only)
router.put('/suspend/:userId', requireRole(['admin']), async (req, res) => {
try {
const { userId } = req.params;
// Check if user exists
const existingUser = await db.query('SELECT id FROM users WHERE id = $1', [userId]);
if (existingUser.rows.length === 0) {
return res.status(404).json({ error: 'User not found' });
}
// Suspend user
await db.query('UPDATE users SET suspended = true WHERE id = $1', [userId]);
// Log audit event
const auditEvent = {
actorUserId: req.user.userId,
action: 'USER_SUSPEND',
targetType: 'user',
targetId: userId,
reason: req.body.reason || 'No reason provided',
timestamp: new Date()
};
res.json({ message: 'User suspended successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
}
});
// Unsuspend a user (admin only)
router.put('/unsuspend/:userId', requireRole(['admin']), async (req, res) => {
try {
const { userId } = req.params;
// Check if user exists
const existingUser = await db.query('SELECT id FROM users WHERE id = $1', [userId]);
if (existingUser.rows.length === 0) {
return res.status(404).json({ error: 'User not found' });
}
// Unsuspend user
await db.query('UPDATE users SET suspended = false WHERE id = $1', [userId]);
// Log audit event
const auditEvent = {
actorUserId: req.user.userId,
action: 'USER_UNSUSPEND',
targetType: 'user',
targetId: userId,
reason: req.body.reason || 'No reason provided',
timestamp: new Date()
};
res.json({ message: 'User unsuspended successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
}
});
module.exports = router;