Chỉnh sửa giao diện quản lí của admin giai đoạn 1

This commit is contained in:
2026-06-09 12:47:24 +07:00
parent 0eaaf074ba
commit cdd5f30ae1
4 changed files with 138 additions and 22 deletions
+48 -12
View File
@@ -952,8 +952,38 @@ router.get('/admin/users', protect, async (req, res) => {
return res.status(403).json({ message: 'Bạn không có quyền truy cập quản trị' });
}
try {
const users = await User.find({}).sort({ createdAt: -1 });
res.json(users);
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const skip = (page - 1) * limit;
const totalUsers = await User.countDocuments();
// Sử dụng Aggregation để sắp xếp Role ưu tiên và Phân trang
const users = await User.aggregate([
{
$addFields: {
roleOrder: {
$switch: {
branches: [
{ case: { $eq: ["$role", "admin"] }, then: 0 },
{ case: { $eq: ["$role", "Chủ sở hữu"] }, then: 1 }
],
default: 2
}
}
}
},
{ $sort: { roleOrder: 1, createdAt: -1 } },
{ $skip: skip },
{ $limit: limit }
]);
res.json({
users,
totalPages: Math.ceil(totalUsers / limit),
currentPage: page,
totalUsers
});
} catch (error) {
res.status(500).json({ message: error.message });
}
@@ -970,14 +1000,20 @@ router.put('/admin/users/:id', protect, async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: 'Người dùng không tồn tại' });
// Cập nhật thông tin cơ bản
if (fullName) user.fullName = fullName;
if (email) user.email = email;
if (role) user.role = role;
// Nếu có nhập mật khẩu mới thì cập nhật (Middleware pre-save sẽ tự hash)
if (password && password.trim() !== '') {
user.password = password;
if (user.role === 'admin') {
// Theo yêu cầu: Admin tối cao chỉ được sửa Họ tên và Email
if (fullName) user.fullName = fullName;
if (email) user.email = email;
// Bỏ qua role và password để bảo vệ tài khoản root
} else {
// User bình thường được sửa tất cả
if (fullName) user.fullName = fullName;
if (email) user.email = email;
if (role) user.role = role;
if (password && password.trim() !== '') {
user.password = password;
}
}
await user.save();
@@ -997,8 +1033,8 @@ router.delete('/admin/users/:id', protect, async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: 'Người dùng không tồn tại' });
if (user.role === 'admin' && user._id.toString() === req.user._id.toString()) {
return res.status(400).json({ message: 'Bạn không thể tự xóa chính mình' });
if (user.role === 'admin') {
return res.status(400).json({ message: 'Không thể xóa tài khoản Admin tối cao' });
}
// Lưu ý: Trong thực tế bạn có thể muốn xóa cả các Scene của user này