feat: 开发user、auth相关接口,初始化后台管理项目admin

This commit is contained in:
R524809
2025-11-19 17:42:53 +08:00
parent 7acadf191f
commit d195495449
45 changed files with 3016 additions and 101 deletions

View File

@@ -7,3 +7,6 @@ DB_USER=
DB_PASSWORD=
DB_DATABASE=vest_mind_test
# DB_DATABASE_TEST=vest_mind_test
JWT_SECRET=vest_thinking_key
JWT_EXPIRES_IN=7d

View File

@@ -24,16 +24,22 @@
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
"@nestjs/jwt": "^11.0.1",
"@nestjs/mapped-types": "^2.1.0",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/swagger": "^11.2.2",
"@nestjs/typeorm": "^11.0.0",
"@types/jsonwebtoken": "^9.0.10",
"bcrypt": "^6.0.0",
"body-parser": "^2.2.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.2",
"compression": "^1.8.1",
"express-rate-limit": "^8.2.1",
"helmet": "^8.1.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"pg": "^8.16.3",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
@@ -45,11 +51,13 @@
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/bcrypt": "^6.0.0",
"@types/body-parser": "^1.19.6",
"@types/compression": "^1.8.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^22.10.7",
"@types/passport-jwt": "^4.0.1",
"@types/pg": "^8.15.6",
"@types/supertest": "^6.0.2",
"eslint": "^9.18.0",

View File

@@ -1,22 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@@ -1,12 +0,0 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

View File

@@ -3,8 +3,8 @@ import { ConfigModule } from '@nestjs/config';
import { DatabaseModule } from './database/database.module';
import { CoreModule } from './core/core.module';
import { BrokerModule } from './modules/broker/broker.module';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './modules/user/user.module';
import { AuthModule } from './modules/auth/auth.module';
@Module({
imports: [
@@ -18,8 +18,10 @@ import { AppService } from './app.service';
CoreModule,
DatabaseModule,
BrokerModule,
UserModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
controllers: [],
providers: [],
})
export class AppModule {}

View File

@@ -1,8 +0,0 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@@ -0,0 +1,66 @@
import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { LoginResponse } from './interfaces/login-response.interface';
@ApiTags('auth')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
/**
* 用户登录
*/
@Post('login')
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: '用户登录',
description: '使用用户名/邮箱和密码登录,返回 access_token 和用户信息',
})
@ApiResponse({
status: 200,
description: '登录成功',
schema: {
type: 'object',
properties: {
code: { type: 'number', example: 0 },
message: { type: 'string', example: 'success' },
data: {
type: 'object',
properties: {
accessToken: {
type: 'string',
example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
},
user: {
type: 'object',
properties: {
userId: { type: 'number', example: 1 },
username: {
type: 'string',
example: 'john_doe',
},
email: {
type: 'string',
example: 'user@example.com',
},
nickname: {
type: 'string',
example: 'John Doe',
},
role: { type: 'string', example: 'user' },
},
},
},
},
timestamp: { type: 'string' },
},
},
})
@ApiResponse({ status: 401, description: '用户名或密码错误' })
@ApiResponse({ status: 400, description: '请求参数错误' })
async login(@Body() loginDto: LoginDto): Promise<LoginResponse> {
return this.authService.login(loginDto);
}
}

View File

@@ -0,0 +1,41 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './strategies/jwt.strategy';
import { User } from '../user/user.entity';
@Module({
imports: [
TypeOrmModule.forFeature([User]),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [ConfigModule],
// @ts-expect-error - JWT expiresIn accepts string but type definition is strict
useFactory: (configService: ConfigService) => {
const expiresIn = configService.get<string>(
'JWT_EXPIRES_IN',
'7d',
);
const secret = configService.get<string>(
'JWT_SECRET',
'your-secret-key-change-in-production',
);
return {
secret: secret,
signOptions: {
expiresIn: expiresIn || '7d', // 默认7天过期
},
};
},
inject: [ConfigService],
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [AuthService, JwtModule],
})
export class AuthModule {}

View File

@@ -0,0 +1,73 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { User } from '../user/user.entity';
import { LoginDto } from './dto/login.dto';
import { JwtPayload } from './interfaces/jwt-payload.interface';
import { LoginResponse } from './interfaces/login-response.interface';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
private readonly jwtService: JwtService,
) {}
/**
* 用户登录
*/
async login(loginDto: LoginDto): Promise<LoginResponse> {
// 根据用户名或邮箱查找用户
const user = await this.userRepository.findOne({
where: [
{ username: loginDto.usernameOrEmail },
{ email: loginDto.usernameOrEmail },
],
});
if (!user) {
throw new UnauthorizedException('用户名或密码错误');
}
// 检查用户状态
if (user.status !== 'active') {
throw new UnauthorizedException('用户已被禁用');
}
// 验证密码
const isPasswordValid = await bcrypt.compare(
loginDto.password,
user.passwordHash,
);
if (!isPasswordValid) {
throw new UnauthorizedException('用户名或密码错误');
}
// 更新最后登录时间
user.lastLoginAt = new Date();
await this.userRepository.save(user);
// 生成 JWT token
const payload: JwtPayload = {
sub: user.userId,
username: user.username,
email: user.email,
role: user.role,
};
const accessToken = this.jwtService.sign(payload);
// 返回 token 和用户信息(排除密码)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { passwordHash, ...userWithoutPassword } = user;
return {
accessToken,
user: userWithoutPassword,
};
}
}

