From d3a0ef6f9d2cb314bb182c92d6a77abedca79dd1 Mon Sep 17 00:00:00 2001 From: Coalery Date: Sun, 3 Nov 2024 01:02:04 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20auth=20guard=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/auth/AuthGuard.spec.ts | 38 ++++++++++++++++----------------- src/core/auth/AuthGuard.ts | 17 +++++++-------- src/core/auth/AuthModule.ts | 2 ++ src/core/core.module.ts | 2 ++ 4 files changed, 30 insertions(+), 29 deletions(-) diff --git a/src/core/auth/AuthGuard.spec.ts b/src/core/auth/AuthGuard.spec.ts index 55b7d11..51e46d5 100644 --- a/src/core/auth/AuthGuard.spec.ts +++ b/src/core/auth/AuthGuard.spec.ts @@ -1,5 +1,4 @@ -import { EntityRepository } from '@mikro-orm/mysql'; -import { getRepositoryToken } from '@mikro-orm/nestjs'; +import { EntityManager } from '@mikro-orm/mysql'; import { ExecutionContext, UnauthorizedException } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { advanceTo, clear } from 'jest-date-mock'; @@ -14,15 +13,11 @@ import { IRequester } from '@khlug/core/auth/IRequester'; import { LaravelAuthnAdapter } from '@khlug/core/auth/LaravelAuthnAdapter'; import { UserRole } from '@khlug/core/auth/UserRole'; -import { User } from '@khlug/app/domain/user/model/User'; - -import { generateUser } from '@khlug/__test__/fixtures/domain'; - describe('AuthGuard', () => { let authGuard: AuthGuard; let laravelAuthnAdapter: jest.Mocked; let clsService: jest.Mocked; - let userRepository: jest.Mocked>; + let entityManager: jest.Mocked; beforeAll(() => advanceTo(new Date())); @@ -45,9 +40,12 @@ describe('AuthGuard', () => { }, }, { - provide: getRepositoryToken(User), + provide: EntityManager, useValue: { - findOne: jest.fn(), + getConnection: (() => { + const connectionMock = { execute: jest.fn() }; + return () => connectionMock; + })(), }, }, ], @@ -56,7 +54,7 @@ describe('AuthGuard', () => { authGuard = testModule.get(AuthGuard); laravelAuthnAdapter = testModule.get(LaravelAuthnAdapter); clsService = testModule.get(ClsService); - userRepository = testModule.get(getRepositoryToken(User)); + entityManager = testModule.get(EntityManager); }); afterEach(() => clear()); @@ -121,7 +119,7 @@ describe('AuthGuard', () => { context.getHandler(), ); laravelAuthnAdapter.authenticate.mockResolvedValue('1'); - userRepository.findOne.mockResolvedValue(null); + entityManager.getConnection().execute = jest.fn().mockResolvedValue([]); await expect(authGuard.canActivate(context)).rejects.toThrow( UnauthorizedException, @@ -138,9 +136,9 @@ describe('AuthGuard', () => { context.getHandler(), ); laravelAuthnAdapter.authenticate.mockResolvedValue('1'); - userRepository.findOne.mockResolvedValue( - generateUser({ manager: false }), - ); + entityManager.getConnection().execute = jest + .fn() + .mockResolvedValue([{ id: '1', manager: false }]); await expect(authGuard.canActivate(context)).rejects.toThrow( UnauthorizedException, @@ -158,9 +156,9 @@ describe('AuthGuard', () => { context.getHandler(), ); laravelAuthnAdapter.authenticate.mockResolvedValue(userId); - userRepository.findOne.mockResolvedValue( - generateUser({ id: userId, manager: false }), - ); + entityManager.getConnection().execute = jest + .fn() + .mockResolvedValue([{ id: userId, manager: false }]); await expect(authGuard.canActivate(context)).resolves.toBe(true); @@ -184,9 +182,9 @@ describe('AuthGuard', () => { context.getHandler(), ); laravelAuthnAdapter.authenticate.mockResolvedValue(userId); - userRepository.findOne.mockResolvedValue( - generateUser({ id: userId, manager: false }), - ); + entityManager.getConnection().execute = jest + .fn() + .mockResolvedValue([{ id: userId, manager: false }]); await expect(authGuard.canActivate(context)).resolves.toBe(true); diff --git a/src/core/auth/AuthGuard.ts b/src/core/auth/AuthGuard.ts index 6ff83c0..c0c2365 100644 --- a/src/core/auth/AuthGuard.ts +++ b/src/core/auth/AuthGuard.ts @@ -1,5 +1,4 @@ -import { EntityRepository } from '@mikro-orm/core'; -import { InjectRepository } from '@mikro-orm/nestjs'; +import { EntityManager } from '@mikro-orm/mysql'; import { CanActivate, ExecutionContext, @@ -14,16 +13,12 @@ import { IRequester } from '@khlug/core/auth/IRequester'; import { LaravelAuthnAdapter } from '@khlug/core/auth/LaravelAuthnAdapter'; import { UserRole } from '@khlug/core/auth/UserRole'; -import { User } from '@khlug/app/domain/user/model/User'; - @Injectable() export class AuthGuard implements CanActivate { constructor( private readonly laravelAuthnAdapter: LaravelAuthnAdapter, private readonly clsService: ClsService, - - @InjectRepository(User) - private readonly userRepository: EntityRepository, + private readonly em: EntityManager, ) {} async canActivate(context: ExecutionContext): Promise { @@ -49,11 +44,15 @@ export class AuthGuard implements CanActivate { throw new UnauthorizedException(); } - const user = await this.userRepository.findOne({ id: requesterUserId }); - if (!user) { + // TODO: User 엔티티 정의 후 수정 필요 + const result: { manager: boolean }[] = await this.em + .getConnection() + .execute('SELECT * FROM khlug_member WHERE id = ?', [requesterUserId]); + if (!result || result.length === 0) { throw new UnauthorizedException(); } + const user = result[0]; const requester: IRequester = { userId: requesterUserId, role: user.manager ? UserRole.MANAGER : UserRole.USER, diff --git a/src/core/auth/AuthModule.ts b/src/core/auth/AuthModule.ts index b9961e7..d2fbf31 100644 --- a/src/core/auth/AuthModule.ts +++ b/src/core/auth/AuthModule.ts @@ -2,10 +2,12 @@ import { Module } from '@nestjs/common'; import { APP_GUARD } from '@nestjs/core'; import { AuthGuard } from '@khlug/core/auth/AuthGuard'; +import { LaravelAuthnAdapter } from '@khlug/core/auth/LaravelAuthnAdapter'; @Module({ providers: [ { provide: APP_GUARD, useClass: AuthGuard }, + LaravelAuthnAdapter, // TODO: TokenVerifier 구현 후 추가 ], }) diff --git a/src/core/core.module.ts b/src/core/core.module.ts index 8e3e3a1..7865e85 100644 --- a/src/core/core.module.ts +++ b/src/core/core.module.ts @@ -5,6 +5,7 @@ import { ConfigModule, ConfigService } from '@nestjs/config'; import { CqrsModule } from '@nestjs/cqrs'; import { ClsModule } from 'nestjs-cls'; +import { AuthModule } from '@khlug/core/auth/AuthModule'; import { configuration } from '@khlug/core/config'; import { DatabaseConfig } from '@khlug/core/config/DatabaseConfig'; import { EntityModels } from '@khlug/core/persistence/Entities'; @@ -12,6 +13,7 @@ import { EntityModels } from '@khlug/core/persistence/Entities'; @Global() @Module({ imports: [ + AuthModule, ClsModule.forRoot({ middleware: { mount: true } }), ConfigModule.forRoot({ envFilePath: `.env.${process.env.NODE_ENV}`,