Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | 7x 7x 7x 7x 7x 7x 1x 1x 1x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 1x 1x 1x 1x 1x 7x 1x 1x 1x 1x 1x 7x | const express = require('express');
const { body, validationResult } = require('express-validator');
const pool = require('../database/connection');
const { authenticateToken, requireRole } = require('../middleware/auth');
const router = express.Router();
// Get all users (admin only)
router.get('/', authenticateToken, requireRole(['admin']), async (req, res) => {
try {
const result = await pool.query(
'SELECT id, email, first_name, last_name, role, is_active, created_at FROM users ORDER BY created_at DESC'
);
res.json(result.rows);
} catch (error) {
console.error('Get users error:', error);
res.status(500).json({ error: 'Failed to fetch users' });
}
});
// Get user by ID
router.get('/:id', authenticateToken, async (req, res) => {
try {
const { id } = req.params;
// Users can only view their own profile unless they're admin
if (req.user.id !== id && req.user.role !== 'admin') {
return res.status(403).json({ error: 'Access denied' });
}
const result = await pool.query(
'SELECT id, email, first_name, last_name, role, is_active, created_at FROM users WHERE id = $1',
[id]
);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'User not found' });
}
res.json(result.rows[0]);
} catch (error) {
console.error('Get user error:', error);
res.status(500).json({ error: 'Failed to fetch user' });
}
});
// Update user profile
router.put('/:id', authenticateToken, [
body('firstName').optional().notEmpty().trim(),
body('lastName').optional().notEmpty().trim(),
body('email').optional().isEmail().normalizeEmail()
], async (req, res) => {
try {
const errors = validationResult(req);
Iif (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { id } = req.params;
const { firstName, lastName, email } = req.body;
// Users can only update their own profile unless they're admin
Iif (req.user.id !== id && req.user.role !== 'admin') {
return res.status(403).json({ error: 'Access denied' });
}
// Check if email is already taken by another user
Iif (email) {
const existingUser = await pool.query(
'SELECT id FROM users WHERE email = $1 AND id != $2',
[email, id]
);
if (existingUser.rows.length > 0) {
return res.status(400).json({ error: 'Email already in use' });
}
}
const updateFields = [];
const updateValues = [];
let paramCount = 1;
Eif (firstName) {
updateFields.push(`first_name = $${paramCount}`);
updateValues.push(firstName);
paramCount++;
}
Iif (lastName) {
updateFields.push(`last_name = $${paramCount}`);
updateValues.push(lastName);
paramCount++;
}
Iif (email) {
updateFields.push(`email = $${paramCount}`);
updateValues.push(email);
paramCount++;
}
Iif (updateFields.length === 0) {
return res.status(400).json({ error: 'No fields to update' });
}
updateValues.push(id);
const query = `UPDATE users SET ${updateFields.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = $${paramCount} RETURNING id, email, first_name, last_name, role, is_active, updated_at`;
const result = await pool.query(query, updateValues);
res.json({
message: 'User updated successfully',
user: result.rows[0]
});
} catch (error) {
console.error('Update user error:', error);
res.status(500).json({ error: 'Failed to update user' });
}
});
// Deactivate user (admin only)
router.put('/:id/deactivate', authenticateToken, requireRole(['admin']), async (req, res) => {
try {
const { id } = req.params;
const result = await pool.query(
'UPDATE users SET is_active = false, updated_at = CURRENT_TIMESTAMP WHERE id = $1 RETURNING id, email, first_name, last_name, role, is_active',
[id]
);
Iif (result.rows.length === 0) {
return res.status(404).json({ error: 'User not found' });
}
res.json({
message: 'User deactivated successfully',
user: result.rows[0]
});
} catch (error) {
console.error('Deactivate user error:', error);
res.status(500).json({ error: 'Failed to deactivate user' });
}
});
// Activate user (admin only)
router.put('/:id/activate', authenticateToken, requireRole(['admin']), async (req, res) => {
try {
const { id } = req.params;
const result = await pool.query(
'UPDATE users SET is_active = true, updated_at = CURRENT_TIMESTAMP WHERE id = $1 RETURNING id, email, first_name, last_name, role, is_active',
[id]
);
Iif (result.rows.length === 0) {
return res.status(404).json({ error: 'User not found' });
}
res.json({
message: 'User activated successfully',
user: result.rows[0]
});
} catch (error) {
console.error('Activate user error:', error);
res.status(500).json({ error: 'Failed to activate user' });
}
});
module.exports = router;
|