View File

@@ -0,0 +1,37 @@
import { SetMetadata } from '@nestjs/common';
/**
* 角色权限装饰器
*
* 这个装饰器用于在控制器或方法上标记需要的角色权限。
* 配合 RolesGuard 使用实现基于角色的访问控制RBAC
*
* 使用示例:
* @Roles('admin', 'super_admin')
* @Get()
* findAll() { ... }
*
* 工作原理:
* 1. SetMetadata 会在目标方法或类上设置元数据
* 2. ROLES_KEY 作为元数据的键,存储角色数组
* 3. RolesGuard 通过 Reflector 读取这些元数据来验证用户权限
*/
/**
* 元数据键名
* 用于在 Reflector 中存储和读取角色信息
*/
export const ROLES_KEY = 'roles';
/**
* 角色权限装饰器工厂函数
*
* @param roles - 允许访问的角色列表(可变参数)
* @returns 返回一个装饰器函数,用于设置元数据
*
* 示例:
* - @Roles('admin') - 只允许 admin 角色访问
* - @Roles('admin', 'super_admin') - 允许 admin 或 super_admin 角色访问
* - @Roles() - 不传参数时RolesGuard 会允许所有已认证用户访问
*/
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);

View File

@@ -0,0 +1,22 @@
import { IsString, IsNotEmpty, MinLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class LoginDto {
@ApiProperty({
description: '用户名或邮箱',
example: 'john_doe',
})
@IsString()
@IsNotEmpty()
@MinLength(3)
usernameOrEmail: string;
@ApiProperty({
description: '密码',
example: 'password123',
})
@IsString()
@IsNotEmpty()
@MinLength(6)
password: string;
}

View File

@@ -0,0 +1,24 @@
import {
Injectable,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
handleRequest<TUser = unknown>(
err: Error | null,
user: TUser | false,
info: Error | string | undefined,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_context: ExecutionContext,
): TUser {
// 如果认证失败user 为 false 或 undefined或者有错误
if (err || !user || info) {
throw new UnauthorizedException('身份验证失败');
}
return user;
}
}

View File

@@ -0,0 +1,44 @@
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from '../decorators/roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles) {
// 如果没有设置角色要求,允许访问
return true;
}
const request = context.switchToHttp().getRequest<{
user?: { role: string };
}>();
const user = request.user;
if (!user) {
throw new ForbiddenException('未授权访问');
}
const hasRole = requiredRoles.some((role) => user.role === role);
if (!hasRole) {
throw new ForbiddenException(
`需要以下角色之一:${requiredRoles.join('、')}`,
);
}
return true;
}
}

View File

@@ -0,0 +1,6 @@
export interface JwtPayload {
sub: number; // 用户ID
username: string;
email: string;
role: string;
}

View File

@@ -0,0 +1,6 @@
import { User } from '../../user/user.entity';
export interface LoginResponse {
accessToken: string;
user: Omit<User, 'passwordHash'>; // 排除密码哈希
}

View File

@@ -0,0 +1,38 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../user/user.entity';
import { JwtPayload } from '../interfaces/jwt-payload.interface';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly configService: ConfigService,
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>(
'JWT_SECRET',
'your-secret-key',
),
});
}
async validate(payload: JwtPayload): Promise<User> {
const user = await this.userRepository.findOne({
where: { userId: payload.sub },
});
if (!user || user.status !== 'active') {
throw new UnauthorizedException('用户不存在或已被禁用');
}
return user;
}
}

View File

