Cài đặt tính năng quản lí người dùng cho admin

This commit is contained in:
2026-06-13 18:24:14 +07:00
parent ea5799ffb5
commit 7b42058d77
21 changed files with 458 additions and 30 deletions
+57 -2
View File
@@ -1,8 +1,9 @@
import { NestFactory } from '@nestjs/core';
import { Module, Controller, Get, Post, Body, Param, ParseIntPipe, NotFoundException, BadRequestException, UnauthorizedException } from '@nestjs/common';
import { Module, Controller, Get, Post, Body, Param, Patch, Delete, ParseIntPipe, NotFoundException, BadRequestException, UnauthorizedException, UseGuards } from '@nestjs/common';
import { PrismaService } from './prisma.service.js';
import 'dotenv/config';
import * as bcrypt from 'bcrypt';
import { AdminGuard } from './admin.guard.js';
@Controller()
class AppController {
@@ -32,6 +33,11 @@ class AuthController {
throw new UnauthorizedException('Email hoặc mật khẩu không chính xác');
}
// Chặn người dùng đã bị khóa đăng nhập
if (user.isBlocked) {
throw new UnauthorizedException('Tài khoản của bạn đã bị khóa. Vui lòng liên hệ quản trị viên.');
}
return {
access_token: 'simulated-jwt-token',
user: {
@@ -108,8 +114,57 @@ class TourController {
}
}
@Controller('v1/users')
@UseGuards(AdminGuard)
class UserController {
constructor(private prisma: PrismaService) {}
@Get()
async getAllUsers() {
return this.prisma.user.findMany({
select: { id: true, email: true, name: true, isAdmin: true, isBlocked: true, createdAt: true }
});
}
@Patch(':id')
async updateUser(@Param('id', ParseIntPipe) id: number, @Body() data: any) {
// Nếu đổi mật khẩu thì cần hash
if (data.password) {
data.passwordHash = await bcrypt.hash(data.password, 10);
delete data.password;
}
return this.prisma.user.update({
where: { id },
data,
select: { id: true, email: true, name: true, isAdmin: true, isBlocked: true }
});
}
@Delete(':id')
async deleteUser(@Param('id', ParseIntPipe) id: number) {
// Không cho phép tự xóa chính mình hoặc xóa admin cuối cùng (logic đơn giản)
const user = await this.prisma.user.findUnique({ where: { id } });
if (user?.isAdmin) {
const adminCount = await this.prisma.user.count({ where: { isAdmin: true } });
if (adminCount <= 1) throw new BadRequestException('Không thể xóa Quản trị viên cuối cùng');
}
await this.prisma.user.delete({ where: { id } });
return { success: true };
}
@Post('block/:id')
async toggleBlock(@Param('id', ParseIntPipe) id: number) {
const user = await this.prisma.user.findUnique({ where: { id } });
if (!user) throw new NotFoundException('Người dùng không tồn tại');
return this.prisma.user.update({
where: { id },
data: { isBlocked: !user.isBlocked }
});
}
}
@Module({
controllers: [AppController, AuthController, TourController],
controllers: [AppController, AuthController, TourController, UserController],
providers: [PrismaService],
exports: [PrismaService]
})