Skip to content
Draft
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
8 changes: 8 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema

# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings

DATABASE_URL=
secret=
11 changes: 11 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,16 @@
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.2",
"@nestjs/platform-express": "^10.0.0",
"@prisma/client": "^5.6.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"prisma": "^5.6.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1"
},
Expand All @@ -34,6 +43,8 @@
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/passport-jwt": "^3.0.13",
"@types/passport-local": "^1.0.38",
"@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
Expand Down
12 changes: 12 additions & 0 deletions prisma/migrations/20231119154116_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- CreateTable
CREATE TABLE "user" (
"id" TEXT NOT NULL,
"name" VARCHAR(64) NOT NULL,
"email" VARCHAR(64) NOT NULL,
"password" VARCHAR(64) NOT NULL,

CONSTRAINT "user_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "user_id_key" ON "user"("id");
2 changes: 2 additions & 0 deletions prisma/migrations/20231119154336_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "user" ADD COLUMN "idx" SERIAL NOT NULL;
6 changes: 6 additions & 0 deletions prisma/migrations/20231119154600_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/*
Warnings:
- You are about to drop the column `idx` on the `user` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "user" DROP COLUMN "idx";
19 changes: 19 additions & 0 deletions prisma/migrations/20231120003024_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
Warnings:
- You are about to drop the `user` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropTable
DROP TABLE "user";

-- CreateTable
CREATE TABLE "user1" (
"id" TEXT NOT NULL,
"name" VARCHAR(64) NOT NULL,
"email" VARCHAR(64) NOT NULL,
"password" VARCHAR(64) NOT NULL,

CONSTRAINT "user1_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "user1_id_key" ON "user1"("id");
12 changes: 12 additions & 0 deletions prisma/migrations/20231120003348_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- CreateTable
CREATE TABLE "user2" (
"id" TEXT NOT NULL,
"name" VARCHAR(64) NOT NULL,
"email" VARCHAR(64) NOT NULL,
"password" VARCHAR(64) NOT NULL,

CONSTRAINT "user2_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "user2_id_key" ON "user2"("id");
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
17 changes: 17 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model User {
id String @id @unique @default(uuid())
name String @db.VarChar(64)
email String @unique @db.VarChar(64)
password String @db.VarChar(64)

@@map("user")
}
25 changes: 21 additions & 4 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,27 @@
import { JwtModule } from '@nestjs/jwt';
import { Module } from '@nestjs/common';
import { UserController } from './user/user.controller';

import { UserService } from './user/user.service';
import { PrismaService } from './prisma/prisma.service';
import { AuthModule } from './auth/auth.module';
import { UserModule } from './user/user.module';
import { AuthController } from './auth/auth.controller';
import { AuthService } from './auth/auth.service';
import { PassportModule } from '@nestjs/passport';

@Module({
imports: [],
controllers: [UserController],
providers: [UserService],
imports: [
AuthModule,
UserModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: process.env.secret,
signOptions: {
expiresIn: 60 * 60,
},
}),
],
controllers: [AuthController],
providers: [UserService, PrismaService, AuthService],
})
export class AppModule {}
27 changes: 27 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { SignupBody, LoginBody } from './dto/auth.dto';
import {
Body,
Controller,
Get,
Post,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}

@Post('signup')
@UsePipes(ValidationPipe)
signUp(@Body() signupBody: SignupBody) {
return this.authService.signup(signupBody);
}

@Post('login')
@UsePipes(ValidationPipe)
login(@Body() loginBody: LoginBody) {
return this.authService.login(loginBody);
}
}
22 changes: 22 additions & 0 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { PrismaService } from './../prisma/prisma.service';
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { UserService } from 'src/user/user.service';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';

@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: process.env.secret,
signOptions: {
expiresIn: 60 * 60,
},
}),
],
providers: [AuthService, UserService, PrismaService],
controllers: [AuthController],
})
export class AuthModule {}
44 changes: 44 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { PrismaService } from './../prisma/prisma.service';
import { UserService } from 'src/user/user.service';
import {
BadRequestException,
Injectable,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { Messeges } from 'src/utils/messege.utils';

import { LoginBody, SignupBody } from './dto/auth.dto';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
constructor(
private userService: UserService,
private jwtService: JwtService,
) {}

async signup(userData: SignupBody) {
const { password, email, name } = userData;
try {
const response = await this.userService.createOne(userData);
} catch (response) {
if (response.code === 'P2002') {
throw new BadRequestException(Messeges.already.email);
}
}
return { messege: Messeges.success.signup };
}

async login(loginData: LoginBody) {
const { email, password } = loginData;
const currentUser = await this.userService.findOne(email);
if (!currentUser) return new NotFoundException(Messeges.notFound.email);
if (currentUser.password !== password)
return new UnauthorizedException(Messeges.correct.password);

const payload = { email: email };
const accessToken = await this.jwtService.sign(payload);
return { accessToken: accessToken };
}
}
28 changes: 28 additions & 0 deletions src/auth/dto/auth.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { IsEmail, IsNotEmpty, IsString, Length } from 'class-validator';

export class SignupBody {
@IsNotEmpty()
@IsString()
@Length(1, 16)
name: string;

@IsNotEmpty()
@IsEmail()
email: string;

@IsNotEmpty()
@IsString()
@Length(1, 16)
password: string;
}

export class LoginBody {
@IsNotEmpty()
@IsEmail()
email: string;

@IsNotEmpty()
@IsString()
@Length(1, 16)
password: string;
}
Empty file added src/auth/jwt.stratefy.ts
Empty file.
5 changes: 5 additions & 0 deletions src/auth/jwt/jwt.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
14 changes: 14 additions & 0 deletions src/auth/jwt/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), // 헤더로부터 토큰 추출하는 함수
secretOrKey: process.env.JWT_SECRET_KEY,
ignoreExpiration: false,
});
}
}
17 changes: 17 additions & 0 deletions src/auth/pipe/validation.pipe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { ArgumentMetadata, PipeTransform } from '@nestjs/common';
import { ArgumentOutOfRangeError } from 'rxjs';

export class ValidationPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
console.log(
'🚀 ~ file: validation.pipe.ts:6 ~ ValidationPipe ~ transform ~ metadata:',
metadata,
);
console.log(
'🚀 ~ file: validation.pipe.ts:6 ~ ValidationPipe ~ transform ~ value:',
value,
);

return value;
}
}
16 changes: 0 additions & 16 deletions src/model/user.model.ts

This file was deleted.

9 changes: 9 additions & 0 deletions src/prisma/prisma.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$connect();
}
}
23 changes: 0 additions & 23 deletions src/user/user.controller.ts

This file was deleted.

9 changes: 9 additions & 0 deletions src/user/user.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { PrismaService } from 'src/prisma/prisma.service';

@Module({
providers: [UserService, PrismaService],
exports: [UserService],
})
export class UserModule {}
Loading