feat: 实现登录鉴权 RBAC 与用户管理模块
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user