feat: 实现登录鉴权 RBAC 与用户管理模块

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-28 15:43:18 +08:00
co-authored by Cursor
parent 9629597b1d
commit 9368574cf7
18 changed files with 568 additions and 3 deletions
+10
View File
@@ -0,0 +1,10 @@
* text=auto eol=lf
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.webp binary
*.ico binary
*.woff binary
*.woff2 binary
*.ttf binary
+2 -1
View File
@@ -49,5 +49,6 @@
- 阶段 0(脚手架)已完成:pnpm monorepo(apps/* + packages/*)、根脚本、`.env`/`.env.example`、`docker/docker-compose.dev.yml`(MySQL 8 + Redis7-alpine,本地镜像)、`packages/shared`(枚举/错误码/响应类型/常量,含出库导入列定义)。MySQL/Redis 已起并连通,shared 已构建。
- 约定:shared 用 tsc 构建为 CommonJS 供 api/admin/h5 复用;env 驱动存储(local/oss)、区块链(mock/tianhe)、Geo(mock) 可切换。
- 阶段 1(后端基础设施)已完成:`apps/api` NestJS 工程;Prisma 全量建模并迁移(init),生成客户端;全局统一响应拦截器/异常过滤器/校验管道/BigInt 序列化;ConfigModule 读根 `.env`(dotenv-cli 供 Prisma CLI 用 `dotenv -e ../../.env`);静态目录 `/uploads`;Swagger 在 `/api/docs`。已验证启动、DB 连接、health/app-info 正常。
- 踩坑:pnpm 10 默认禁用原生构建脚本,已在根 `pnpm.onlyBuiltDependencies` 放行 prisma/sharp 等;Prisma migrate 需 shadow db 权限,开发库已对 `artveris` 用户授予全部权限;nanoid 固定 ^3(CJS)。
- 踩坑:pnpm 10 默认禁用原生构建脚本,已在根 `pnpm.onlyBuiltDependencies` 放行 prisma/sharp 等;Prisma migrate 需 shadow db 权限,开发库已对 `artveris` 用户授予全部权限;nanoid 固定 ^3(CJS);`tsconfig.json` 的 include 仅 `src`(含 prisma 会让 tsc 改变 rootDir 导致 dist/main.js 路径错位)。
- 阶段 2(鉴权与用户)已完成:JWT 登录(bcryptjs)、全局 JwtAuthGuard + RolesGuard(`@Public`/`@Roles` 元数据,SUPER_ADMIN 全通)、用户 CRUD(仅超管)、改密、`auth/profile`;种子超管 `admin/Admin@12345` 与系统默认设置。已用 PowerShell 验证登录/鉴权/RBAC/401。
+45
View File
@@ -0,0 +1,45 @@
import { PrismaClient, RoleType } from '@prisma/client';
import * as bcrypt from 'bcryptjs';
const prisma = new PrismaClient();
async function main(): Promise<void> {
const username = process.env.SEED_ADMIN_USERNAME || 'admin';
const password = process.env.SEED_ADMIN_PASSWORD || 'Admin@12345';
const realName = process.env.SEED_ADMIN_NAME || '超级管理员';
const existing = await prisma.sysUser.findUnique({ where: { username } });
if (existing) {
console.log(`超级管理员 ${username} 已存在,跳过。`);
} else {
const passwordHash = await bcrypt.hash(password, 10);
await prisma.sysUser.create({
data: { username, passwordHash, realName, role: RoleType.SUPER_ADMIN },
});
console.log(`已创建超级管理员:${username} / ${password}`);
}
// 默认系统设置
const defaults: Record<string, string> = {
appName: process.env.APP_NAME || '艺术品可信溯源与认证平台',
logRetentionDays: process.env.LOG_RETENTION_DAYS || '365',
watermarkText: process.env.WATERMARK_TEXT || '仅供溯源核验使用',
};
for (const [key, value] of Object.entries(defaults)) {
await prisma.systemSetting.upsert({
where: { key },
update: {},
create: { key, value },
});
}
console.log('系统默认设置已就绪。');
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(() => {
void prisma.$disconnect();
});
+4
View File
@@ -3,6 +3,8 @@ import { ConfigModule } from '@nestjs/config';
import configuration from './config/configuration';
import { PrismaModule } from './prisma/prisma.module';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
import { UserModule } from './user/user.module';
@Module({
imports: [
@@ -12,6 +14,8 @@ import { AppController } from './app.controller';
envFilePath: ['../../.env', '.env'],
}),
PrismaModule,
AuthModule,
UserModule,
],
controllers: [AppController],
})
+34
View File
@@ -0,0 +1,34 @@
import { Body, Controller, Get, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { Public } from '../common/decorators/public.decorator';
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
@ApiTags('认证')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Public()
@Post('login')
@ApiOperation({ summary: '登录' })
login(@Body() dto: LoginDto) {
return this.authService.login(dto);
}
@ApiBearerAuth()
@Get('profile')
@ApiOperation({ summary: '获取当前登录用户信息' })
profile(@CurrentUser() user: AuthUser) {
return this.authService.profile(user.id);
}
@ApiBearerAuth()
@Post('change-password')
@ApiOperation({ summary: '修改密码' })
changePassword(@CurrentUser() user: AuthUser, @Body() dto: ChangePasswordDto) {
return this.authService.changePassword(user.id, dto.oldPassword, dto.newPassword);
}
}
+29
View File
@@ -0,0 +1,29 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { APP_GUARD } from '@nestjs/core';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { RolesGuard } from './guards/roles.guard';
@Module({
imports: [
JwtModule.registerAsync({
global: true,
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: config.get<string>('jwt.secret'),
signOptions: { expiresIn: config.get<string>('jwt.expiresIn') || '7d' },
}),
}),
],
controllers: [AuthController],
providers: [
AuthService,
{ provide: APP_GUARD, useClass: JwtAuthGuard },
{ provide: APP_GUARD, useClass: RolesGuard },
],
exports: [AuthService],
})
export class AuthModule {}
+76
View File
@@ -0,0 +1,76 @@
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcryptjs';
import { ErrorCode, UserStatus } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { LoginDto } from './dto/login.dto';
@Injectable()
export class AuthService {
constructor(
private readonly prisma: PrismaService,
private readonly jwt: JwtService,
) {}
async login(dto: LoginDto) {
const user = await this.prisma.sysUser.findUnique({ where: { username: dto.username } });
if (!user) {
throw new BusinessException(ErrorCode.INVALID_CREDENTIALS, '用户名或密码错误', 401);
}
if (user.status === UserStatus.DISABLED) {
throw new BusinessException(ErrorCode.USER_DISABLED, '账号已被停用', 403);
}
const ok = await bcrypt.compare(dto.password, user.passwordHash);
if (!ok) {
throw new BusinessException(ErrorCode.INVALID_CREDENTIALS, '用户名或密码错误', 401);
}
await this.prisma.sysUser.update({
where: { id: user.id },
data: { lastLoginAt: new Date() },
});
const token = await this.jwt.signAsync({
sub: user.id,
username: user.username,
role: user.role,
realName: user.realName ?? undefined,
});
return {
token,
user: {
id: user.id,
username: user.username,
realName: user.realName,
role: user.role,
},
};
}
async profile(userId: number) {
const user = await this.prisma.sysUser.findUnique({
where: { id: userId },
select: { id: true, username: true, realName: true, role: true, status: true, lastLoginAt: true },
});
if (!user) {
throw new BusinessException(ErrorCode.NOT_FOUND, '用户不存在', 404);
}
return user;
}
async changePassword(userId: number, oldPassword: string, newPassword: string) {
const user = await this.prisma.sysUser.findUnique({ where: { id: userId } });
if (!user) {
throw new BusinessException(ErrorCode.NOT_FOUND, '用户不存在', 404);
}
const ok = await bcrypt.compare(oldPassword, user.passwordHash);
if (!ok) {
throw new BusinessException(ErrorCode.OLD_PASSWORD_WRONG, '原密码不正确');
}
const passwordHash = await bcrypt.hash(newPassword, 10);
await this.prisma.sysUser.update({ where: { id: userId }, data: { passwordHash } });
return { success: true };
}
}
@@ -0,0 +1,16 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString, MaxLength, MinLength } from 'class-validator';
export class ChangePasswordDto {
@ApiProperty({ description: '原密码' })
@IsString()
@IsNotEmpty()
oldPassword!: string;
@ApiProperty({ description: '新密码', minLength: 6 })
@IsString()
@IsNotEmpty()
@MinLength(6)
@MaxLength(64)
newPassword!: string;
}
+17
View File
@@ -0,0 +1,17 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString, MaxLength, MinLength } from 'class-validator';
export class LoginDto {
@ApiProperty({ description: '用户名', example: 'admin' })
@IsString()
@IsNotEmpty()
@MaxLength(50)
username!: string;
@ApiProperty({ description: '密码', example: 'Admin@12345' })
@IsString()
@IsNotEmpty()
@MinLength(6)
@MaxLength(64)
password!: string;
}
@@ -0,0 +1,56 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
import { ErrorCode } from '@artveris/shared';
import { IS_PUBLIC_KEY } from '../../common/decorators/public.decorator';
import { BusinessException } from '../../common/exceptions/business.exception';
import { AuthUser } from '../../common/decorators/current-user.decorator';
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
private readonly jwt: JwtService,
private readonly reflector: Reflector,
private readonly config: ConfigService,
) {}
canActivate(context: ExecutionContext): boolean {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return true;
}
const req = context.switchToHttp().getRequest<Request>();
const token = this.extractToken(req);
if (!token) {
throw new BusinessException(ErrorCode.UNAUTHORIZED, '未登录或登录已过期', 401);
}
try {
const payload = this.jwt.verify<AuthUser & { sub: number }>(token, {
secret: this.config.get<string>('jwt.secret'),
});
(req as Request & { user: AuthUser }).user = {
id: payload.sub ?? payload.id,
username: payload.username,
role: payload.role,
realName: payload.realName,
};
return true;
} catch {
throw new BusinessException(ErrorCode.TOKEN_EXPIRED, '登录已过期,请重新登录', 401);
}
}
private extractToken(req: Request): string | null {
const auth = req.headers.authorization;
if (auth && auth.startsWith('Bearer ')) {
return auth.slice(7);
}
return null;
}
}
+44
View File
@@ -0,0 +1,44 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { ErrorCode, RoleType } from '@artveris/shared';
import { ROLES_KEY } from '../../common/decorators/roles.decorator';
import { IS_PUBLIC_KEY } from '../../common/decorators/public.decorator';
import { BusinessException } from '../../common/exceptions/business.exception';
import { AuthUser } from '../../common/decorators/current-user.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return true;
}
const requiredRoles = this.reflector.getAllAndOverride<RoleType[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
const req = context.switchToHttp().getRequest<Request & { user?: AuthUser }>();
const user = req.user;
if (!user) {
throw new BusinessException(ErrorCode.UNAUTHORIZED, '未登录', 401);
}
if (user.role === RoleType.SUPER_ADMIN) {
return true;
}
if (!requiredRoles.includes(user.role as RoleType)) {
throw new BusinessException(ErrorCode.FORBIDDEN, '没有操作权限', 403);
}
return true;
}
}
+27
View File
@@ -0,0 +1,27 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsEnum, IsNotEmpty, IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
import { RoleType } from '@artveris/shared';
export class CreateUserDto {
@ApiProperty({ description: '用户名' })
@IsString()
@IsNotEmpty()
@MaxLength(50)
username!: string;
@ApiProperty({ description: '密码', minLength: 6 })
@IsString()
@MinLength(6)
@MaxLength(64)
password!: string;
@ApiProperty({ description: '姓名', required: false })
@IsOptional()
@IsString()
@MaxLength(50)
realName?: string;
@ApiProperty({ description: '角色', enum: RoleType })
@IsEnum(RoleType)
role!: RoleType;
}
+21
View File
@@ -0,0 +1,21 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsOptional, IsString } from 'class-validator';
import { RoleType, UserStatus } from '@artveris/shared';
import { PaginationDto } from '../../common/dto/pagination.dto';
export class QueryUserDto extends PaginationDto {
@ApiPropertyOptional({ description: '关键词(用户名/姓名)' })
@IsOptional()
@IsString()
keyword?: string;
@ApiPropertyOptional({ description: '角色', enum: RoleType })
@IsOptional()
@IsEnum(RoleType)
role?: RoleType;
@ApiPropertyOptional({ description: '状态', enum: UserStatus })
@IsOptional()
@IsEnum(UserStatus)
status?: UserStatus;
}
+29
View File
@@ -0,0 +1,29 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsEnum, IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
import { RoleType, UserStatus } from '@artveris/shared';
export class UpdateUserDto {
@ApiPropertyOptional({ description: '姓名' })
@IsOptional()
@IsString()
@MaxLength(50)
realName?: string;
@ApiPropertyOptional({ description: '角色', enum: RoleType })
@IsOptional()
@IsEnum(RoleType)
role?: RoleType;
@ApiPropertyOptional({ description: '状态', enum: UserStatus })
@IsOptional()
@IsEnum(UserStatus)
status?: UserStatus;
}
export class ResetPasswordDto {
@ApiPropertyOptional({ description: '新密码', minLength: 6 })
@IsString()
@MinLength(6)
@MaxLength(64)
newPassword!: string;
}
+47
View File
@@ -0,0 +1,47 @@
import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { RoleType } from '@artveris/shared';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto, ResetPasswordDto } from './dto/update-user.dto';
import { QueryUserDto } from './dto/query-user.dto';
import { Roles } from '../common/decorators/roles.decorator';
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
@ApiTags('用户管理')
@ApiBearerAuth()
@Roles(RoleType.SUPER_ADMIN)
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get()
@ApiOperation({ summary: '用户列表' })
list(@Query() query: QueryUserDto) {
return this.userService.list(query);
}
@Post()
@ApiOperation({ summary: '创建用户' })
create(@Body() dto: CreateUserDto) {
return this.userService.create(dto);
}
@Put(':id')
@ApiOperation({ summary: '更新用户' })
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateUserDto) {
return this.userService.update(id, dto);
}
@Put(':id/password')
@ApiOperation({ summary: '重置用户密码' })
resetPassword(@Param('id', ParseIntPipe) id: number, @Body() dto: ResetPasswordDto) {
return this.userService.resetPassword(id, dto.newPassword);
}
@Delete(':id')
@ApiOperation({ summary: '删除用户' })
remove(@Param('id', ParseIntPipe) id: number, @CurrentUser() user: AuthUser) {
return this.userService.remove(id, user.id);
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
@Module({
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}
+99
View File
@@ -0,0 +1,99 @@
import { Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import * as bcrypt from 'bcryptjs';
import { ErrorCode } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { buildPage } from '../common/utils/pagination.util';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { QueryUserDto } from './dto/query-user.dto';
const userSelect = {
id: true,
username: true,
realName: true,
role: true,
status: true,
lastLoginAt: true,
createdAt: true,
};
@Injectable()
export class UserService {
constructor(private readonly prisma: PrismaService) {}
async list(query: QueryUserDto) {
const where: Prisma.SysUserWhereInput = {};
if (query.keyword) {
where.OR = [
{ username: { contains: query.keyword } },
{ realName: { contains: query.keyword } },
];
}
if (query.role) where.role = query.role;
if (query.status) where.status = query.status;
const [list, total] = await this.prisma.$transaction([
this.prisma.sysUser.findMany({
where,
select: userSelect,
orderBy: { id: 'desc' },
skip: query.skip,
take: query.take,
}),
this.prisma.sysUser.count({ where }),
]);
return buildPage(list, total, query.page, query.pageSize);
}
async create(dto: CreateUserDto) {
const exists = await this.prisma.sysUser.findUnique({ where: { username: dto.username } });
if (exists) {
throw new BusinessException(ErrorCode.USERNAME_EXISTS, '用户名已存在');
}
const passwordHash = await bcrypt.hash(dto.password, 10);
return this.prisma.sysUser.create({
data: {
username: dto.username,
passwordHash,
realName: dto.realName,
role: dto.role,
},
select: userSelect,
});
}
async update(id: number, dto: UpdateUserDto) {
await this.ensureExists(id);
return this.prisma.sysUser.update({
where: { id },
data: { realName: dto.realName, role: dto.role, status: dto.status },
select: userSelect,
});
}
async resetPassword(id: number, newPassword: string) {
await this.ensureExists(id);
const passwordHash = await bcrypt.hash(newPassword, 10);
await this.prisma.sysUser.update({ where: { id }, data: { passwordHash } });
return { success: true };
}
async remove(id: number, currentUserId: number) {
if (id === currentUserId) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '不能删除当前登录账号');
}
await this.ensureExists(id);
await this.prisma.sysUser.delete({ where: { id } });
return { success: true };
}
private async ensureExists(id: number) {
const user = await this.prisma.sysUser.findUnique({ where: { id } });
if (!user) {
throw new BusinessException(ErrorCode.NOT_FOUND, '用户不存在', 404);
}
return user;
}
}
+2 -2
View File
@@ -20,6 +20,6 @@
"esModuleInterop": true,
"resolveJsonModule": true
},
"include": ["src", "prisma"],
"exclude": ["node_modules", "dist"]
"include": ["src"],
"exclude": ["node_modules", "dist", "prisma/seed.ts", "**/*.spec.ts"]
}