Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[고재훈] 휴대폰 인증 API #8

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
File renamed without changes.
9 changes: 9 additions & 0 deletions src/apis/phone/dto/issue-code.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';

export class issueCodeDto {
@IsString()
@IsNotEmpty()
@ApiProperty({ description: '전화번호', default: '010-1234-5678' })
phoneNumber: string;
}
14 changes: 14 additions & 0 deletions src/apis/phone/dto/verify-phone.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';

export class verifyPhoneDto {
@IsString()
@IsNotEmpty()
@ApiProperty({ description: '전화번호', default: '010-1234-5678' })
phoneNumber: string;

@IsString()
@IsNotEmpty()
@ApiProperty({ description: '인증번호', default: '123456' })
code: string;
}
24 changes: 24 additions & 0 deletions src/apis/phone/entities/phone.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import {
Column,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';

@Entity()
export class Phone {
@PrimaryGeneratedColumn()
id: number;

@Column({ unique: true, length: 13 })
phoneNumber: string;

@Column({ length: 6 })
code: string;

@UpdateDateColumn() //TypeORM에서 제공하는 수정여부 타임스탬프
issuedAt: Date;

@Column({ default: false })
isVerified: boolean;
}
55 changes: 55 additions & 0 deletions src/apis/phone/phone.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Controller, Post, Body, UseFilters, Catch } from '@nestjs/common';
import { PhoneService } from './phone.service';
import { issueCodeDto } from './dto/issue-code.dto';
import { verifyPhoneDto } from './dto/verify-phone.dto';
import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';

@Controller('')
export class PhoneController {
constructor(private readonly phoneService: PhoneService) {}

@Post('/issue-code')
@ApiOperation({
summary: '인증번호 발급 API',
description: '제출한 전화번호에 대한 인증번호를 발급합니다.',
})
@ApiBody({ type: issueCodeDto })
@ApiResponse({
status: 201,
description: '인증번호가 성공적으로 발급되었습니다.',
})
@ApiResponse({
status: 400,
description: '전화번호 형식이 올바르지 않습니다.',
})
async issueCode(
@Body() issueCodeDto: issueCodeDto,
): Promise<{ code: string }> {
const { phoneNumber } = issueCodeDto;
const code = await this.phoneService.issue(phoneNumber);
return { code };
}

@Post('/verify-code')
@ApiOperation({
summary: '휴대폰 인증 API',
description: '휴대폰 인증을 처리합니다.',
})
@ApiBody({ type: verifyPhoneDto })
@ApiResponse({
status: 201,
description: '휴대폰 인증이 처리되었습니다.',
})
@ApiResponse({
status: 400,
description: '제출 형식이 올바르지 않습니다.',
})
async verifyNumber(
@Body() verifyPhoneDto: verifyPhoneDto,
): Promise<{ result: boolean }> {
const { phoneNumber, code } = verifyPhoneDto;
const result = await this.phoneService.verify(phoneNumber, code);

return { result };
}
}
12 changes: 12 additions & 0 deletions src/apis/phone/phone.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PhoneService } from './phone.service';
import { PhoneController } from './phone.controller';
import { Phone } from './entities/phone.entity';

@Module({
imports: [TypeOrmModule.forFeature([Phone])],
controllers: [PhoneController],
providers: [PhoneService],
})
export class PhoneModule {}
53 changes: 53 additions & 0 deletions src/apis/phone/phone.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Phone } from './entities/phone.entity';
import { Repository } from 'typeorm';

@Injectable()
export class PhoneService {
constructor(
@InjectRepository(Phone)
private readonly phoneRepository: Repository<Phone>,
) {}

async issue(phoneNumber: string): Promise<string> {
// 무작위 인증번호 생성
const authCode = Array.from({ length: 6 }, () =>
Math.floor(Math.random() * 10),
).join('');

// 사용자 검색
let phone = await this.phoneRepository.findOne({ where: { phoneNumber } });

if (phone) {
// 사용자가 이미 존재하면, 인증번호 업데이트
phone.code = authCode;
} else {
// 사용자가 존재하지 않으면, 사용자 생성
phone = this.phoneRepository.create({ phoneNumber, code: authCode });
}

// 변경사항 저장
await this.phoneRepository.save(phone);

return authCode;
}

async verify(phoneNumber: string, authCode: string): Promise<boolean> {
// 사용자 검색
let phone = await this.phoneRepository.findOne({ where: { phoneNumber } });
const now = new Date();
const diffMin = now.getMinutes() - phone.issuedAt.getMinutes();

// 사용자가 존재 && 인증번호가 일치 && 5분 이내
if (phone && phone.code === authCode && diffMin < 5) {
// 인증여부 변경
phone.isVerified = true;
// 변경사항 저장
await this.phoneRepository.save(phone);
return true;
}

return false;
}
}
11 changes: 9 additions & 2 deletions template/source/typeorm/app.module.ts → src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { addTransactionalDataSource } from 'typeorm-transactional';
import { DataSource } from 'typeorm';
import { PhoneModule } from './apis/phone/phone.module';
import { Phone } from './apis/phone/entities/phone.entity';
import { PhoneController } from './apis/phone/phone.controller';
import { PhoneService } from './apis/phone/phone.service';

@Module({
imports: [
Expand All @@ -17,6 +21,7 @@ import { DataSource } from 'typeorm';
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
synchronize: process.env.DB_SYNC === 'true',
entities: [Phone],
timezone: 'Z',
};
},
Expand All @@ -28,8 +33,10 @@ import { DataSource } from 'typeorm';
return addTransactionalDataSource(new DataSource(options));
},
}),
TypeOrmModule.forFeature([Phone]),
PhoneModule,
],
controllers: [],
providers: [],
controllers: [PhoneController],
providers: [PhoneService],
})
export class AppModule {}
28 changes: 28 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { initializeTransactionalContext } from 'typeorm-transactional';
import { ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

async function bootstrap() {
initializeTransactionalContext();

const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe()); // HTTP 요청 필터링

// Swagger 설정, 문서 생성
const config = new DocumentBuilder()
.setTitle('휴대폰 인증 API')
.setDescription('휴대폰 인증 API 문서입니다.')
.setVersion('1.0')
.build();

// API 문서 경로 지정
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);

await app.listen(process.env.PORT || 8000);
console.log(`Application is running on: ${await app.getUrl()}`);
}

bootstrap();
6 changes: 0 additions & 6 deletions template/environment/prisma/.env.example

This file was deleted.

39 changes: 0 additions & 39 deletions template/environment/prisma/docker-compose.yml

This file was deleted.

11 changes: 0 additions & 11 deletions template/environment/typeorm/.env.example

This file was deleted.

87 changes: 0 additions & 87 deletions template/package/package.prisma.json

This file was deleted.

12 changes: 0 additions & 12 deletions template/source/prisma-src/app.module.ts

This file was deleted.

Loading