feat: auth guard 增加
This commit is contained in:
1 parent
346742b157
commit
a2ee53f83a
11 files changed
+245
-6
No files matched your search
@@ -0,0 +1,2 @@
|
||||
export const JWT_SECRET = 'jwtSecret';
|
||||
export const JWT_EXPIRATION = '1h';
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { TokenCreateRequest } from '../dto/token-create.request';
|
||||
import { NoAuth } from '../decorators/no-auth.decorator';
|
||||
|
||||
@Controller('/tokens')
|
||||
export class TokenController {
|
||||
@Post()
|
||||
@NoAuth()
|
||||
create(@Body() tokenCreateRequest: TokenCreateRequest) {
|
||||
return tokenCreateRequest.username;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,15 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { TokenController } from './controller/token.controller';
|
||||
import { UserService } from './service/user.service';
|
||||
import { User } from './entity/user.entity';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { AuthGuard } from './guards/auth.guard';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
|
||||
@Module({
|
||||
controllers: [TokenController],
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
@@ -21,11 +28,23 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
password: configService.get<string>('DB_PASSWORD'),
|
||||
database: configService.get<string>('DB_NAME'),
|
||||
autoLoadEntities: true,
|
||||
entities: [__dirname + '/**/*.entity{.ts,.js}'],
|
||||
synchronize: process.env.NODE_ENV === 'development',
|
||||
logging: true,
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
TypeOrmModule.forFeature([User]),
|
||||
],
|
||||
providers: [
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: AuthGuard,
|
||||
},
|
||||
UserService,
|
||||
JwtService,
|
||||
],
|
||||
exports: [UserService],
|
||||
})
|
||||
@Global()
|
||||
export class CoreModule {}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const NO_AUTH_KEY = 'noAuth';
|
||||
export const NoAuth = () => SetMetadata(NO_AUTH_KEY, true);
|
||||
@@ -0,0 +1,16 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty } from 'class-validator';
|
||||
|
||||
export class TokenCreateRequest {
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
})
|
||||
@IsNotEmpty({ message: '用户名不能为空' })
|
||||
username: string;
|
||||
|
||||
@IsNotEmpty({ message: '密码不能为空' })
|
||||
@ApiProperty({
|
||||
required: true,
|
||||
})
|
||||
password: string;
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import { BaseEntity } from './base.entity';
|
||||
import { Entity, ManyToOne } from 'typeorm';
|
||||
import { ManyToOne } from 'typeorm';
|
||||
import { User } from './user.entity';
|
||||
|
||||
@Entity()
|
||||
export abstract class TraceableEntity extends BaseEntity {
|
||||
@ManyToOne(() => User)
|
||||
createBy: User;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { UserService } from '../service/user.service';
|
||||
import { NO_AUTH_KEY } from '../decorators/no-auth.decorator';
|
||||
import { JWT_SECRET } from '../constants/jwt';
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly userService: UserService, // 注入 UserService
|
||||
) {}
|
||||
async canActivate(context: ExecutionContext) {
|
||||
const isNoAuth = this.reflector.getAllAndOverride<boolean>(NO_AUTH_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (isNoAuth) {
|
||||
return true;
|
||||
}
|
||||
// 获取请求对象
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Missing authorization token');
|
||||
}
|
||||
try {
|
||||
// 验证并解析 JWT
|
||||
const payload = await this.jwtService.verifyAsync(token, {
|
||||
secret: JWT_SECRET,
|
||||
});
|
||||
|
||||
// 从 UserService 加载用户
|
||||
const user = await this.userService.findById(payload.sub);
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('User not found');
|
||||
}
|
||||
|
||||
// 将用户信息附加到请求对象
|
||||
request.user = user;
|
||||
return true;
|
||||
} catch (error) {
|
||||
throw new UnauthorizedException('Invalid token');
|
||||
}
|
||||
}
|
||||
private extractTokenFromHeader(request: any): string | null {
|
||||
const authHeader = request.headers['Authorization'];
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return null;
|
||||
}
|
||||
return authHeader.split(' ')[1];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { User } from '../entity/user.entity';
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
constructor(
|
||||
@InjectRepository(User) private readonly userRepository: Repository<User>,
|
||||
) {}
|
||||
async findById(id: string) {
|
||||
return this.userRepository.findOne({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
+5
-4
@@ -5,6 +5,10 @@ import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
|
||||
async function bootstrap() {
|
||||
SnowflakeUtil.initialize(
|
||||
parseInt(process.env.WORKER_ID, 10),
|
||||
parseInt(process.env.DATACENTER_ID, 10),
|
||||
);
|
||||
const app = await NestFactory.create(AppModule);
|
||||
if (['development', 'test'].includes(process.env.NODE_ENV)) {
|
||||
const config = new DocumentBuilder()
|
||||
@@ -15,10 +19,7 @@ async function bootstrap() {
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('docs', app, document);
|
||||
}
|
||||
SnowflakeUtil.initialize(
|
||||
parseInt(process.env.WORKER_ID, 10),
|
||||
parseInt(process.env.DATACENTER_ID, 10),
|
||||
);
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
transform: true,
|
||||
|
||||
Reference in new issue
Block a user