@@ -32,7 +32,7 @@ export class BrokerService {
if (existingByCode) {
throw new ConflictException(
`Broker with code "${createBrokerDto.brokerCode}" already exists in region "${createBrokerDto.region}"`,
`地区 "${createBrokerDto.region}" 中已存在代码为 "${createBrokerDto.brokerCode}" 的券商`,
);
}
@@ -46,7 +46,7 @@ export class BrokerService {
if (existingByName) {
throw new ConflictException(
`Broker with name "${createBrokerDto.brokerName}" already exists in region "${createBrokerDto.region}"`,
`地区 "${createBrokerDto.region}" 中已存在名称为 "${createBrokerDto.brokerName}" 的券商`,
);
}
@@ -88,10 +88,10 @@ export class BrokerService {
if (existingBrokers.length > 0) {
const conflicts = existingBrokers.map(
(b) => `${b.brokerCode} in ${b.region}`,
(b) => `${b.brokerCode} (${b.region})`,
);
throw new ConflictException(
`The following brokers already exist: ${conflicts.join(', ')}`,
`以下券商已存在:${conflicts.join('')}`,
);
}
@@ -101,7 +101,7 @@ export class BrokerService {
);
if (uniquePairs.size !== codeRegionPairs.length) {
throw new ConflictException(
'Duplicate broker_code and region combinations in batch data',
'批量数据中存在重复的券商代码和地区组合',
);
}
@@ -152,7 +152,7 @@ export class BrokerService {
});
if (!broker) {
throw new NotFoundException(`Broker with ID ${id} not found`);
throw new NotFoundException(`未找到ID ${id} 的券商`);
}
return broker;
@@ -187,9 +187,7 @@ export class BrokerService {
const broker = await this.brokerRepository.findOne({ where });
if (!broker) {
throw new NotFoundException(
'Broker not found with the given conditions',
);
throw new NotFoundException('未找到符合给定条件的券商');
}
return broker;
@@ -218,7 +216,7 @@ export class BrokerService {
if (existing && existing.brokerId !== id) {
throw new ConflictException(
`Broker with code "${newCode}" already exists in region "${newRegion}"`,
`地区 "${newRegion}" 中已存在代码为 "${newCode}" 的券商`,
);
}
}
@@ -237,7 +235,7 @@ export class BrokerService {
if (existing && existing.brokerId !== id) {
throw new ConflictException(
`Broker with name "${newName}" already exists in region "${newRegion}"`,
`地区 "${newRegion}" 中已存在名称为 "${newName}" 的券商`,
);
}
}

View File

@@ -0,0 +1,23 @@
import { IsString, IsNotEmpty, MinLength, MaxLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class ChangePasswordDto {
@ApiProperty({
description: '旧密码',
example: 'OldPassword123!',
})
@IsString()
@IsNotEmpty()
oldPassword: string;
@ApiProperty({
description: '新密码',
example: 'NewPassword123!',
minLength: 6,
})
@IsString()
@IsNotEmpty()
@MinLength(6)
@MaxLength(100)
newPassword: string;
}

View File

@@ -0,0 +1,109 @@
import {
IsString,
IsNotEmpty,
IsOptional,
IsEmail,
MinLength,
MaxLength,
Matches,
IsIn,
} from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({
description: '用户名',
example: 'john_doe',
maxLength: 100,
})
@IsString()
@IsNotEmpty()
@MinLength(3)
@MaxLength(100)
username: string;
@ApiProperty({
description: '密码(明文,服务端会使用 bcrypt 加密后存储)',
example: 'SecurePassword123!',
minLength: 6,
})
@IsString()
@IsNotEmpty()
@MinLength(6)
@MaxLength(100)
password: string;
@ApiProperty({
description: '邮箱',
example: 'user@example.com',
maxLength: 100,
})
@IsEmail()
@IsNotEmpty()
@MaxLength(100)
email: string;
@ApiPropertyOptional({
description: '用户昵称',
example: 'John Doe',
maxLength: 100,
})
@IsOptional()
@IsString()
@MaxLength(100)
nickname?: string;
@ApiPropertyOptional({
description: '头像URL',
example: 'https://example.com/avatar.jpg',
maxLength: 255,
})
@IsOptional()
@IsString()
@MaxLength(255)
avatarUrl?: string;
@ApiPropertyOptional({
description: '电话号码',
example: '13800138000',
maxLength: 20,
})
@IsOptional()
@IsString()
@Matches(/^[0-9+\-() ]+$/, {
message: '电话号码格式不正确',
})
@MaxLength(20)
phone?: string;
@ApiPropertyOptional({
description: '微信 openId',
example: 'openid123456',
maxLength: 100,
})
@IsOptional()
@IsString()
@MaxLength(100)
openId?: string;
@ApiPropertyOptional({
description: '微信 unionId',
example: 'unionid123456',
maxLength: 100,
})
@IsOptional()
@IsString()
@MaxLength(100)
unionId?: string;
@ApiPropertyOptional({
description: '用户角色',
example: 'user',
enum: ['user', 'admin', 'super_admin'],
default: 'user',
})
@IsOptional()
@IsString()
@IsIn(['user', 'admin', 'super_admin'])
role?: string;
}

View File

@@ -0,0 +1,20 @@
import { IsOptional, IsString, IsEmail } from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger';
export class QueryUserDto {
@ApiPropertyOptional({
description: '用户名',
example: 'john_doe',
})
@IsOptional()
@IsString()
username?: string;
@ApiPropertyOptional({
description: '邮箱',
example: 'user@example.com',
})
@IsOptional()
@IsEmail()
email?: string;
}

View File

@@ -0,0 +1,73 @@
import {
IsString,
IsOptional,
IsEmail,
MaxLength,
Matches,
IsIn,
} from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger';
export class UpdateUserDto {
@ApiPropertyOptional({
description: '邮箱',
example: 'newemail@example.com',
maxLength: 100,
})
@IsOptional()
@IsEmail()
@MaxLength(100)
email?: string;
@ApiPropertyOptional({
description: '电话号码',
example: '13800138000',
maxLength: 20,
})
@IsOptional()
@IsString()
@Matches(/^[0-9+\-() ]+$/, {
message: '电话号码格式不正确',
})
@MaxLength(20)
phone?: string;
@ApiPropertyOptional({
description: '用户昵称',
example: 'John Doe',
maxLength: 100,
})
@IsOptional()
@IsString()
@MaxLength(100)
nickname?: string;
@ApiPropertyOptional({
description: '头像URL',
example: 'https://example.com/avatar.jpg',
maxLength: 255,
})
@IsOptional()
@IsString()
@MaxLength(255)
avatarUrl?: string;
@ApiPropertyOptional({
description: '用户状态',
example: 'active',
enum: ['active', 'inactive', 'deleted'],
})
@IsOptional()
@IsString()
status?: string;
@ApiPropertyOptional({
description: '用户角色',
example: 'user',
enum: ['user', 'admin', 'super_admin'],
})
@IsOptional()
@IsString()
@IsIn(['user', 'admin', 'super_admin'])
role?: string;
}

View File

@@ -0,0 +1,180 @@
import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
Query,
HttpCode,
HttpStatus,
UseGuards,
} from '@nestjs/common';
import {
ApiTags,
ApiOperation,
ApiResponse,
ApiParam,
ApiBearerAuth,
} from '@nestjs/swagger';
import { UserService } from './user.service';
import { User } from './user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { QueryUserDto } from './dto/query-user.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator';
@ApiTags('user')
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
/**
* 注册用户
*/
@Post('register')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({
summary: '注册用户',
description: '创建新用户username、password、email 为必填项',
})
@ApiResponse({
status: 201,
description: '注册成功',
type: User,
})
@ApiResponse({ status: 400, description: '请求参数错误' })
@ApiResponse({
status: 409,
description: '用户名、邮箱或其他唯一字段已存在',
})
create(@Body() createUserDto: CreateUserDto): Promise<User> {
return this.userService.create(createUserDto);
}
/**
* 查询所有用户
*/
@Get()
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin', 'super_admin')
@ApiBearerAuth()
@ApiOperation({
summary: '查询所有用户',
description: '获取所有用户列表(需要管理员权限)',
})
@ApiResponse({
status: 200,
description: '查询成功',
type: [User],
})
@ApiResponse({ status: 401, description: '未授权' })
@ApiResponse({ status: 403, description: '权限不足' })
findAll(): Promise<User[]> {
return this.userService.findAll();
}
/**
* 根据 username 或 email 查询单个用户
*/
@Get('find')
@ApiOperation({
summary: '查询单个用户',
description: '根据 username 或 email 查询用户',
})
@ApiResponse({
status: 200,
description: '查询成功',
type: User,
})
@ApiResponse({
status: 400,
description: '请求参数错误,必须提供 username 或 email',
})
@ApiResponse({ status: 404, description: '用户不存在' })
findOne(@Query() queryDto: QueryUserDto): Promise<User> {
return this.userService.findOne(queryDto);
}
/**
* 根据 ID 查询单个用户
*/
@Get(':id')
@ApiOperation({
summary: '根据ID查询用户',
description: '根据用户ID获取详细信息',
})
@ApiParam({ name: 'id', description: '用户ID', type: Number })
@ApiResponse({
status: 200,
description: '查询成功',
type: User,
})
@ApiResponse({ status: 404, description: '用户不存在' })
findOneById(@Param('id') id: string): Promise<User> {
return this.userService.findOneById(+id);
}
/**
* 更新用户信息
*/
@Patch(':id')
@ApiOperation({
summary: '更新用户信息',
description: '更新用户信息,不允许修改 username、openId、unionId',
})
@ApiParam({ name: 'id', description: '用户ID', type: Number })
@ApiResponse({
status: 200,
description: '更新成功',
type: User,
})
@ApiResponse({ status: 404, description: '用户不存在' })
@ApiResponse({ status: 409, description: '邮箱或手机号已存在' })
update(
@Param('id') id: string,
@Body() updateUserDto: UpdateUserDto,
): Promise<User> {
return this.userService.update(+id, updateUserDto);
}
/**
* 修改密码
*/
@Patch(':id/password')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({
summary: '修改密码',
description: '修改用户密码,需要先验证旧密码',
})
@ApiParam({ name: 'id', description: '用户ID', type: Number })
@ApiResponse({ status: 204, description: '密码修改成功' })
@ApiResponse({ status: 400, description: '旧密码错误' })
@ApiResponse({ status: 404, description: '用户不存在' })
changePassword(
@Param('id') id: string,
@Body() changePasswordDto: ChangePasswordDto,
): Promise<void> {
return this.userService.changePassword(+id, changePasswordDto);
}
/**
* 删除用户(软删除)
*/
@Delete(':id')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({
summary: '删除用户',
description: '软删除用户,将状态更新为 deleted',
})
@ApiParam({ name: 'id', description: '用户ID', type: Number })
@ApiResponse({ status: 204, description: '删除成功' })
@ApiResponse({ status: 404, description: '用户不存在' })
remove(@Param('id') id: string): Promise<void> {
return this.userService.remove(+id);
}
}

View File

@@ -0,0 +1,142 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
Index,
} from 'typeorm';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
@Entity('user')
export class User {
@ApiProperty({ description: '用户ID', example: 1 })
@PrimaryGeneratedColumn({ name: 'user_id' })
userId: number;
@ApiPropertyOptional({
description: '微信 openId',
example: 'openid123456',
maxLength: 100,
})
@Column({ name: 'open_id', type: 'varchar', length: 100, nullable: true })
@Index()
openId?: string;
@ApiPropertyOptional({
description: '微信 unionId',
example: 'unionid123456',
maxLength: 100,
})
@Column({ name: 'union_id', type: 'varchar', length: 100, nullable: true })
@Index()
unionId?: string;
@ApiProperty({
description: '用户名',
example: 'john_doe',
maxLength: 100,
})
@Column({ name: 'username', type: 'varchar', length: 100 })
@Index()
username: string;
@ApiProperty({
description: '密码哈希值bcrypt加密',
example: '$2b$10$...',
maxLength: 255,
})
@Column({ name: 'password_hash', type: 'varchar', length: 255 })
passwordHash: string;
@ApiProperty({
description: '邮箱',
example: 'user@example.com',
maxLength: 100,
})
@Column({ name: 'email', type: 'varchar', length: 100 })
@Index()
email: string;
@ApiPropertyOptional({
description: '电话号码',
example: '13800138000',
maxLength: 20,
})
@Column({ name: 'phone', type: 'varchar', length: 20, nullable: true })
@Index()
phone?: string;
@ApiPropertyOptional({
description: '用户昵称',
example: 'John Doe',
maxLength: 100,
})
@Column({ name: 'nickname', type: 'varchar', length: 100, nullable: true })
nickname?: string;
@ApiPropertyOptional({
description: '头像URL',
example: 'https://example.com/avatar.jpg',
maxLength: 255,
})
@Column({
name: 'avatar_url',
type: 'varchar',
length: 255,
nullable: true,
})
avatarUrl?: string;
@ApiProperty({
description: '创建时间',
example: '2024-01-01T00:00:00.000Z',
})
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@ApiProperty({
description: '更新时间',
example: '2024-01-01T00:00:00.000Z',
})
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
@ApiPropertyOptional({
description: '最后登录时间',
example: '2024-01-01T00:00:00.000Z',
})
@Column({ name: 'last_login_at', type: 'timestamp', nullable: true })
lastLoginAt?: Date;
@ApiProperty({
description: '用户状态',
example: 'active',
enum: ['active', 'inactive', 'deleted'],
default: 'active',
})
@Column({
name: 'status',
type: 'varchar',
length: 20,
default: 'active',
nullable: false,
})
status: string;
@ApiProperty({
description: '用户角色',
example: 'user',
enum: ['user', 'admin', 'super_admin'],
default: 'user',
})
@Column({
name: 'role',
type: 'varchar',
length: 20,
default: 'user',
nullable: false,
})
@Index()
role: string;
}

