2026-01-28 14:36:33 -07:00
|
|
|
// User Management Routes (Admin only)
|
|
|
|
|
const express = require('express');
|
|
|
|
|
const bcrypt = require('bcryptjs');
|
2026-05-06 11:44:17 -06:00
|
|
|
const pool = require('../db');
|
2026-05-05 11:04:53 -06:00
|
|
|
const { validateTeams } = require('../helpers/teams');
|
2026-01-28 14:36:33 -07:00
|
|
|
|
2026-05-06 11:44:17 -06:00
|
|
|
function createUsersRouter(requireAuth, requireGroup, logAudit) {
|
2026-01-28 14:36:33 -07:00
|
|
|
const router = express.Router();
|
|
|
|
|
|
2026-04-06 16:18:07 -06:00
|
|
|
// All routes require Admin group
|
2026-05-06 11:44:17 -06:00
|
|
|
router.use(requireAuth(), requireGroup('Admin'));
|
2026-01-28 14:36:33 -07:00
|
|
|
|
|
|
|
|
// Get all users
|
|
|
|
|
router.get('/', async (req, res) => {
|
|
|
|
|
try {
|
2026-05-06 11:44:17 -06:00
|
|
|
const { rows: users } = await pool.query(
|
|
|
|
|
`SELECT id, username, email, user_group AS "group", bu_teams, is_active, created_at, last_login
|
|
|
|
|
FROM users ORDER BY created_at DESC`
|
|
|
|
|
);
|
2026-05-05 11:04:53 -06:00
|
|
|
// Parse bu_teams into teams array for each user
|
|
|
|
|
const usersWithTeams = users.map(u => ({
|
|
|
|
|
...u,
|
|
|
|
|
teams: u.bu_teams ? u.bu_teams.split(',').filter(Boolean) : []
|
|
|
|
|
}));
|
|
|
|
|
res.json(usersWithTeams);
|
2026-01-28 14:36:33 -07:00
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Get users error:', err);
|
|
|
|
|
res.status(500).json({ error: 'Failed to fetch users' });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Get single user
|
|
|
|
|
router.get('/:id', async (req, res) => {
|
|
|
|
|
try {
|
2026-05-06 11:44:17 -06:00
|
|
|
const { rows } = await pool.query(
|
|
|
|
|
`SELECT id, username, email, user_group AS "group", bu_teams, is_active, created_at, last_login
|
|
|
|
|
FROM users WHERE id = $1`,
|
|
|
|
|
[req.params.id]
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const user = rows[0];
|
2026-01-28 14:36:33 -07:00
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
return res.status(404).json({ error: 'User not found' });
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-05 11:04:53 -06:00
|
|
|
res.json({
|
|
|
|
|
...user,
|
|
|
|
|
teams: user.bu_teams ? user.bu_teams.split(',').filter(Boolean) : []
|
|
|
|
|
});
|
2026-01-28 14:36:33 -07:00
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Get user error:', err);
|
|
|
|
|
res.status(500).json({ error: 'Failed to fetch user' });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Create new user
|
|
|
|
|
router.post('/', async (req, res) => {
|
2026-05-05 11:04:53 -06:00
|
|
|
const { username, email, password, group, bu_teams } = req.body;
|
2026-04-06 16:18:07 -06:00
|
|
|
const VALID_GROUPS = ['Admin', 'Standard_User', 'Leadership', 'Read_Only'];
|
2026-01-28 14:36:33 -07:00
|
|
|
|
|
|
|
|
if (!username || !email || !password) {
|
|
|
|
|
return res.status(400).json({ error: 'Username, email, and password are required' });
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-06 16:18:07 -06:00
|
|
|
const userGroup = group || 'Read_Only';
|
|
|
|
|
|
|
|
|
|
if (!VALID_GROUPS.includes(userGroup)) {
|
|
|
|
|
return res.status(400).json({ error: 'Invalid group. Must be one of: Admin, Standard_User, Leadership, Read_Only' });
|
2026-01-28 14:36:33 -07:00
|
|
|
}
|
|
|
|
|
|
2026-05-05 11:04:53 -06:00
|
|
|
// Validate bu_teams if provided
|
|
|
|
|
const teamsStr = bu_teams || '';
|
|
|
|
|
if (teamsStr) {
|
|
|
|
|
const teamsResult = validateTeams(teamsStr);
|
|
|
|
|
if (!teamsResult.valid) {
|
|
|
|
|
return res.status(400).json({ error: `Invalid team(s): ${teamsResult.invalid.join(', ')}. Must be one of: STEAM, ACCESS-ENG, ACCESS-OPS, INTELDEV` });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-28 14:36:33 -07:00
|
|
|
try {
|
|
|
|
|
const passwordHash = await bcrypt.hash(password, 10);
|
|
|
|
|
|
2026-05-06 11:44:17 -06:00
|
|
|
const { rows } = await pool.query(
|
|
|
|
|
`INSERT INTO users (username, email, password_hash, user_group, bu_teams)
|
|
|
|
|
VALUES ($1, $2, $3, $4, $5)
|
|
|
|
|
RETURNING id`,
|
|
|
|
|
[username, email, passwordHash, userGroup, teamsStr]
|
|
|
|
|
);
|
2026-01-28 14:36:33 -07:00
|
|
|
|
2026-05-06 11:44:17 -06:00
|
|
|
const result = rows[0];
|
|
|
|
|
|
|
|
|
|
logAudit({
|
2026-01-29 15:10:29 -07:00
|
|
|
userId: req.user.id,
|
|
|
|
|
username: req.user.username,
|
|
|
|
|
action: 'user_create',
|
|
|
|
|
entityType: 'user',
|
|
|
|
|
entityId: String(result.id),
|
2026-05-05 11:04:53 -06:00
|
|
|
details: { created_username: username, group: userGroup, bu_teams: teamsStr },
|
2026-01-29 15:10:29 -07:00
|
|
|
ipAddress: req.ip
|
|
|
|
|
});
|
|
|
|
|
|
2026-01-28 14:36:33 -07:00
|
|
|
res.status(201).json({
|
|
|
|
|
message: 'User created successfully',
|
|
|
|
|
user: {
|
|
|
|
|
id: result.id,
|
|
|
|
|
username,
|
|
|
|
|
email,
|
2026-05-05 11:04:53 -06:00
|
|
|
group: userGroup,
|
|
|
|
|
bu_teams: teamsStr,
|
|
|
|
|
teams: teamsStr ? teamsStr.split(',').filter(Boolean) : []
|
2026-01-28 14:36:33 -07:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Create user error:', err);
|
2026-05-06 11:44:17 -06:00
|
|
|
if (err.code === '23505') { // Postgres unique violation
|
2026-01-28 14:36:33 -07:00
|
|
|
return res.status(409).json({ error: 'Username or email already exists' });
|
|
|
|
|
}
|
|
|
|
|
res.status(500).json({ error: 'Failed to create user' });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Update user
|
|
|
|
|
router.patch('/:id', async (req, res) => {
|
2026-05-05 11:04:53 -06:00
|
|
|
const { username, email, password, group, is_active, bu_teams } = req.body;
|
2026-04-06 16:18:07 -06:00
|
|
|
const VALID_GROUPS = ['Admin', 'Standard_User', 'Leadership', 'Read_Only'];
|
2026-01-28 14:36:33 -07:00
|
|
|
const userId = req.params.id;
|
|
|
|
|
|
2026-04-06 16:18:07 -06:00
|
|
|
// Validate group if provided
|
|
|
|
|
if (group && !VALID_GROUPS.includes(group)) {
|
|
|
|
|
return res.status(400).json({ error: 'Invalid group. Must be one of: Admin, Standard_User, Leadership, Read_Only' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Prevent admin self-demotion
|
2026-04-07 10:23:10 -06:00
|
|
|
if (String(userId) === String(req.user.id) && group && group !== 'Admin') {
|
2026-04-06 16:18:07 -06:00
|
|
|
return res.status(400).json({ error: 'Cannot remove your own admin group' });
|
2026-01-28 14:36:33 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Prevent self-deactivation
|
2026-04-07 10:23:10 -06:00
|
|
|
if (String(userId) === String(req.user.id) && is_active === false) {
|
2026-01-28 14:36:33 -07:00
|
|
|
return res.status(400).json({ error: 'Cannot deactivate your own account' });
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-05 11:04:53 -06:00
|
|
|
// Validate bu_teams if provided
|
|
|
|
|
if (typeof bu_teams === 'string') {
|
|
|
|
|
if (bu_teams !== '') {
|
|
|
|
|
const teamsResult = validateTeams(bu_teams);
|
|
|
|
|
if (!teamsResult.valid) {
|
|
|
|
|
return res.status(400).json({ error: `Invalid team(s): ${teamsResult.invalid.join(', ')}. Must be one of: STEAM, ACCESS-ENG, ACCESS-OPS, INTELDEV` });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-28 14:36:33 -07:00
|
|
|
try {
|
2026-04-06 16:18:07 -06:00
|
|
|
// Fetch current user record before update (needed for group change audit)
|
2026-05-06 11:44:17 -06:00
|
|
|
const { rows: currentRows } = await pool.query(
|
|
|
|
|
'SELECT user_group, bu_teams FROM users WHERE id = $1',
|
|
|
|
|
[userId]
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const currentUser = currentRows[0];
|
2026-04-06 16:18:07 -06:00
|
|
|
|
|
|
|
|
if (!currentUser) {
|
|
|
|
|
return res.status(404).json({ error: 'User not found' });
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-28 14:36:33 -07:00
|
|
|
const updates = [];
|
|
|
|
|
const values = [];
|
2026-05-06 11:44:17 -06:00
|
|
|
let paramIndex = 1;
|
2026-01-28 14:36:33 -07:00
|
|
|
|
|
|
|
|
if (username) {
|
2026-05-06 11:44:17 -06:00
|
|
|
updates.push(`username = $${paramIndex++}`);
|
2026-01-28 14:36:33 -07:00
|
|
|
values.push(username);
|
|
|
|
|
}
|
|
|
|
|
if (email) {
|
2026-05-06 11:44:17 -06:00
|
|
|
updates.push(`email = $${paramIndex++}`);
|
2026-01-28 14:36:33 -07:00
|
|
|
values.push(email);
|
|
|
|
|
}
|
|
|
|
|
if (password) {
|
|
|
|
|
const passwordHash = await bcrypt.hash(password, 10);
|
2026-05-06 11:44:17 -06:00
|
|
|
updates.push(`password_hash = $${paramIndex++}`);
|
2026-01-28 14:36:33 -07:00
|
|
|
values.push(passwordHash);
|
|
|
|
|
}
|
2026-04-06 16:18:07 -06:00
|
|
|
if (group) {
|
2026-05-06 11:44:17 -06:00
|
|
|
updates.push(`user_group = $${paramIndex++}`);
|
2026-04-06 16:18:07 -06:00
|
|
|
values.push(group);
|
2026-01-28 14:36:33 -07:00
|
|
|
}
|
|
|
|
|
if (typeof is_active === 'boolean') {
|
2026-05-06 11:44:17 -06:00
|
|
|
updates.push(`is_active = $${paramIndex++}`);
|
|
|
|
|
values.push(is_active);
|
2026-01-28 14:36:33 -07:00
|
|
|
}
|
2026-05-05 11:04:53 -06:00
|
|
|
if (typeof bu_teams === 'string') {
|
2026-05-06 11:44:17 -06:00
|
|
|
updates.push(`bu_teams = $${paramIndex++}`);
|
2026-05-05 11:04:53 -06:00
|
|
|
values.push(bu_teams);
|
|
|
|
|
}
|
2026-01-28 14:36:33 -07:00
|
|
|
|
|
|
|
|
if (updates.length === 0) {
|
|
|
|
|
return res.status(400).json({ error: 'No fields to update' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
values.push(userId);
|
|
|
|
|
|
2026-05-06 11:44:17 -06:00
|
|
|
await pool.query(
|
|
|
|
|
`UPDATE users SET ${updates.join(', ')} WHERE id = $${paramIndex}`,
|
|
|
|
|
values
|
|
|
|
|
);
|
2026-01-28 14:36:33 -07:00
|
|
|
|
2026-01-29 15:10:29 -07:00
|
|
|
const updatedFields = {};
|
|
|
|
|
if (username) updatedFields.username = username;
|
|
|
|
|
if (email) updatedFields.email = email;
|
2026-04-06 16:18:07 -06:00
|
|
|
if (group) updatedFields.group = group;
|
2026-01-29 15:10:29 -07:00
|
|
|
if (typeof is_active === 'boolean') updatedFields.is_active = is_active;
|
|
|
|
|
if (password) updatedFields.password_changed = true;
|
2026-05-05 11:04:53 -06:00
|
|
|
if (typeof bu_teams === 'string') updatedFields.bu_teams = bu_teams;
|
2026-01-29 15:10:29 -07:00
|
|
|
|
2026-05-06 11:44:17 -06:00
|
|
|
logAudit({
|
2026-01-29 15:10:29 -07:00
|
|
|
userId: req.user.id,
|
|
|
|
|
username: req.user.username,
|
|
|
|
|
action: 'user_update',
|
|
|
|
|
entityType: 'user',
|
|
|
|
|
entityId: String(userId),
|
|
|
|
|
details: updatedFields,
|
|
|
|
|
ipAddress: req.ip
|
|
|
|
|
});
|
|
|
|
|
|
2026-04-06 16:18:07 -06:00
|
|
|
// Log specific audit entry for group changes
|
|
|
|
|
if (group && group !== currentUser.user_group) {
|
2026-05-06 11:44:17 -06:00
|
|
|
logAudit({
|
2026-04-06 16:18:07 -06:00
|
|
|
userId: req.user.id,
|
|
|
|
|
username: req.user.username,
|
|
|
|
|
action: 'user_group_change',
|
|
|
|
|
entityType: 'user',
|
|
|
|
|
entityId: String(userId),
|
|
|
|
|
details: {
|
|
|
|
|
previous_group: currentUser.user_group,
|
|
|
|
|
new_group: group
|
|
|
|
|
},
|
|
|
|
|
ipAddress: req.ip
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-05 11:04:53 -06:00
|
|
|
// Log specific audit entry for bu_teams changes
|
|
|
|
|
if (typeof bu_teams === 'string' && bu_teams !== (currentUser.bu_teams || '')) {
|
2026-05-06 11:44:17 -06:00
|
|
|
logAudit({
|
2026-05-05 11:04:53 -06:00
|
|
|
userId: req.user.id,
|
|
|
|
|
username: req.user.username,
|
|
|
|
|
action: 'user_teams_change',
|
|
|
|
|
entityType: 'user',
|
|
|
|
|
entityId: String(userId),
|
|
|
|
|
details: {
|
|
|
|
|
previous_teams: currentUser.bu_teams || '',
|
|
|
|
|
new_teams: bu_teams
|
|
|
|
|
},
|
|
|
|
|
ipAddress: req.ip
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-28 14:36:33 -07:00
|
|
|
// If user was deactivated, delete their sessions
|
|
|
|
|
if (is_active === false) {
|
2026-05-06 11:44:17 -06:00
|
|
|
await pool.query('DELETE FROM sessions WHERE user_id = $1', [userId]);
|
2026-01-28 14:36:33 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
res.json({ message: 'User updated successfully' });
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Update user error:', err);
|
2026-05-06 11:44:17 -06:00
|
|
|
if (err.code === '23505') { // Postgres unique violation
|
2026-01-28 14:36:33 -07:00
|
|
|
return res.status(409).json({ error: 'Username or email already exists' });
|
|
|
|
|
}
|
|
|
|
|
res.status(500).json({ error: 'Failed to update user' });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Delete user
|
|
|
|
|
router.delete('/:id', async (req, res) => {
|
|
|
|
|
const userId = req.params.id;
|
|
|
|
|
|
|
|
|
|
// Prevent self-deletion
|
2026-04-07 10:23:10 -06:00
|
|
|
if (String(userId) === String(req.user.id)) {
|
2026-01-28 14:36:33 -07:00
|
|
|
return res.status(400).json({ error: 'Cannot delete your own account' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
2026-01-29 15:10:29 -07:00
|
|
|
// Look up the user before deleting
|
2026-05-06 11:44:17 -06:00
|
|
|
const { rows: userRows } = await pool.query(
|
|
|
|
|
'SELECT username FROM users WHERE id = $1',
|
|
|
|
|
[userId]
|
|
|
|
|
);
|
|
|
|
|
const targetUser = userRows[0];
|
2026-01-29 15:10:29 -07:00
|
|
|
|
2026-01-28 14:36:33 -07:00
|
|
|
// Delete sessions first (foreign key)
|
2026-05-06 11:44:17 -06:00
|
|
|
await pool.query('DELETE FROM sessions WHERE user_id = $1', [userId]);
|
2026-01-28 14:36:33 -07:00
|
|
|
|
|
|
|
|
// Delete user
|
2026-05-06 11:44:17 -06:00
|
|
|
const result = await pool.query('DELETE FROM users WHERE id = $1', [userId]);
|
2026-01-28 14:36:33 -07:00
|
|
|
|
2026-05-06 11:44:17 -06:00
|
|
|
if (result.rowCount === 0) {
|
2026-01-28 14:36:33 -07:00
|
|
|
return res.status(404).json({ error: 'User not found' });
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-06 11:44:17 -06:00
|
|
|
logAudit({
|
2026-01-29 15:10:29 -07:00
|
|
|
userId: req.user.id,
|
|
|
|
|
username: req.user.username,
|
|
|
|
|
action: 'user_delete',
|
|
|
|
|
entityType: 'user',
|
|
|
|
|
entityId: String(userId),
|
|
|
|
|
details: { deleted_username: targetUser ? targetUser.username : 'unknown' },
|
|
|
|
|
ipAddress: req.ip
|
|
|
|
|
});
|
|
|
|
|
|
2026-01-28 14:36:33 -07:00
|
|
|
res.json({ message: 'User deleted successfully' });
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Delete user error:', err);
|
|
|
|
|
res.status(500).json({ error: 'Failed to delete user' });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return router;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
module.exports = createUsersRouter;
|