Skip to content

Commit

Permalink
fix: auth guard 적용 (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
Coalery authored Nov 2, 2024
2 parents 5e454ee + d3a0ef6 commit 8688619
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 29 deletions.
38 changes: 18 additions & 20 deletions src/core/auth/AuthGuard.spec.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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<LaravelAuthnAdapter>;
let clsService: jest.Mocked<ClsService>;
let userRepository: jest.Mocked<EntityRepository<User>>;
let entityManager: jest.Mocked<EntityManager>;

beforeAll(() => advanceTo(new Date()));

Expand All @@ -45,9 +40,12 @@ describe('AuthGuard', () => {
},
},
{
provide: getRepositoryToken(User),
provide: EntityManager,
useValue: {
findOne: jest.fn(),
getConnection: (() => {
const connectionMock = { execute: jest.fn() };
return () => connectionMock;
})(),
},
},
],
Expand All @@ -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());
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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);

Expand All @@ -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);

Expand Down
17 changes: 8 additions & 9 deletions src/core/auth/AuthGuard.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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<User>,
private readonly em: EntityManager,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
Expand All @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions src/core/auth/AuthModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 구현 후 추가
],
})
Expand Down
2 changes: 2 additions & 0 deletions src/core/core.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ 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';

@Global()
@Module({
imports: [
AuthModule,
ClsModule.forRoot({ middleware: { mount: true } }),
ConfigModule.forRoot({
envFilePath: `.env.${process.env.NODE_ENV}`,
Expand Down

0 comments on commit 8688619

Please sign in to comment.