View File

@@ -1,4 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { User } from './user.entity';
@Module({})
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}

View File

@@ -0,0 +1,240 @@
import {
Injectable,
NotFoundException,
ConflictException,
BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { User } from './user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { QueryUserDto } from './dto/query-user.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {}
/**
* 注册用户
*/
async create(createUserDto: CreateUserDto): Promise<User> {
// 检查用户名是否已存在
const existingByUsername = await this.userRepository.findOne({
where: { username: createUserDto.username },
});
if (existingByUsername) {
throw new ConflictException(
`用户名 "${createUserDto.username}" 已存在`,
);
}
// 检查邮箱是否已存在
const existingByEmail = await this.userRepository.findOne({
where: { email: createUserDto.email },
});
if (existingByEmail) {
throw new ConflictException(`邮箱 "${createUserDto.email}" 已存在`);
}
// 检查 phone 是否已存在(如果提供了)
/* if (createUserDto.phone) {
const existingByPhone = await this.userRepository.findOne({
where: { phone: createUserDto.phone },
});
if (existingByPhone) {
throw new ConflictException(
`Phone "${createUserDto.phone}" already exists`,
);
}
}
// 检查 openId 是否已存在(如果提供了)
if (createUserDto.openId) {
const existingByOpenId = await this.userRepository.findOne({
where: { openId: createUserDto.openId },
});
if (existingByOpenId) {
throw new ConflictException(
`OpenId "${createUserDto.openId}" already exists`,
);
}
}
// 检查 unionId 是否已存在(如果提供了)
if (createUserDto.unionId) {
const existingByUnionId = await this.userRepository.findOne({
where: { unionId: createUserDto.unionId },
});
if (existingByUnionId) {
throw new ConflictException(
`UnionId "${createUserDto.unionId}" already exists`,
);
}
} */
// 使用 bcrypt 加密密码
const saltRounds = 10;
const passwordHash = await bcrypt.hash(
createUserDto.password,
saltRounds,
);
// 创建用户
const user = this.userRepository.create({
username: createUserDto.username,
passwordHash,
email: createUserDto.email,
nickname: createUserDto.nickname,
avatarUrl: createUserDto.avatarUrl,
phone: createUserDto.phone,
openId: createUserDto.openId,
unionId: createUserDto.unionId,
status: 'active',
role: createUserDto.role || 'user', // 默认为普通用户
});
return this.userRepository.save(user);
}
/**
* 查询所有用户
*/
async findAll(): Promise<User[]> {
return this.userRepository.find({
order: {
createdAt: 'DESC',
},
});
}
/**
* 根据 username 或 email 查询单个用户
*/
async findOne(queryDto: QueryUserDto): Promise<User> {
if (!queryDto.username && !queryDto.email) {
throw new BadRequestException('必须提供用户名或邮箱');
}
const where: { username?: string; email?: string } = {};
if (queryDto.username) {
where.username = queryDto.username;
}
if (queryDto.email) {
where.email = queryDto.email;
}
const user = await this.userRepository.findOne({ where });
if (!user) {
const identifier = queryDto.username || queryDto.email;
throw new NotFoundException(
`未找到${queryDto.username ? '用户名' : '邮箱'}为 "${identifier}" 的用户`,
);
}
return user;
}
/**
* 根据 ID 查询单个用户
*/
async findOneById(id: number): Promise<User> {
const user = await this.userRepository.findOne({
where: { userId: id },
});
if (!user) {
throw new NotFoundException(`未找到ID为 ${id} 的用户`);
}
return user;
}
/**
* 更新用户信息(不允许修改 username、openId、unionId
*/
async update(id: number, updateUserDto: UpdateUserDto): Promise<User> {
const user = await this.findOneById(id);
// 如果更新邮箱,检查是否与其他用户冲突
if (updateUserDto.email && updateUserDto.email !== user.email) {
const existingByEmail = await this.userRepository.findOne({
where: { email: updateUserDto.email },
});
if (existingByEmail) {
throw new ConflictException(
`邮箱 "${updateUserDto.email}" 已存在`,
);
}
}
// 如果更新 phone检查是否与其他用户冲突
if (updateUserDto.phone && updateUserDto.phone !== user.phone) {
const existingByPhone = await this.userRepository.findOne({
where: { phone: updateUserDto.phone },
});
if (existingByPhone) {
throw new ConflictException(
`手机号 "${updateUserDto.phone}" 已存在`,
);
}
}
// 更新用户信息
Object.assign(user, updateUserDto);
return this.userRepository.save(user);
}
/**
* 修改密码(需要先验证旧密码)
*/
async changePassword(
id: number,
changePasswordDto: ChangePasswordDto,
): Promise<void> {
const user = await this.findOneById(id);
// 验证旧密码
const isOldPasswordValid = await bcrypt.compare(
changePasswordDto.oldPassword,
user.passwordHash,
);
if (!isOldPasswordValid) {
throw new BadRequestException('旧密码错误');
}
// 加密新密码
const saltRounds = 10;
const newPasswordHash = await bcrypt.hash(
changePasswordDto.newPassword,
saltRounds,
);
// 更新密码
user.passwordHash = newPasswordHash;
await this.userRepository.save(user);
}
/**
* 删除用户(软删除,更新状态为 deleted
*/
async remove(id: number): Promise<void> {
const user = await this.findOneById(id);
user.status = 'deleted';
await this.userRepository.save(user);
}
}

