Skip to content

Commit

Permalink
Merge pull request #275 from boostcampwm-2024/feat/#267/guest-login
Browse files Browse the repository at this point in the history
[Feat] guest login 도입
  • Loading branch information
begong313 authored Nov 26, 2024
2 parents 55c402f + 4bb6d11 commit 1a544b6
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 10 deletions.
1 change: 1 addition & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^8.0.1",
"@nestjs/throttler": "^6.2.1",
"@nestjs/typeorm": "^10.0.2",
"@repo/types": "workspace:*",
"bcrypt": "^5.1.1",
Expand Down
7 changes: 7 additions & 0 deletions apps/api/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { ThrottlerModule } from '@nestjs/throttler';
import { TypeOrmModule } from '@nestjs/typeorm';

import { TypeOrmConfigService } from '@/config/typeorm.config';
Expand All @@ -16,6 +17,12 @@ import { UserModule } from './user/user.module';
isGlobal: true,
envFilePath: '.env',
}),
ThrottlerModule.forRoot([
{
ttl: 60000,
limit: 100,
},
]),
AuthModule,
TicleModule,
StreamModule,
Expand Down
16 changes: 13 additions & 3 deletions apps/api/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Body, Controller, Get, Post, Res, UseGuards } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { ThrottlerGuard } from '@nestjs/throttler';
import { Response } from 'express';

import { GetUserId } from '@/common/decorator/get-userId.decorator';
Expand All @@ -22,7 +23,7 @@ export class AuthController {
) {}

@Post('signup')
@ApiOperation({ summary: '회원가입' })
@ApiOperation({ summary: '로컬 회원가입' })
@ApiResponse({ status: 201, type: SignupResponseDto })
@ApiResponse({ status: 409 })
async signup(@Body() createUserDto: LocalSignupRequestDto): Promise<SignupResponseDto> {
Expand All @@ -40,6 +41,15 @@ export class AuthController {
this.cookieInsertJWT(response, userId);
}

@Post('guest/login')
@ApiOperation({ summary: '게스트 로그인' })
@ApiResponse({ status: 302, description: '홈으로 리다이렉션' })
@UseGuards(ThrottlerGuard)
async guestLogin(@Res() response: Response) {
const guestUser = await this.authService.createGuestUser();
this.cookieInsertJWT(response, guestUser.id);
}

@Get('google/login')
@ApiOperation({ summary: '구글 OAuth 로그인' })
@ApiResponse({ status: 302, description: '홈으로 리다이렉션' })
Expand Down Expand Up @@ -75,12 +85,12 @@ export class AuthController {
});
}

private async cookieInsertJWT(
private cookieInsertJWT(
response: Response,
userId: number,
redirectUrl: string = this.configService.get<string>('LOGIN_REDIRECT_URL')
) {
const { accessToken } = await this.authService.createJWT(userId);
const { accessToken } = this.authService.createJWT(userId);
this.setAuthCookie(response, accessToken);
response.redirect(redirectUrl);
}
Expand Down
22 changes: 19 additions & 3 deletions apps/api/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,24 @@ export class AuthService {
if (!isPasswordValid) {
throw new UnauthorizedException('잘못된 로그인 정보');
}
const { password, ...result } = user;
return result;
return user;
}

async createGuestUser() {
const randomNum = Math.floor(Math.random() * 10000);
const guestUser = {
username: `guest_${randomNum}`,
password: `guest_password_${randomNum}`,
email: `[email protected]`,
nickname: `guest_${randomNum}`,
introduce: `게스트 사용자입니다. `,
profileImageUrl: `https://cataas.com/cat?${Date.now()}`,
};
const user = await this.userService.findUserByUsername(guestUser.username);
if (!user) {
return this.userService.createLocalUser({ provider: 'guest', ...guestUser });
}
return user;
}

async checkSocialUser(socialUserData: CreateSocialUserDto) {
Expand All @@ -42,7 +58,7 @@ export class AuthService {
return user;
}

async createJWT(userId: number) {
createJWT(userId: number) {
const payload = { sub: userId };
return {
accessToken: this.jwtService.sign(payload),
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/ticle/ticle.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Body, Controller, Get, Param, Post, Query, UseGuards, UsePipes } from '@nestjs/common';
import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
import { CreateTicleSchema } from '@repo/types';

import { JwtAuthGuard } from '@/auth/jwt/jwt-auth.guard';
Expand Down
5 changes: 2 additions & 3 deletions apps/api/src/user/user.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { ConflictException, InternalServerErrorException } from '@nestjs/common'
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import * as bcrypt from 'bcrypt';
import { Repository } from 'typeorm';

import { User } from '@/entity/user.entity';

Expand Down Expand Up @@ -55,7 +54,7 @@ describe('UserService', () => {
});

it('should throw InternalServerErrorException on database error', async () => {
mockUserRepository.exists.mockRejectedValue(new Error('DB Error'));
mockUserRepository.exists.mockRejectedValue(new InternalServerErrorException());

await expect(service.createLocalUser(createLocalUserDto)).rejects.toThrow(
InternalServerErrorException
Expand Down Expand Up @@ -88,7 +87,7 @@ describe('UserService', () => {

it('should throw InternalServerErrorException on database error', async () => {
mockUserRepository.create.mockReturnValue(createSocialUserDto);
mockUserRepository.save.mockRejectedValue(new Error('DB Error'));
mockUserRepository.save.mockRejectedValue(new InternalServerErrorException());

await expect(service.createSocialUser(createSocialUserDto)).rejects.toThrow(
InternalServerErrorException
Expand Down
16 changes: 16 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 1a544b6

Please sign in to comment.