Skip to content

Commit

Permalink
feat: guard logic more correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
iqeq1945 committed Nov 21, 2024
1 parent c99cada commit 361d8e2
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 6 deletions.
5 changes: 5 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { LocalAuthenticatedGuard } from './local-auth.guard';
import { LoginUserDto } from 'src/user/dto/login-user.dto';
import { ConfigService } from '@nestjs/config';
import { CloudflareGuard } from './cf-auth.guard';
import { IsJogongGuard } from './jogong-auth.guard';

@ApiTags('Auth')
@Controller('auth')
Expand All @@ -44,6 +45,7 @@ export class AuthController {
},
})
@Post('login')
@UseGuards(IsJogongGuard)
@UseGuards(LocalAuthenticatedGuard)
@UseGuards(IsNotLoginedGuard)
async localLogin(
Expand All @@ -67,6 +69,7 @@ export class AuthController {
},
})
@Post('signup')
@UseGuards(IsJogongGuard)
@UseGuards(IsNotLoginedGuard)
async signup(@Body() user: CreateUserDto): Promise<any> {
return await this.authService.signup(user);
Expand Down Expand Up @@ -105,6 +108,7 @@ export class AuthController {
}

@Get('wakta')
@UseGuards(IsJogongGuard)
async waktaOauth(@Session() session: Record<string, any>) {
const data = await this.authService.waktaOauth();
session.auth = data;
Expand Down Expand Up @@ -145,6 +149,7 @@ export class AuthController {
}

@Get('guest')
@UseGuards(IsJogongGuard)
async guest(@Session() session) {
session.user = await this.authService.guestUser();
return session.user ? { status: 200 } : { status: 400 };
Expand Down
2 changes: 2 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import * as bcrypt from 'bcrypt';
import { Request } from 'express';
import { WakgamesService } from 'src/wakgames/wakgames.service';
import { randomUUID } from 'crypto';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AuthService {
constructor(
private readonly userService: UserService,
private readonly wakgamesService: WakgamesService,
private readonly config: ConfigService,
) {}

async OAuthLogin(user) {
Expand Down
22 changes: 16 additions & 6 deletions src/auth/cf-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import {
Injectable,
CanActivate,
ExecutionContext,
Logger,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as jwt from 'jsonwebtoken';
import * as jwksClient from 'jwks-rsa';

@Injectable()
export class CloudflareGuard implements CanActivate {
private client: jwksClient.JwksClient;
private readonly client: jwksClient.JwksClient;
private readonly logger = new Logger(CloudflareGuard.name);

constructor(config: ConfigService) {
const domain = config.get('CLOUD_DOMAIN');
Expand All @@ -23,17 +29,17 @@ export class CloudflareGuard implements CanActivate {
const token = authHeader && authHeader.split(' ')[1];

if (!token) {
console.error('JWT 없음: Authorization 헤더가 비어 있습니다.');
this.logger.error('JWT 없음: Authorization 헤더가 비어 있습니다.');
return false;
}

try {
const decoded = await this.verifyToken(token);
// 검증 성공 시 사용자 정보를 요청 객체에 저장
request.user = decoded;
this.logger.log('JWT 검증 성공');
return true;
} catch (error) {
console.error('JWT 검증 실패:', error.message);
this.logger.error('JWT 검증 실패:', error.message);
return false;
}
}
Expand All @@ -43,11 +49,13 @@ export class CloudflareGuard implements CanActivate {
jwt.verify(
token,
(header, callback) => this.getKey(header, callback),
{ algorithms: ['RS256'] }, // Cloudflare는 RS256 알고리즘 사용
{ algorithms: ['RS256'] },
(err, decoded) => {
if (err) {
this.logger.error('토큰 검증 오류:', err.message);
return reject(err);
}
this.logger.log('토큰 검증 완료');
resolve(decoded);
},
);
Expand All @@ -57,9 +65,11 @@ export class CloudflareGuard implements CanActivate {
private getKey(header: jwt.JwtHeader, callback: jwt.SigningKeyCallback) {
this.client.getSigningKey(header.kid, (err, key) => {
if (err) {
this.logger.error(`키 가져오기 실패: ${err.message}`);
return callback(err, null);
}
const signingKey = key.getPublicKey();
this.logger.log(`키 가져오기 성공: kid=${header.kid}`);
callback(null, signingKey);
});
}
Expand Down
25 changes: 25 additions & 0 deletions src/auth/jogong-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class IsJogongGuard implements CanActivate {
constructor(private readonly configService: ConfigService) {}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
canActivate(context: ExecutionContext): boolean {
const NODE_ENV = this.configService.get<string>('NODE_ENV');

if (NODE_ENV !== 'jogong') {
throw new ForbiddenException(
'Access to this resource is forbidden in the current environment.',
);
}

return true;
}
}

0 comments on commit 361d8e2

Please sign in to comment.