View File

@@ -1,7 +0,0 @@
import { User } from './user';
describe('User', () => {
it('should be defined', () => {
expect(new User()).toBeDefined();
});
});

View File

@@ -1 +0,0 @@
export class User {}

View File

@@ -0,0 +1,293 @@
import { Test, TestingModule } from '@nestjs/testing';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserService } from '../../../src/modules/user/user.service';
import { User } from '../../../src/modules/user/user.entity';
import { UserModule } from '../../../src/modules/user/user.module';
import { CreateUserDto } from '../../../src/modules/user/dto/create-user.dto';
import { getDatabaseConfig } from '../../../src/database/database.config';
import { ConflictException } from '@nestjs/common';
describe('UserService (集成测试)', () => {
let service: UserService;
let repository: Repository<User>;
let module: TestingModule;
beforeAll(async () => {
jest.setTimeout(30000); // 设置超时为 30 秒
// 创建测试模块,使用真实数据库连接
module = await Test.createTestingModule({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: ['.env.development', '.env'],
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => {
const config = getDatabaseConfig(configService);
// 使用测试数据库(如果配置了),否则使用开发数据库
const testDatabase =
configService.get<string>('DB_DATABASE') ||
(config.database as string);
return {
...config,
database: testDatabase,
synchronize: true, // 测试环境允许同步
dropSchema: false, // 不删除现有数据
} as typeof config;
},
inject: [ConfigService],
}),
UserModule,
],
}).compile();
service = module.get<UserService>(UserService);
repository = module.get<Repository<User>>(getRepositoryToken(User));
// 清理测试数据(可选)
await repository.clear();
});
afterAll(async () => {
// 测试结束后清理
// await repository.clear();
await module.close();
});
describe('create - 集成测试', () => {
it('应该成功在数据库中创建用户', async () => {
const createUserDto: CreateUserDto = {
username: 'test_user_1',
password: 'password123',
email: 'test1@example.com',
nickname: '测试用户1',
};
const result = await service.create(createUserDto);
console.log('regitser result', result);
expect(result).toBeDefined();
expect(result.userId).toBeDefined();
expect(result.username).toBe(createUserDto.username);
expect(result.email).toBe(createUserDto.email);
expect(result.nickname).toBe(createUserDto.nickname);
expect(result.status).toBe('active');
expect(result.role).toBe('user'); // 默认角色
expect(result.passwordHash).toBeDefined();
expect(result.passwordHash).not.toBe(createUserDto.password); // 密码应该被加密
// 验证数据确实保存到数据库
const savedUser = await repository.findOne({
where: { userId: result.userId },
});
expect(savedUser).toBeDefined();
expect(savedUser?.username).toBe(createUserDto.username);
expect(savedUser?.email).toBe(createUserDto.email);
// 清理
await repository.remove(result);
});
it('应该使用默认角色和状态', async () => {
const createUserDto: CreateUserDto = {
username: 'test_user_2',
password: 'password123',
email: 'test2@example.com',
// 不提供 role
};
const result = await service.create(createUserDto);
expect(result.role).toBe('user'); // 默认角色
expect(result.status).toBe('active'); // 默认状态
// 清理
// await repository.remove(result);
});
it('应该支持可选字段', async () => {
const createUserDto: CreateUserDto = {
username: 'test_user_3',
password: 'password123',
email: 'test3@example.com',
nickname: '测试用户3',
avatarUrl: 'https://example.com/avatar.jpg',
phone: '13800138000',
};
const result = await service.create(createUserDto);
expect(result.nickname).toBe(createUserDto.nickname);
expect(result.avatarUrl).toBe(createUserDto.avatarUrl);
expect(result.phone).toBe(createUserDto.phone);
// 清理
// await repository.remove(result);
});
it('应该抛出 ConflictException 当用户名已存在时', async () => {
const createUserDto: CreateUserDto = {
username: 'duplicate_username',
password: 'password123',
email: 'unique@example.com',
};
// 先创建一个用户
await service.create(createUserDto);
// 尝试创建相同用户名的用户
const duplicateDto: CreateUserDto = {
username: 'duplicate_username',
password: 'password456',
email: 'another@example.com',
};
await expect(service.create(duplicateDto)).rejects.toThrow(
ConflictException,
);
await expect(service.create(duplicateDto)).rejects.toThrow(
'用户名',
);
// 清理
// const user = await repository.findOne({ where: { username: 'duplicate_username' } });
// if (user) await repository.remove(user);
});
it('应该抛出 ConflictException 当邮箱已存在时', async () => {
const createUserDto: CreateUserDto = {
username: 'unique_username',
password: 'password123',
email: 'duplicate@example.com',
};
// 先创建一个用户
await service.create(createUserDto);
// 尝试创建相同邮箱的用户
const duplicateDto: CreateUserDto = {
username: 'another_username',
password: 'password456',
email: 'duplicate@example.com',
};
await expect(service.create(duplicateDto)).rejects.toThrow(
ConflictException,
);
await expect(service.create(duplicateDto)).rejects.toThrow('邮箱');
// 清理
// const user = await repository.findOne({ where: { email: 'duplicate@example.com' } });
// if (user) await repository.remove(user);
});
});
describe('findAll - 集成测试', () => {
it('应该返回所有用户列表', async () => {
// 先创建几个测试用户
const users: CreateUserDto[] = [
{
username: 'findall_user_1',
password: 'password123',
email: 'findall1@example.com',
nickname: '查询测试用户1',
},
{
username: 'findall_user_2',
password: 'password123',
email: 'findall2@example.com',
nickname: '查询测试用户2',
},
{
username: 'findall_user_3',
password: 'password123',
email: 'findall3@example.com',
nickname: '查询测试用户3',
role: 'admin',
},
];
const createdUsers: User[] = [];
for (const userDto of users) {
const user = await service.create(userDto);
createdUsers.push(user);
}
// 查询所有用户
const result = await service.findAll();
expect(result).toBeDefined();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBeGreaterThanOrEqual(users.length);
// 验证创建的用户都在列表中
const usernames = result.map((u) => u.username);
users.forEach((userDto) => {
expect(usernames).toContain(userDto.username);
});
// 验证排序(按创建时间倒序)
if (result.length > 1) {
for (let i = 0; i < result.length - 1; i++) {
expect(
result[i].createdAt.getTime(),
).toBeGreaterThanOrEqual(result[i + 1].createdAt.getTime());
}
}
// 清理
// await repository.remove(createdUsers);
});
it('应该返回空数组当没有用户时', async () => {
// 清理所有用户
await repository.clear();
const result = await service.findAll();
expect(result).toBeDefined();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBe(0);
});
it('应该包含用户的所有字段', async () => {
// 创建一个完整信息的用户
const createUserDto: CreateUserDto = {
username: 'full_info_user',
password: 'password123',
email: 'fullinfo@example.com',
nickname: '完整信息用户',
avatarUrl: 'https://example.com/avatar.jpg',
phone: '13800138000',
role: 'admin',
};
await service.create(createUserDto);
// 查询所有用户
const result = await service.findAll();
const foundUser = result.find(
(u) => u.username === createUserDto.username,
);
expect(foundUser).toBeDefined();
expect(foundUser?.userId).toBeDefined();
expect(foundUser?.username).toBe(createUserDto.username);
expect(foundUser?.email).toBe(createUserDto.email);
expect(foundUser?.nickname).toBe(createUserDto.nickname);
expect(foundUser?.avatarUrl).toBe(createUserDto.avatarUrl);
expect(foundUser?.phone).toBe(createUserDto.phone);
expect(foundUser?.role).toBe(createUserDto.role);
expect(foundUser?.status).toBe('active');
expect(foundUser?.createdAt).toBeDefined();
expect(foundUser?.updatedAt).toBeDefined();
// 清理
// if (foundUser) await repository.remove(foundUser);
});
});
});