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 #7

Open
wants to merge 3 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
4 changes: 2 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ PORT=8000
# DB 세팅 환경 변수입니다
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=user
DB_PASSWORD=password
DB_USERNAME=root
DB_PASSWORD=1234
DB_DATABASE=nest_db

DB_SYNC=true
45 changes: 30 additions & 15 deletions package-lock.json

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

6 changes: 5 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { addTransactionalDataSource } from 'typeorm-transactional';
import { DataSource } from 'typeorm';
import { PhoneModule } from './phone/phone.module';
import { Phone } from './phone/entities/phone.entity';

@Module({
imports: [
Expand All @@ -11,11 +13,12 @@ import { DataSource } from 'typeorm';
useFactory() {
return {
type: 'mysql',
host: process.env.DB_HOST,
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT),
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
entities: [Phone],
synchronize: process.env.DB_SYNC === 'true',
timezone: 'Z',
};
Expand All @@ -28,6 +31,7 @@ import { DataSource } from 'typeorm';
return addTransactionalDataSource(new DataSource(options));
},
}),
PhoneModule,
],
controllers: [],
providers: [],
Expand Down
23 changes: 23 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,38 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { initializeTransactionalContext } from 'typeorm-transactional';

async function bootstrap() {
initializeTransactionalContext();

const app = await NestFactory.create(AppModule);


const config = new DocumentBuilder()
.setTitle('핸드폰 인증')
.setDescription('핸드폰 인증 API 문서')
.setVersion('1.0')
.addTag('phone')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
)

// TODO: 프로그램 구현
await app.listen(process.env.PORT || 8000);

console.log(`Application is running on: ${await app.getUrl()}`);



}

bootstrap();
7 changes: 7 additions & 0 deletions src/phone/dto/codeRequest.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {IsNotEmpty, IsString } from "class-validator";

export class CodeRequestDto {
@IsString()
@IsNotEmpty()
code: string;
}
13 changes: 13 additions & 0 deletions src/phone/dto/codeResponse.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { IsNotEmpty, IsString } from 'class-validator';

export class CodeResponseDto {
@IsString()
@IsNotEmpty()
code: string;

constructor(code: string) {
this.code = code;

}

}
12 changes: 12 additions & 0 deletions src/phone/dto/phoneNumberRequest.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { IsNotEmpty, IsString, Matches } from "class-validator";

export class PhoneNumberRequestDto {
@IsString()
@IsNotEmpty()
@Matches(/^010-\d{4}-\d{4}$/, {
message: 'Invalid phone num',
}
)
phone: string;

}
12 changes: 12 additions & 0 deletions src/phone/dto/resultResponse.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { IsEmail,IsNotEmpty,IsString } from "class-validator";

export class ResultResponseDto {

@IsNotEmpty()
result: boolean;


constructor(result: boolean) {
this.result = result;
}
}
18 changes: 18 additions & 0 deletions src/phone/entities/phone.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Phone {
@PrimaryGeneratedColumn()
id: number;

@Column()
phone: string;

@Column()
code: string;

// @Column()
// isVerified: boolean;

@Column()
createdAt: string;
}
20 changes: 20 additions & 0 deletions src/phone/phone.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PhoneController } from './phone.controller';
import { PhoneService } from './phone.service';

describe('PhoneController', () => {
let controller: PhoneController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [PhoneController],
providers: [PhoneService],
}).compile();

controller = module.get<PhoneController>(PhoneController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
23 changes: 23 additions & 0 deletions src/phone/phone.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Controller, Get, Post, Body, Patch, Param, Delete,ValidationPipe } from '@nestjs/common';
import { PhoneService } from './phone.service';

import { PhoneNumberRequestDto } from './dto/phoneNumberRequest.dto';
import { ResultResponseDto } from './dto/resultResponse.dto';
import { CodeRequestDto } from './dto/codeRequest.dto';
import { CodeResponseDto } from './dto/codeResponse.dto';
//import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';

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

@Post('/createCode') //번호받았을때 db화긴후 인증번호 전송
createCode(@Body() phoneNumberRequestDto: PhoneNumberRequestDto) {
return this.phoneService.sendCode(phoneNumberRequestDto);
}

@Post('/verifyCode')
verifyCode(@Body() codeRequestDto: CodeRequestDto) {
return this.phoneService.verifyCode(codeRequestDto);
}
}
12 changes: 12 additions & 0 deletions src/phone/phone.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { PhoneService } from './phone.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Phone } from './entities/phone.entity';
import { PhoneController } from './phone.controller';

@Module({
imports: [TypeOrmModule.forFeature([Phone])],
controllers: [PhoneController],
providers: [PhoneService],
})
export class PhoneModule {}
18 changes: 18 additions & 0 deletions src/phone/phone.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PhoneService } from './phone.service';

describe('PhoneService', () => {
let service: PhoneService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [PhoneService],
}).compile();

service = module.get<PhoneService>(PhoneService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
59 changes: 59 additions & 0 deletions src/phone/phone.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Phone } from './entities/phone.entity';
import { Repository } from 'typeorm';
import { CodeRequestDto } from './dto/codeRequest.dto';
import { PhoneNumberRequestDto } from './dto/phoneNumberRequest.dto';
import { ResultResponseDto } from './dto/resultResponse.dto';
import { CodeResponseDto } from './dto/codeResponse.dto';

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

createCode() {
return String(Math.floor(Math.random()*1000000)).padStart(6, "0");

}

sendCode(phoneNumberRequestDto: PhoneNumberRequestDto): CodeResponseDto {

//if 번호 존재하면 code 만 업데이트 하기
const phoneEntity = new Phone();
phoneEntity.phone = phoneNumberRequestDto.phone;
phoneEntity.code = this.createCode();
phoneEntity.createdAt = new Date().toString();

this.phoneRepository.save(phoneEntity);
const codeResponseDto = new CodeResponseDto(phoneEntity.code);
return codeResponseDto;
}

async verifyCode(codeRequestDto: CodeRequestDto): Promise<ResultResponseDto> {
try {
const phoneEntity =await this.phoneRepository.findOne({
where :{code: codeRequestDto.code}});

if (phoneEntity) {
const createdAtDate = new Date(phoneEntity.createdAt);
const now = new Date();


const differenceInMilliseconds = now.getTime() - createdAtDate.getTime();
const isWithin5Minutes = differenceInMilliseconds <= 5 * 60 * 1000;
const resultResponseDto = new ResultResponseDto(true);
return resultResponseDto;
} else {
const resultResponseDto = new ResultResponseDto(false);
return resultResponseDto;
}
} catch (error) {
console.error('Error querying the database:', error);
const resultResponseDto = new ResultResponseDto(false);
return resultResponseDto;
}
}
}
Loading