feat: 开发user、auth相关接口,初始化后台管理项目admin
This commit is contained in:
66
apps/api/src/modules/auth/auth.controller.ts
Normal file
66
apps/api/src/modules/auth/auth.controller.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
41
apps/api/src/modules/auth/auth.module.ts
Normal file
41
apps/api/src/modules/auth/auth.module.ts
Normal 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 {}
|
||||
73
apps/api/src/modules/auth/auth.service.ts
Normal file
73
apps/api/src/modules/auth/auth.service.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
37
apps/api/src/modules/auth/decorators/roles.decorator.ts
Normal file
37
apps/api/src/modules/auth/decorators/roles.decorator.ts
Normal 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);
|
||||
22
apps/api/src/modules/auth/dto/login.dto.ts
Normal file
22
apps/api/src/modules/auth/dto/login.dto.ts
Normal 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;
|
||||
}
|
||||
24
apps/api/src/modules/auth/guards/jwt-auth.guard.ts
Normal file
24
apps/api/src/modules/auth/guards/jwt-auth.guard.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
44
apps/api/src/modules/auth/guards/roles.guard.ts
Normal file
44
apps/api/src/modules/auth/guards/roles.guard.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export interface JwtPayload {
|
||||
sub: number; // 用户ID
|
||||
username: string;
|
||||
email: string;
|
||||
role: string;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { User } from '../../user/user.entity';
|
||||
|
||||
export interface LoginResponse {
|
||||
accessToken: string;
|
||||
user: Omit<User, 'passwordHash'>; // 排除密码哈希
|
||||
}
|
||||
38
apps/api/src/modules/auth/strategies/jwt.strategy.ts
Normal file
38
apps/api/src/modules/auth/strategies/jwt.strategy.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -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}" 的券商`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
23
apps/api/src/modules/user/dto/change-password.dto.ts
Normal file
23
apps/api/src/modules/user/dto/change-password.dto.ts
Normal 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;
|
||||
}
|
||||
109
apps/api/src/modules/user/dto/create-user.dto.ts
Normal file
109
apps/api/src/modules/user/dto/create-user.dto.ts
Normal 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;
|
||||
}
|
||||
20
apps/api/src/modules/user/dto/query-user.dto.ts
Normal file
20
apps/api/src/modules/user/dto/query-user.dto.ts
Normal 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;
|
||||
}
|
||||
73
apps/api/src/modules/user/dto/update-user.dto.ts
Normal file
73
apps/api/src/modules/user/dto/update-user.dto.ts
Normal 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;
|
||||
}
|
||||
180
apps/api/src/modules/user/user.controller.ts
Normal file
180
apps/api/src/modules/user/user.controller.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
142
apps/api/src/modules/user/user.entity.ts
Normal file
142
apps/api/src/modules/user/user.entity.ts
Normal 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;
|
||||
}
|
||||
@@ -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 {}
|
||||
|
||||
240
apps/api/src/modules/user/user.service.ts
Normal file
240
apps/api/src/modules/user/user.service.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import { User } from './user';
|
||||
|
||||
describe('User', () => {
|
||||
it('should be defined', () => {
|
||||
expect(new User()).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -1 +0,0 @@
|
||||
export class User {}
|
||||
Reference in New Issue
Block a user