Compare commits
49 Commits
0170421d16
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 91e4f987ea | |||
| 1611026688 | |||
| e4048843e9 | |||
|
|
0f0717fc79 | ||
| 58d092536e | |||
|
|
56cee12c81 | ||
| 43868489e0 | |||
| be65742caa | |||
| ab99d23de3 | |||
| 5c79aa18f4 | |||
|
|
810b4c1fb0 | ||
|
|
3bea9bca11 | ||
|
|
115c5e61f0 | ||
|
|
4365f29e27 | ||
|
|
f71415d7c0 | ||
|
|
ca1e6071cf | ||
|
|
4d77d2689b | ||
|
|
c58ee43112 | ||
|
|
9bd7df97d4 | ||
|
|
6d36fcab7e | ||
|
|
3ed2975e04 | ||
|
|
75d4173124 | ||
|
|
ba70c32d34 | ||
|
|
ac5b6bdc52 | ||
|
|
a951895850 | ||
|
|
778904ff6d | ||
|
|
d815dd73dd | ||
|
|
36ea7a6be4 | ||
|
|
4f6eba3430 | ||
|
|
6f7aa2b309 | ||
|
|
72fd7594c1 | ||
|
|
0fa55acc14 | ||
|
|
ea85899906 | ||
|
|
3747838f9a | ||
|
|
7035c7b7c3 | ||
|
|
25c7c52dd4 | ||
| 92376b8aec | |||
| 4a42080024 | |||
| ccfbdaffe2 | |||
|
|
ab74fd1a71 | ||
|
|
7ea116dc8e | ||
|
|
5e65a70ce2 | ||
|
|
818aa659fc | ||
|
|
f810fc888d | ||
|
|
dbf96453b5 | ||
|
|
fb544e9e3a | ||
|
|
dce509bad9 | ||
|
|
8303a8ab19 | ||
|
|
6cd0361375 |
28
.env
28
.env
@@ -1,28 +0,0 @@
|
|||||||
# PostgreSQL 설정
|
|
||||||
PGHOST=bkdhome.p-e.kr
|
|
||||||
PGPORT=15454
|
|
||||||
PGDATABASE=scheduler
|
|
||||||
PGUSER=baekyangdan
|
|
||||||
PGPASSWORD=qwas745478!
|
|
||||||
PG_DATABASE_URL=postgres://baekyangdan:qwas745478!@bkdhome.p-e.kr:15454/scheduler
|
|
||||||
|
|
||||||
# Redis 설정
|
|
||||||
RD_HOST=bkdhome.p-e.kr
|
|
||||||
RD_PORT=16779
|
|
||||||
RD_URL=redis://bkdhome.p-e.kr:16779
|
|
||||||
|
|
||||||
# Express 서버 포트
|
|
||||||
PORT=3000
|
|
||||||
|
|
||||||
# Gmail SMTP 설정
|
|
||||||
GMAIL_USER=bkd.scheduler@gmail.com
|
|
||||||
GMAIL_PASS= # 앱 비밀번호 또는 OAuth2 토큰
|
|
||||||
GMAIL_CLIENT_ID=688417162908-iqvnj4ceb8t1dkbjr70dtcafo27m8kqe.apps.googleusercontent.com
|
|
||||||
GMAIL_CLIENT_SECRET=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
|
|
||||||
GMAIL_REFRESH_TOKEN=1//04_pSivNoGpPUCgYIARAAGAQSNwF-L9IrO0Kx6jSzq_eQNjdl65f0O2iqKSNpFeZ3gtIGMhOk0oiZsnKrPfWs8jvuEic1NhUoZ0g
|
|
||||||
|
|
||||||
# SMTP 추가 옵션
|
|
||||||
SMTP_AUTH=true
|
|
||||||
SMTP_STARTTLS_ENABLE=true
|
|
||||||
SMTP_STARTTLS_REQUIRED=true
|
|
||||||
SMTP_AUTH_MECHANISMS=XOAUTH2
|
|
||||||
14
.env.common
Normal file
14
.env.common
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
# Gmail SMTP 설정
|
||||||
|
GMAIL_USER=bkd.scheduler@gmail.com
|
||||||
|
GMAIL_PASS= # 앱 비밀번호 또는 OAuth2 토큰
|
||||||
|
GMAIL_CLIENT_ID=688417162908-iqvnj4ceb8t1dkbjr70dtcafo27m8kqe.apps.googleusercontent.com
|
||||||
|
GMAIL_CLIENT_SECRET=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
|
||||||
|
GMAIL_REFRESH_TOKEN=1//04P8ekVQmkdtnCgYIARAAGAQSNwF-L9IrqPOyH8oYB-mdjUqw9jGHienVLBTWFdiZgpRnPgFmYnAdbjnstd9RkRVeJErB0NRAwg4
|
||||||
|
|
||||||
|
# SMTP 추가 옵션
|
||||||
|
SMTP_AUTH=true
|
||||||
|
SMTP_STARTTLS_ENABLE=true
|
||||||
|
SMTP_STARTTLS_REQUIRED=true
|
||||||
|
SMTP_AUTH_MECHANISMS=XOAUTH2
|
||||||
|
|
||||||
|
JWT_SECRET=96612b08364bbd9f275f29f86d39c18225e3cb3f31551434d5a84a88f5b01e627b5aafac902e0769bda4f1574b2f84ffb26e659b1a672182015a180c086cb911
|
||||||
14
.env.dev
Normal file
14
.env.dev
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
PORT=8088
|
||||||
|
|
||||||
|
# PostgreSQL 설정
|
||||||
|
PGHOST=bkdhome.p-e.kr
|
||||||
|
PGPORT=15454
|
||||||
|
PGDATABASE=scheduler
|
||||||
|
PGUSER=baekyangdan
|
||||||
|
PGPASSWORD=qwas745478!
|
||||||
|
PG_DATABASE_URL=postgres://baekyangdan:qwas745478!@bkdhome.p-e.kr:15454/scheduler
|
||||||
|
|
||||||
|
# Redis 설정
|
||||||
|
RD_HOST=bkdhome.p-e.kr
|
||||||
|
RD_PORT=16779
|
||||||
|
RD_URL=redis://bkdhome.p-e.kr:16779
|
||||||
12
.env.local
Normal file
12
.env.local
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
HOST=0.0.0.0
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# PostgreSQL 설정
|
||||||
|
PGUSER=baekyangdan
|
||||||
|
PGPASSWORD=qwas745478!
|
||||||
|
PG_DATABASE_URL=postgres://192.168.219.103:5454/scheduler
|
||||||
|
|
||||||
|
# Redis 설정
|
||||||
|
RD_HOST=192.168.219.103
|
||||||
|
RD_PORT=6779
|
||||||
|
RD_URL=redis://192.168.219.103:6779
|
||||||
14
.env.prod
Normal file
14
.env.prod
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# PostgreSQL 설정
|
||||||
|
PGHOST=db
|
||||||
|
PGPORT=5454
|
||||||
|
PGDATABASE=scheduler
|
||||||
|
PGUSER=baekyangdan
|
||||||
|
PGPASSWORD=qwas745478!
|
||||||
|
PG_DATABASE_URL=postgres://baekyangdan:qwas745478!@db:5454/scheduler
|
||||||
|
|
||||||
|
# Redis 설정
|
||||||
|
RD_HOST=redis
|
||||||
|
RD_PORT=6779
|
||||||
|
RD_URL=redis://redis:6779
|
||||||
65
.gitea/workflows/gitea-ci.yml
Normal file
65
.gitea/workflows/gitea-ci.yml
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
name: Test CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: rpi5
|
||||||
|
|
||||||
|
env:
|
||||||
|
DOCKER_VOLUME: ${{ vars.DOCKER_VOLUME }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Check PWD
|
||||||
|
run: |
|
||||||
|
echo "Docker volume: $DOCKER_VOLUME"
|
||||||
|
echo "PWD: $PWD"
|
||||||
|
ls -lRa ./.yarn
|
||||||
|
|
||||||
|
- name: Validate Node and Yarn Environment
|
||||||
|
run: |
|
||||||
|
if ! command -v node &> /dev/null
|
||||||
|
then
|
||||||
|
echo "Error: Node.js not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Node.js version: $(node -v)"
|
||||||
|
|
||||||
|
if ! command -v yarn &> /dev/null
|
||||||
|
then
|
||||||
|
echo "Error: Yarn.js not found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "yarn version: $(yarn -v)"
|
||||||
|
|
||||||
|
- name: Restore Yarn cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
.yarn/cache
|
||||||
|
.yarn/unplugged
|
||||||
|
.yarn/install-state.gz
|
||||||
|
.pnp.cjs
|
||||||
|
key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock','package.json') }}
|
||||||
|
|
||||||
|
- name: Install Dependencies with yarn
|
||||||
|
run: |
|
||||||
|
yarn install --immutable
|
||||||
|
ls .
|
||||||
|
|
||||||
|
- name: Build Nestjs project
|
||||||
|
run: |
|
||||||
|
yarn build
|
||||||
|
ls .
|
||||||
|
|
||||||
|
- name: Deploy dist
|
||||||
|
run: |
|
||||||
|
cp -r dist $DOCKER_VOLUME/scheduler/back/
|
||||||
|
cp -r node_modules $DOCKER_VOLUME/scheduler/back/
|
||||||
|
ls $DOCKER_VOLUME/scheduler/back
|
||||||
|
docker exec -it scheduler_back pm2 reload scheduler-back
|
||||||
13
.gitignore
vendored
13
.gitignore
vendored
@@ -3,11 +3,18 @@ node_modules/
|
|||||||
npm-debug.log*
|
npm-debug.log*
|
||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
package-lock.json
|
package-lock.json
|
||||||
yarn.lock
|
# yarn.lock
|
||||||
|
|
||||||
|
# Yarn Berry
|
||||||
|
.yarn/*
|
||||||
|
!.yarn/patches
|
||||||
|
!.yarn/plugins
|
||||||
|
!.yarn/releases
|
||||||
|
!.yarn/sdks
|
||||||
|
!.yarn/versions
|
||||||
.pnp.*
|
.pnp.*
|
||||||
.pnp.loader.mjs
|
# .pnp.loader.mjs
|
||||||
.yarn/install-state.gz
|
# .yarn/install-state.gz
|
||||||
|
|
||||||
# TypeScript
|
# TypeScript
|
||||||
dist/
|
dist/
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
# # This file is a template, and might need editing before it works on your project.
|
|
||||||
# # This is a sample GitLab CI/CD configuration file that should run without any modifications.
|
|
||||||
# # It demonstrates a basic 3 stage CI/CD pipeline. Instead of real tests or scripts,
|
|
||||||
# # it uses echo commands to simulate the pipeline execution.
|
|
||||||
# #
|
|
||||||
# # A pipeline is composed of independent jobs that run scripts, grouped into stages.
|
|
||||||
# # Stages run in sequential order, but jobs within stages run in parallel.
|
|
||||||
# #
|
|
||||||
# # For more information, see: https://docs.gitlab.com/ee/ci/yaml/#stages
|
|
||||||
# #
|
|
||||||
# # You can copy and paste this template into a new `.gitlab-ci.yml` file.
|
|
||||||
# # You should not add this template to an existing `.gitlab-ci.yml` file by using the `include:` keyword.
|
|
||||||
# #
|
|
||||||
# # To contribute improvements to CI/CD templates, please follow the Development guide at:
|
|
||||||
# # https://docs.gitlab.com/development/cicd/templates/
|
|
||||||
# # This specific template is located at:
|
|
||||||
# # https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Getting-Started.gitlab-ci.yml
|
|
||||||
|
|
||||||
# stages: # List of stages for jobs, and their order of execution
|
|
||||||
# - build
|
|
||||||
|
|
||||||
# cache:
|
|
||||||
# key:
|
|
||||||
# files:
|
|
||||||
# - package-lock.json
|
|
||||||
# paths:
|
|
||||||
# - node_modules/
|
|
||||||
|
|
||||||
# build: # This job runs in the build stage, which runs first.
|
|
||||||
# stage: build
|
|
||||||
# tags:
|
|
||||||
# - local-runner
|
|
||||||
# before_script:
|
|
||||||
# script:
|
|
||||||
# - echo "Compiling the code..."
|
|
||||||
# - echo $DOCKER_VOLUME
|
|
||||||
# - echo $DOCKER_COMPOSE_VOLUME
|
|
||||||
# - npm install
|
|
||||||
# - npm run build
|
|
||||||
# - sudo cp -r $PWD/dist/. $DOCKER_VOLUME/scheduler/back/dist
|
|
||||||
# - sudo cp $PWD/package.json $DOCKER_VOLUME/scheduler/back/dist
|
|
||||||
# - docker compose -f $DOCKER_COMPOSE_VOLUME/scheduler/docker-compose.yaml up -d back
|
|
||||||
# - echo "Compile complete."
|
|
||||||
942
.yarn/releases/yarn-4.11.0.cjs
vendored
Normal file
942
.yarn/releases/yarn-4.11.0.cjs
vendored
Normal file
File diff suppressed because one or more lines are too long
2
.yarnrc.yml
Normal file
2
.yarnrc.yml
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
yarnPath: .yarn/releases/yarn-4.11.0.cjs
|
||||||
|
nodeLinker: node-modules
|
||||||
@@ -54,7 +54,7 @@ export const account = pgTable("account", {
|
|||||||
birthday: date(),
|
birthday: date(),
|
||||||
accountId: varchar("account_id").notNull(),
|
accountId: varchar("account_id").notNull(),
|
||||||
nickname: varchar().notNull(),
|
nickname: varchar().notNull(),
|
||||||
status: varchar().default('wait').notNull(),
|
status: varchar().default('active').notNull(),
|
||||||
isDeleted: boolean("is_deleted").default(false).notNull(),
|
isDeleted: boolean("is_deleted").default(false).notNull(),
|
||||||
createdAt: date("created_at").defaultNow().notNull(),
|
createdAt: date("created_at").defaultNow().notNull(),
|
||||||
id: uuid().default(sql`uuid_generate_v4()`).primaryKey().notNull(),
|
id: uuid().default(sql`uuid_generate_v4()`).primaryKey().notNull(),
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://json.schemastore.org/nest-cli",
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
"collection": "@nestjs/schematics",
|
"collection": "@nestjs/schematics",
|
||||||
"sourceRoot": "src",
|
"sourceRoot": "src"
|
||||||
"compilerOptions": {
|
|
||||||
"deleteOutDir": true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
28
package.json
28
package.json
@@ -6,12 +6,15 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"license": "UNLICENSED",
|
"license": "UNLICENSED",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "nest build",
|
"build": "cross-env NODE_ENV=prod nest build",
|
||||||
|
"build:local": "cross-env NODE_ENV=local nest build",
|
||||||
|
"build:dev": "cross-env NODE_ENV=dev nest build",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"start": "nest start",
|
"start": "nest start",
|
||||||
"start:dev": "nest start --watch",
|
"start:local": "cross-env NODE_ENV=local nest start --watch",
|
||||||
|
"start:dev": "cross-env NODE_ENV=dev nest start --watch",
|
||||||
"start:debug": "nest start --debug --watch",
|
"start:debug": "nest start --debug --watch",
|
||||||
"start:prod": "node dist/main",
|
"start:prod": "cross-env NODE_ENV=prod node dist/main",
|
||||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
"test": "jest",
|
"test": "jest",
|
||||||
"test:watch": "jest --watch",
|
"test:watch": "jest --watch",
|
||||||
@@ -23,12 +26,23 @@
|
|||||||
"@nestjs/class-transformer": "^0.4.0",
|
"@nestjs/class-transformer": "^0.4.0",
|
||||||
"@nestjs/class-validator": "^0.13.4",
|
"@nestjs/class-validator": "^0.13.4",
|
||||||
"@nestjs/common": "^11.0.1",
|
"@nestjs/common": "^11.0.1",
|
||||||
|
"@nestjs/config": "^4.0.2",
|
||||||
"@nestjs/core": "^11.0.1",
|
"@nestjs/core": "^11.0.1",
|
||||||
|
"@nestjs/jwt": "^11.0.1",
|
||||||
|
"@nestjs/passport": "^11.0.5",
|
||||||
"@nestjs/platform-express": "^11.0.1",
|
"@nestjs/platform-express": "^11.0.1",
|
||||||
|
"@nestjs/platform-fastify": "^11.1.9",
|
||||||
|
"bcrypt": "^6.0.0",
|
||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
"drizzle-kit": "^0.31.7",
|
"drizzle-kit": "^0.31.7",
|
||||||
"drizzle-orm": "^0.44.7",
|
"drizzle-orm": "^0.44.7",
|
||||||
|
"fastify": "^5.6.2",
|
||||||
|
"fastify-cors": "^6.1.0",
|
||||||
|
"googleapis": "^166.0.0",
|
||||||
"ioredis": "^5.8.2",
|
"ioredis": "^5.8.2",
|
||||||
|
"nodemailer": "^7.0.10",
|
||||||
|
"passport": "^0.7.0",
|
||||||
|
"passport-jwt": "^4.0.1",
|
||||||
"pg": "^8.16.3",
|
"pg": "^8.16.3",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1"
|
"rxjs": "^7.8.1"
|
||||||
@@ -39,12 +53,17 @@
|
|||||||
"@nestjs/cli": "^11.0.0",
|
"@nestjs/cli": "^11.0.0",
|
||||||
"@nestjs/schematics": "^11.0.0",
|
"@nestjs/schematics": "^11.0.0",
|
||||||
"@nestjs/testing": "^11.0.1",
|
"@nestjs/testing": "^11.0.1",
|
||||||
|
"@types/bcrypt": "^6",
|
||||||
"@types/express": "^5.0.0",
|
"@types/express": "^5.0.0",
|
||||||
"@types/ioredis": "^5.0.0",
|
"@types/ioredis": "^5.0.0",
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/node": "^22.10.7",
|
"@types/node": "^22.10.7",
|
||||||
|
"@types/nodemailer": "^7.0.4",
|
||||||
|
"@types/passport": "^0",
|
||||||
|
"@types/passport-jwt": "^4.0.1",
|
||||||
"@types/pg": "^8.15.6",
|
"@types/pg": "^8.15.6",
|
||||||
"@types/supertest": "^6.0.2",
|
"@types/supertest": "^6.0.2",
|
||||||
|
"cross-env": "^10.1.0",
|
||||||
"eslint": "^9.18.0",
|
"eslint": "^9.18.0",
|
||||||
"eslint-config-prettier": "^10.0.1",
|
"eslint-config-prettier": "^10.0.1",
|
||||||
"eslint-plugin-prettier": "^5.2.2",
|
"eslint-plugin-prettier": "^5.2.2",
|
||||||
@@ -76,5 +95,6 @@
|
|||||||
],
|
],
|
||||||
"coverageDirectory": "../coverage",
|
"coverageDirectory": "../coverage",
|
||||||
"testEnvironment": "node"
|
"testEnvironment": "node"
|
||||||
}
|
},
|
||||||
|
"packageManager": "yarn@4.11.0"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,12 @@ import { AppController } from './app.controller';
|
|||||||
import { AppService } from './app.service';
|
import { AppService } from './app.service';
|
||||||
import { DbModule } from './db/db.module';
|
import { DbModule } from './db/db.module';
|
||||||
import { RedisModule } from './redis/redis.module';
|
import { RedisModule } from './redis/redis.module';
|
||||||
|
import { AccountModule } from './modules/account/account.module';
|
||||||
|
import { MailerModule } from './util/mailer/mailer.module';
|
||||||
|
import { AppConfigModule } from './config/config.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [DbModule, RedisModule],
|
imports: [AppConfigModule, DbModule, RedisModule, MailerModule, AccountModule],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService],
|
providers: [AppService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -3,6 +3,6 @@ import { Injectable } from '@nestjs/common';
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class AppService {
|
export class AppService {
|
||||||
getHello(): string {
|
getHello(): string {
|
||||||
return 'Hello World!';
|
return 'Hello World!\nReload Test!';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
5
src/common/decorators/public.decorator.ts
Normal file
5
src/common/decorators/public.decorator.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { SetMetadata } from "@nestjs/common";
|
||||||
|
|
||||||
|
export const IS_PUBLIC_KEY = 'isPublic345827';
|
||||||
|
|
||||||
|
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||||
39
src/common/filters/all-exceptions.filter.ts
Normal file
39
src/common/filters/all-exceptions.filter.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import {
|
||||||
|
ExceptionFilter,
|
||||||
|
Catch,
|
||||||
|
ArgumentsHost,
|
||||||
|
HttpException,
|
||||||
|
HttpStatus
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||||
|
|
||||||
|
@Catch()
|
||||||
|
export class AllExceptionsFilter implements ExceptionFilter {
|
||||||
|
catch(exception: unknown, host: ArgumentsHost) {
|
||||||
|
const ctx = host.switchToHttp();
|
||||||
|
const response = ctx.getResponse<FastifyReply>();
|
||||||
|
const request = ctx.getRequest<FastifyRequest>();
|
||||||
|
|
||||||
|
let status =
|
||||||
|
exception instanceof HttpException
|
||||||
|
? exception.getStatus()
|
||||||
|
: HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
|
||||||
|
let message =
|
||||||
|
exception instanceof HttpException
|
||||||
|
? exception.getResponse()
|
||||||
|
: 'Internal server error';
|
||||||
|
|
||||||
|
if (typeof message === 'object' && (message as any).message) {
|
||||||
|
message = (message as any).message;
|
||||||
|
}
|
||||||
|
|
||||||
|
response.status(status).send({
|
||||||
|
success: false,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
path: request.url,
|
||||||
|
statusCode: status,
|
||||||
|
error: message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
16
src/config/config.module.ts
Normal file
16
src/config/config.module.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { Module } from "@nestjs/common";
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import dotenv from 'dotenv';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
envFilePath: [
|
||||||
|
`.env.${process.env.NODE_ENV}`,
|
||||||
|
'.env.common'
|
||||||
|
]
|
||||||
|
})
|
||||||
|
]
|
||||||
|
})
|
||||||
|
export class AppConfigModule{}
|
||||||
42
src/const/HttpResponse.ts
Normal file
42
src/const/HttpResponse.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
export const HttpResponse: Record<string, {code: number, title: string, message: string}> = {
|
||||||
|
"ACCESS_TOKEN_EXPIRED": {
|
||||||
|
code: 401,
|
||||||
|
title: "ACCESS_TOKEN_EXPIRED",
|
||||||
|
message: "ACCESS TOKEN EXPIRED"
|
||||||
|
},
|
||||||
|
"INVALID_TOKEN": {
|
||||||
|
code: 401,
|
||||||
|
title: "INVALID_TOKEN",
|
||||||
|
message: "INVALID TOKEN"
|
||||||
|
},
|
||||||
|
"REFRESH_TOKEN_EXPIRED": {
|
||||||
|
code: 401,
|
||||||
|
title: "REFRESH_TOKEN_EXPIRED",
|
||||||
|
message: "REFRESH TOKEN EXPIRED"
|
||||||
|
},
|
||||||
|
"UNAUTHORIZED": {
|
||||||
|
code: 401,
|
||||||
|
title: "UNAUTHORIZED",
|
||||||
|
message: "UNAUTHORIZED"
|
||||||
|
},
|
||||||
|
"OK": {
|
||||||
|
code: 200,
|
||||||
|
title: "OK",
|
||||||
|
message: "OK"
|
||||||
|
},
|
||||||
|
"CREATED": {
|
||||||
|
code: 201,
|
||||||
|
title: "CREATED",
|
||||||
|
message: "CREATED"
|
||||||
|
},
|
||||||
|
"BAD_REQUEST": {
|
||||||
|
code: 400,
|
||||||
|
title: "BAD_REQUEST",
|
||||||
|
message: "BAD REQUEST"
|
||||||
|
},
|
||||||
|
"INTERNAL_SERVER_ERROR": {
|
||||||
|
code: 500,
|
||||||
|
title: "INTERNAL_SERVER_ERROR",
|
||||||
|
message: "INTERNAL SERVER ERROR"
|
||||||
|
}
|
||||||
|
} as const;
|
||||||
@@ -1,22 +1,36 @@
|
|||||||
import { Global, Module } from "@nestjs/common";
|
import { Global, Inject, Module, OnApplicationShutdown } from "@nestjs/common";
|
||||||
import { Pool } from "pg";
|
import { Pool } from "pg";
|
||||||
import { drizzle, NodePgDatabase } from "drizzle-orm/node-postgres";
|
import { drizzle, NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||||
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||||
import * as schema from '../../drizzle/schema';
|
import * as schema from '../../drizzle/schema';
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
|
imports: [ConfigModule],
|
||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
provide: "DRIZZLE",
|
provide: "DB_POOL",
|
||||||
useFactory: (): NodePgDatabase<typeof schema> => {
|
useFactory: (configService: ConfigService) => {
|
||||||
const pool = new Pool({
|
return new Pool({
|
||||||
connectionString: process.env.PG_DATABASE_URL
|
connectionString: configService.get<string>('PG_DATABASE_URL')
|
||||||
});
|
});
|
||||||
|
},
|
||||||
|
inject: [ConfigService]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: "DRIZZLE",
|
||||||
|
useFactory: (pool: Pool): NodePgDatabase<typeof schema> => {
|
||||||
return drizzle(pool, { schema: schema });
|
return drizzle(pool, { schema: schema });
|
||||||
}
|
},
|
||||||
|
inject: ["DB_POOL"]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
exports: ["DRIZZLE"]
|
exports: ["DRIZZLE"]
|
||||||
})
|
})
|
||||||
export class DbModule {}
|
export class DbModule implements OnApplicationShutdown {
|
||||||
|
constructor(@Inject('DB_POOL') private readonly pool: Pool) {}
|
||||||
|
|
||||||
|
async onApplicationShutdown(signal?: string) {
|
||||||
|
await this.pool.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
32
src/main.ts
32
src/main.ts
@@ -1,8 +1,36 @@
|
|||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
|
import {
|
||||||
|
FastifyAdapter,
|
||||||
|
NestFastifyApplication
|
||||||
|
} from '@nestjs/platform-fastify';
|
||||||
|
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create<NestFastifyApplication>(
|
||||||
await app.listen(process.env.PORT ?? 3000);
|
AppModule,
|
||||||
|
new FastifyAdapter()
|
||||||
|
);
|
||||||
|
app.enableCors({
|
||||||
|
origin: (origin, callback) => {
|
||||||
|
// origin이 없는 경우(local file, curl 등) 허용
|
||||||
|
if (!origin) return callback(null, true);
|
||||||
|
|
||||||
|
// 특정 도메인만 막고 싶은 경우 whitelist 가능
|
||||||
|
const whitelist = ["http://localhost:5173", "http://192.168.219.105:5185", "https://scheduler.bkdhome.p-e.kr"];
|
||||||
|
if (whitelist.includes(origin)) {
|
||||||
|
return callback(null, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 그 외 모든 도메인 허용 → 사실상 wildcard
|
||||||
|
return callback(null, true);
|
||||||
|
},
|
||||||
|
credentials: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
app.enableShutdownHooks();
|
||||||
|
app.useGlobalFilters(new AllExceptionsFilter());
|
||||||
|
await app.listen(process.env.PORT ?? 3000, '0.0.0.0', () => { process.env.NODE_ENV !== 'prod' && console.log(`servier is running on ${process.env.PORT}`) });
|
||||||
|
|
||||||
}
|
}
|
||||||
bootstrap();
|
bootstrap();
|
||||||
|
|||||||
24
src/middleware/auth/auth.module.ts
Normal file
24
src/middleware/auth/auth.module.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { forwardRef, Module } from '@nestjs/common';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { AccountModule } from 'src/modules/account/account.module';
|
||||||
|
import { JwtAccessStrategy } from './strategy/access-token.strategy';
|
||||||
|
import { JwtRefreshStrategy } from './strategy/refresh-token.strategy';
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule,
|
||||||
|
JwtModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: (config: ConfigService) => ({
|
||||||
|
secret: config.get<string>('JWT_SECRET')!,
|
||||||
|
signOptions: { expiresIn: '1h' }
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
forwardRef(() => AccountModule)
|
||||||
|
],
|
||||||
|
providers: [AuthService, JwtAccessStrategy, JwtRefreshStrategy],
|
||||||
|
exports: [AuthService]
|
||||||
|
})
|
||||||
|
export class AuthModule{}
|
||||||
23
src/middleware/auth/auth.service.ts
Normal file
23
src/middleware/auth/auth.service.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthService {
|
||||||
|
constructor(private readonly jwtService: JwtService) {}
|
||||||
|
|
||||||
|
generateTokens(payload: any) {
|
||||||
|
const accessToken = this.jwtService.sign(payload, { expiresIn: '5s' });
|
||||||
|
const refreshToken = this.jwtService.sign({id: payload.id}, { expiresIn: '7d' });
|
||||||
|
|
||||||
|
return { accessToken, refreshToken };
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshTokens(refreshToken: string) {
|
||||||
|
try {
|
||||||
|
const payload = this.jwtService.verify(refreshToken);
|
||||||
|
return this.generateTokens(payload);
|
||||||
|
} catch (e) {
|
||||||
|
throw new UnauthorizedException('Invalid Refresh Token');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
45
src/middleware/auth/guard/access-token.guard.ts
Normal file
45
src/middleware/auth/guard/access-token.guard.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
|
||||||
|
import { Reflector } from "@nestjs/core";
|
||||||
|
import { TokenExpiredError } from "@nestjs/jwt";
|
||||||
|
import { AuthGuard } from "@nestjs/passport";
|
||||||
|
import { IS_PUBLIC_KEY } from "src/common/decorators/public.decorator";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtAccessAuthGuard extends AuthGuard('access-token') {
|
||||||
|
constructor(private reflector: Reflector) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
canActivate(context: ExecutionContext) {
|
||||||
|
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||||
|
context.getHandler(),
|
||||||
|
context.getClass()
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (isPublic) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return super.canActivate(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleRequest(err: any, user:any, info:any) {
|
||||||
|
if (info instanceof TokenExpiredError) {
|
||||||
|
throw new UnauthorizedException({
|
||||||
|
statusCode: 401,
|
||||||
|
message: 'Access Token Expired',
|
||||||
|
code: 'AccessTokenExpired'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err || !user) {
|
||||||
|
throw new UnauthorizedException({
|
||||||
|
statusCode: 401,
|
||||||
|
message: 'Invalid Token',
|
||||||
|
code: 'InvalidToken'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
}
|
||||||
45
src/middleware/auth/guard/refresh-token.guard.ts
Normal file
45
src/middleware/auth/guard/refresh-token.guard.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
|
||||||
|
import { Reflector } from "@nestjs/core";
|
||||||
|
import { TokenExpiredError } from "@nestjs/jwt";
|
||||||
|
import { AuthGuard } from "@nestjs/passport";
|
||||||
|
import { IS_PUBLIC_KEY } from "src/common/decorators/public.decorator";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtRefreshAuthGuard extends AuthGuard('refresh-token') {
|
||||||
|
constructor(private reflector: Reflector) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
canActivate(context: ExecutionContext) {
|
||||||
|
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||||
|
context.getHandler(),
|
||||||
|
context.getClass()
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (isPublic) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return super.canActivate(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleRequest(err: any, user:any, info:any) {
|
||||||
|
if (info instanceof TokenExpiredError) {
|
||||||
|
throw new UnauthorizedException({
|
||||||
|
statusCode: 401,
|
||||||
|
message: 'Refresh Token Expired',
|
||||||
|
code: 'RefreshTokenExpired'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err || !user) {
|
||||||
|
throw new UnauthorizedException({
|
||||||
|
statusCode: 401,
|
||||||
|
message: 'Invalid Token',
|
||||||
|
code: 'InvalidToken'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
}
|
||||||
22
src/middleware/auth/strategy/access-token.strategy.ts
Normal file
22
src/middleware/auth/strategy/access-token.strategy.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||||
|
import { ConfigService } from "@nestjs/config";
|
||||||
|
import { PassportStrategy } from "@nestjs/passport";
|
||||||
|
import { ExtractJwt, Strategy } from "passport-jwt";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtAccessStrategy extends PassportStrategy(Strategy, "access-token") {
|
||||||
|
constructor(configService: ConfigService) {
|
||||||
|
super({
|
||||||
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||||
|
secretOrKey: configService.get<string>('JWT_SECRET')!
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async validate(payload: any) {
|
||||||
|
const token = ExtractJwt.fromAuthHeaderAsBearerToken();
|
||||||
|
if (!token) {
|
||||||
|
throw new UnauthorizedException();
|
||||||
|
}
|
||||||
|
return { id: payload.id };
|
||||||
|
}
|
||||||
|
}
|
||||||
26
src/middleware/auth/strategy/refresh-token.strategy.ts
Normal file
26
src/middleware/auth/strategy/refresh-token.strategy.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { PassportStrategy } from '@nestjs/passport';
|
||||||
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'refresh-token') {
|
||||||
|
constructor(configService: ConfigService) {
|
||||||
|
super({
|
||||||
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||||
|
secretOrKey: configService.get<string>('JWT_SECRET')!,
|
||||||
|
passReqToCallback: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async validate(payload: any) {
|
||||||
|
const token = ExtractJwt.fromAuthHeaderAsBearerToken();
|
||||||
|
|
||||||
|
if (!token) throw new UnauthorizedException('Invalid Refresh Token');
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: payload.id,
|
||||||
|
token
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,82 @@
|
|||||||
import { Controller, Get, Post, Query } from "@nestjs/common";
|
import { Body, Controller, Get, Headers, Post, Query, Req, UseGuards } from "@nestjs/common";
|
||||||
import { CheckDuplicationRequestDto } from "./dto/checkDuplication/check-duplication-request.dto";
|
|
||||||
import { CheckDuplicationResponseDto } from "./dto/checkDuplication/check-duplication-response.dto";
|
|
||||||
import { AccountService } from "./account.service";
|
import { AccountService } from "./account.service";
|
||||||
|
import * as DTO from "./dto";
|
||||||
|
import { JwtAccessAuthGuard } from "src/middleware/auth/guard/access-token.guard";
|
||||||
|
import { Public } from "src/common/decorators/public.decorator";
|
||||||
|
import { JwtRefreshAuthGuard } from "src/middleware/auth/guard/refresh-token.guard";
|
||||||
|
|
||||||
|
@UseGuards(JwtAccessAuthGuard)
|
||||||
@Controller('account')
|
@Controller('account')
|
||||||
export class AccountController {
|
export class AccountController {
|
||||||
constructor(private readonly accountService: AccountService) {}
|
constructor(private readonly accountService: AccountService) {}
|
||||||
|
|
||||||
|
@Get('/')
|
||||||
|
async test() {
|
||||||
|
return "Test"
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
@Get('check-duplication')
|
@Get('check-duplication')
|
||||||
async checkDuplication(@Query() query: CheckDuplicationRequestDto): Promise<CheckDuplicationResponseDto> {
|
async checkDuplication(@Query() query: DTO.CheckDuplicationRequest): Promise<DTO.CheckDuplicationResponse> {
|
||||||
return this.accountService.checkDuplication(query);
|
return await this.accountService.checkDuplication(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('send-email-verification-code')
|
||||||
|
async sendEmailVerificationCode(@Body() body: DTO.SendEmailVerificationCodeRequest): Promise<DTO.SendEmailVerificationCodeResponse> {
|
||||||
|
const result = await this.accountService.sendVerificationCode(body);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('verify-email-verification-code')
|
||||||
|
async verifyCode(@Body() body: DTO.VerifyEmailVerificationCodeRequest): Promise<DTO.VerifyEmailVerificationCodeResponse> {
|
||||||
|
const result = await this.accountService.verifyCode(body);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('send-reset-password-code')
|
||||||
|
async sendResetPasswordCode(@Body() body: DTO.SendResetPasswordCodeRequest): Promise<DTO.SendResetPasswordCodeResponse> {
|
||||||
|
const result = await this.accountService.sendResetPasswordCode(body);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('verify-reset-password-code')
|
||||||
|
async verifyResetPasswordCode(@Body() body: DTO.VerifyResetPasswordCodeRequest): Promise<DTO.VerifyResetPasswordCodeResponse> {
|
||||||
|
const result = await this.accountService.verifyResetPasswordCode(body);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('reset-password')
|
||||||
|
async resetPassword(@Body() body: DTO.ResetPasswordRequest): Promise<DTO.ResetPasswordResponse> {
|
||||||
|
const result = await this.accountService.resetPassword(body);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('signup')
|
||||||
|
async signup(@Body() body: DTO.SignupRequest): Promise<DTO.SignupResponse> {
|
||||||
|
const result = await this.accountService.signup(body);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post('login')
|
||||||
|
async login(@Body() body: DTO.LoginRequest): Promise<DTO.LoginResponse> {
|
||||||
|
console.log('a');
|
||||||
|
const result = await this.accountService.login(body);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@UseGuards(JwtRefreshAuthGuard)
|
||||||
|
@Get('refresh-access-token')
|
||||||
|
async refreshAccessToken(@Req() req): Promise<DTO.RefreshAccessTokenResponse> {
|
||||||
|
const id = req.user.id;
|
||||||
|
const newAccessToken = this.accountService.refreshAccessToken(id);
|
||||||
|
return newAccessToken;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { forwardRef, Module } from "@nestjs/common";
|
||||||
import { AccountController } from "./account.controller";
|
import { AccountController } from "./account.controller";
|
||||||
import { AccountRepo } from "./account.repo";
|
import { AccountRepo } from "./account.repo";
|
||||||
import { AccountService } from "./account.service";
|
import { AccountService } from "./account.service";
|
||||||
|
import { AuthModule } from 'src/middleware/auth/auth.module';
|
||||||
@Module({
|
@Module({
|
||||||
|
imports: [forwardRef(() => AuthModule)],
|
||||||
controllers: [AccountController],
|
controllers: [AccountController],
|
||||||
providers: [AccountService, AccountRepo]
|
providers: [AccountService, AccountRepo],
|
||||||
|
exports: [AccountService, AccountRepo]
|
||||||
})
|
})
|
||||||
export class AccountModule {}
|
export class AccountModule {}
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
import { Inject, Injectable } from "@nestjs/common";
|
import { Inject, Injectable } from "@nestjs/common";
|
||||||
import * as schema from "drizzle/schema";
|
import * as schema from "drizzle/schema";
|
||||||
import { countDistinct, and, eq } from 'drizzle-orm';
|
import { countDistinct, and, eq, not } from 'drizzle-orm';
|
||||||
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AccountRepo {
|
export class AccountRepo {
|
||||||
constructor(@Inject('DRIZZLE') private readonly db: NodePgDatabase<typeof schema>) {}
|
constructor(@Inject('DRIZZLE') private readonly db: NodePgDatabase<typeof schema>) {}
|
||||||
|
|
||||||
async checkDuplication(type: 'email' | 'accountId', value: string) {
|
async checkIdExists(type: 'email' | 'accountId', value: string) {
|
||||||
const result = await this
|
const result = await this
|
||||||
.db
|
.db
|
||||||
.select({ count: countDistinct(schema.account[type])})
|
.select({ count: countDistinct(schema.account[type])})
|
||||||
@@ -18,4 +18,68 @@ export class AccountRepo {
|
|||||||
|
|
||||||
return result[0].count;
|
return result[0].count;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async signup(
|
||||||
|
accountId: string,
|
||||||
|
name: string,
|
||||||
|
nickname: string,
|
||||||
|
email: string,
|
||||||
|
password: string
|
||||||
|
) {
|
||||||
|
return this
|
||||||
|
.db
|
||||||
|
.insert(schema.account)
|
||||||
|
.values({
|
||||||
|
accountId: accountId,
|
||||||
|
name: name,
|
||||||
|
nickname: nickname,
|
||||||
|
email: email,
|
||||||
|
password: password
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async login(
|
||||||
|
type: 'email' | 'accountId'
|
||||||
|
, id: string
|
||||||
|
) {
|
||||||
|
return this
|
||||||
|
.db
|
||||||
|
.select()
|
||||||
|
.from(schema.account)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(schema.account[type], id),
|
||||||
|
eq(schema.account.isDeleted, false),
|
||||||
|
eq(schema.account.status, 'active')
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findById(id: string) {
|
||||||
|
return await this
|
||||||
|
.db
|
||||||
|
.select()
|
||||||
|
.from(schema.account)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(schema.account.id, id),
|
||||||
|
eq(schema.account.isDeleted, false)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePassword(type: 'email' | 'accountId', id: string, value: string) {
|
||||||
|
return await this
|
||||||
|
.db
|
||||||
|
.update(schema.account)
|
||||||
|
.set({
|
||||||
|
password: value
|
||||||
|
})
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(schema.account[type], id),
|
||||||
|
eq(schema.account.isDeleted, false)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,204 @@
|
|||||||
import { Injectable } from "@nestjs/common";
|
import { Inject, Injectable } from "@nestjs/common";
|
||||||
import { AccountRepo } from "./account.repo";
|
import { AccountRepo } from "./account.repo";
|
||||||
import { CheckDuplicationRequestDto } from "./dto/checkDuplication/check-duplication-request.dto";
|
import * as DTO from './dto';
|
||||||
import { CheckDuplicationResponseDto } from "./dto/checkDuplication/check-duplication-response.dto";
|
import { MailerService } from "src/util/mailer/mailer.service";
|
||||||
|
import { Generator } from "src/util/generator";
|
||||||
|
import Redis from "ioredis";
|
||||||
|
import { Converter } from "src/util/converter";
|
||||||
|
import { AuthService } from "src/middleware/auth/auth.service";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AccountService {
|
export class AccountService {
|
||||||
constructor(private readonly accountRepo: AccountRepo) {}
|
constructor(
|
||||||
|
private readonly accountRepo: AccountRepo
|
||||||
|
, private readonly mailerService: MailerService
|
||||||
|
, private readonly authService: AuthService
|
||||||
|
, @Inject("REDIS") private readonly redis: Redis
|
||||||
|
) {}
|
||||||
|
|
||||||
async checkDuplication(data: CheckDuplicationRequestDto): Promise<CheckDuplicationResponseDto> {
|
async checkDuplication(data: DTO.CheckDuplicationRequest): Promise<DTO.CheckDuplicationResponse> {
|
||||||
const count = await this.accountRepo.checkDuplication(data.type, data.value);
|
const { type, value } = data;
|
||||||
|
const count = await this.accountRepo.checkIdExists(type, value);
|
||||||
|
|
||||||
return { isDuplicated: count > 0 };
|
return { isDuplicated: count > 0, success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendVerificationCode(data: DTO.SendEmailVerificationCodeRequest): Promise<DTO.SendEmailVerificationCodeResponse> {
|
||||||
|
const { email } = data;
|
||||||
|
const code = Generator.getVerificationCode();
|
||||||
|
const html = `<p>Your verification code is: <strong style="font-size:16px;">${code}</strong></p>`;
|
||||||
|
const result = await this.mailerService.sendMail(email, "<Scheduler> 이메일 인증 코드", html);
|
||||||
|
|
||||||
|
if (result.rejected.length > 0) {
|
||||||
|
return { success: false, error: result.response }
|
||||||
|
} else {
|
||||||
|
await this.redis.set(`verify:${email}`, code, 'EX', 600);
|
||||||
|
|
||||||
|
return { success: true, message: "이메일 발송 완료" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyCode(data: DTO.VerifyEmailVerificationCodeRequest): Promise<DTO.VerifyEmailVerificationCodeResponse> {
|
||||||
|
const { email, code } = data;
|
||||||
|
|
||||||
|
const storedCode = await this.redis.get(`verify:${email}`);
|
||||||
|
|
||||||
|
if (!storedCode) {
|
||||||
|
return { verified: false, success: true, error: '잘못된 이메일이거나 코드가 만료되었습니다.'};
|
||||||
|
}
|
||||||
|
if (storedCode !== code) {
|
||||||
|
return { verified: false, success: true, error: "잘못된 코드입니다." };
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.redis.del(`verify:${email}`);
|
||||||
|
return { verified: true, success: true, message: "이메일 인증이 완료되었습니다." };
|
||||||
|
}
|
||||||
|
|
||||||
|
async signup(data: DTO.SignupRequest): Promise<DTO.SignupResponse> {
|
||||||
|
const { accountId, name, nickname, email, password } = data;
|
||||||
|
const hashedPassword = Converter.getHashedPassword(password);
|
||||||
|
const result = await this.accountRepo.signup(accountId, name, nickname, email, hashedPassword);
|
||||||
|
|
||||||
|
if (result.rowCount) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "회원가입이 완료되었습니다."
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "회원가입에 실패하였습니다."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
async login(data: DTO.LoginRequest): Promise<DTO.LoginResponse> {
|
||||||
|
const { type, id, password } = data;
|
||||||
|
const queryResult = await this.accountRepo.login(type, id);
|
||||||
|
const typeValue = type === 'email' ? '이메일' : '아이디';
|
||||||
|
|
||||||
|
if (!queryResult || (queryResult.length < 1)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: `존재하지 않는 ${typeValue} 입니다.`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const hashedPassword = queryResult[0].password;
|
||||||
|
const isPasswordMatch = Converter.comparePassword(password, hashedPassword);
|
||||||
|
if (!isPasswordMatch) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: `비밀번호가 맞지 않습니다.`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
const { id, accountId, status, isDeleted, birthday } = queryResult[0];
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
id, accountId, status, isDeleted, birthday
|
||||||
|
};
|
||||||
|
|
||||||
|
const { accessToken, refreshToken } = this.authService.generateTokens(payload);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
accessToken: accessToken,
|
||||||
|
refreshToken: refreshToken
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async refreshAccessToken(id: string): Promise<DTO.RefreshAccessTokenResponse> {
|
||||||
|
const { accessToken, refreshToken } = this.authService.refreshTokens(id);
|
||||||
|
return {
|
||||||
|
accessToken: accessToken,
|
||||||
|
refreshToken: refreshToken,
|
||||||
|
success: true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendResetPasswordCode(data: DTO.SendResetPasswordCodeRequest): Promise<DTO.SendResetPasswordCodeResponse> {
|
||||||
|
const { email } = data;
|
||||||
|
|
||||||
|
const count = await this.accountRepo.checkIdExists('email', email);
|
||||||
|
|
||||||
|
if (count === 0) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "찾을 수 없는 사용자"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const code = Generator.getResetPasswordCode();
|
||||||
|
|
||||||
|
const html =
|
||||||
|
`<p>Your Password Reset Code is: <strong>${code}</strong></p>`
|
||||||
|
+ `<p>Please Enter this code in 5 minutes.</p>`;
|
||||||
|
const result = await this.mailerService.sendMail(email, "<Scheduler> 비밀번호 초기화 코드", html);
|
||||||
|
|
||||||
|
if (result.rejected.length > 0) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: result.response
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.redis.set(`resetPassword:${email}`, code, 'EX', 300);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "비밀번호 초기화 코드 발송 완료"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyResetPasswordCode(data: DTO.VerifyResetPasswordCodeRequest): Promise<DTO.VerifyResetPasswordCodeResponse> {
|
||||||
|
const { email, code } = data;
|
||||||
|
|
||||||
|
const storedCode = await this.redis.get(`resetPassword:${email}`);
|
||||||
|
|
||||||
|
if (!storedCode) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
verified: false,
|
||||||
|
error: "잘못된 이메일이거나 코드가 만료되었습니다."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (storedCode !== code) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
verified: false,
|
||||||
|
error: "잘못된 코드입니다."
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.redis.del(`resetPassword:${email}`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
verified: true,
|
||||||
|
message: "비밀번호 초기화 코드 인증 완료"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async resetPassword(data: DTO.ResetPasswordRequest): Promise<DTO.ResetPasswordResponse> {
|
||||||
|
const { email, password } = data;
|
||||||
|
const hashedPassword = Converter.getHashedPassword(password);
|
||||||
|
const result = await this.accountRepo.updatePassword('email', email, hashedPassword);
|
||||||
|
|
||||||
|
if (!result.rowCount || result.rowCount === 0) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "비밀번호 초기화 실패"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "비밀번호 초기화 성공"
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
5
src/modules/account/dto/base-response.dto.ts
Normal file
5
src/modules/account/dto/base-response.dto.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
export class BaseResponseDto {
|
||||||
|
success: boolean;
|
||||||
|
message?: string;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
export class CheckDuplicationResponseDto {
|
import { BaseResponseDto } from "../base-response.dto";
|
||||||
|
|
||||||
|
export class CheckDuplicationResponseDto extends BaseResponseDto {
|
||||||
isDuplicated: boolean;
|
isDuplicated: boolean;
|
||||||
}
|
}
|
||||||
27
src/modules/account/dto/index.ts
Normal file
27
src/modules/account/dto/index.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { ResetPasswordRequestDto } from './resetPassword/reset-password-request.dto';
|
||||||
|
|
||||||
|
export { CheckDuplicationRequestDto as CheckDuplicationRequest } from './checkDuplication/check-duplication-request.dto';
|
||||||
|
export { CheckDuplicationResponseDto as CheckDuplicationResponse } from './checkDuplication/check-duplication-response.dto';
|
||||||
|
|
||||||
|
export { SendEmailVerificationCodeRequestDto as SendEmailVerificationCodeRequest } from './sendEmailVerificationCode/send-email-verification-code-request.dto';
|
||||||
|
export { SendEmailVerificationCodeResponseDto as SendEmailVerificationCodeResponse } from './sendEmailVerificationCode/send-email-verification-code-response.dto';
|
||||||
|
|
||||||
|
export { VerifyEmailVerificationCodeRequestDto as VerifyEmailVerificationCodeRequest } from './verifyEmailVerificationCode/verify-email-verification-code-request.dto';
|
||||||
|
export { VerifyEmailVerificationCodeResponseDto as VerifyEmailVerificationCodeResponse } from './verifyEmailVerificationCode/verify-email-verification-code-response.dto';
|
||||||
|
|
||||||
|
export { SignupRequestDto as SignupRequest } from './signup/signup-request.dto';
|
||||||
|
export { SignupResponseDto as SignupResponse } from './signup/signup-response.dto';
|
||||||
|
|
||||||
|
export { LoginRequestDto as LoginRequest } from './login/login-request.dto';
|
||||||
|
export { LoginResponseDto as LoginResponse } from './login/login-response.dto'
|
||||||
|
|
||||||
|
export { RefreshAccessTokenResponseDto as RefreshAccessTokenResponse } from './refreshAccessToken/refresh-access-token-response.dto';
|
||||||
|
|
||||||
|
export { SendResetPasswordCodeRequestDto as SendResetPasswordCodeRequest } from './sendResetPasswordCode/send-reset-password-code-request.dto';
|
||||||
|
export { SendResetPasswordCodeResponseDto as SendResetPasswordCodeResponse } from './sendResetPasswordCode/send-reset-password-code-response.dto';
|
||||||
|
|
||||||
|
export { VerifyResetPasswordCodeRequestDto as VerifyResetPasswordCodeRequest } from './verifyResetPasswordCode/verify-reset-password-code-request.dto';
|
||||||
|
export { VerifyResetPasswordCodeResponseDto as VerifyResetPasswordCodeResponse } from './verifyResetPasswordCode/verify-reset-password-code-response.dto'
|
||||||
|
|
||||||
|
export { ResetPasswordRequestDto as ResetPasswordRequest } from './resetPassword/reset-password-request.dto';
|
||||||
|
export { ResetPasswordResponseDto as ResetPasswordResponse } from './resetPassword/reset-password-response.dto';
|
||||||
11
src/modules/account/dto/login/login-request.dto.ts
Normal file
11
src/modules/account/dto/login/login-request.dto.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { IsString } from "@nestjs/class-validator";
|
||||||
|
|
||||||
|
export class LoginRequestDto {
|
||||||
|
type: 'email' | 'accountId';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
6
src/modules/account/dto/login/login-response.dto.ts
Normal file
6
src/modules/account/dto/login/login-response.dto.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { BaseResponseDto } from "../base-response.dto";
|
||||||
|
|
||||||
|
export class LoginResponseDto extends BaseResponseDto {
|
||||||
|
accessToken?: string;
|
||||||
|
refreshToken?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { BaseResponseDto } from "../base-response.dto";
|
||||||
|
|
||||||
|
export class RefreshAccessTokenResponseDto extends BaseResponseDto{
|
||||||
|
accessToken: string;
|
||||||
|
refreshToken: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { IsEmail, IsString } from "@nestjs/class-validator";
|
||||||
|
|
||||||
|
export class ResetPasswordRequestDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { BaseResponseDto } from "../base-response.dto";
|
||||||
|
|
||||||
|
export class ResetPasswordResponseDto extends BaseResponseDto {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { IsEmail } from "@nestjs/class-validator";
|
||||||
|
|
||||||
|
export class SendEmailVerificationCodeRequestDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import { BaseResponseDto } from "../base-response.dto";
|
||||||
|
|
||||||
|
export class SendEmailVerificationCodeResponseDto extends BaseResponseDto{
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { IsEmail } from "@nestjs/class-validator";
|
||||||
|
|
||||||
|
export class SendResetPasswordCodeRequestDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import { BaseResponseDto } from "../base-response.dto";
|
||||||
|
|
||||||
|
export class SendResetPasswordCodeResponseDto extends BaseResponseDto {
|
||||||
|
}
|
||||||
18
src/modules/account/dto/signup/signup-request.dto.ts
Normal file
18
src/modules/account/dto/signup/signup-request.dto.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { IsEmail, IsString } from "@nestjs/class-validator";
|
||||||
|
|
||||||
|
export class SignupRequestDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
nickname: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
accountId: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
4
src/modules/account/dto/signup/signup-response.dto.ts
Normal file
4
src/modules/account/dto/signup/signup-response.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
import { BaseResponseDto } from "../base-response.dto";
|
||||||
|
|
||||||
|
export class SignupResponseDto extends BaseResponseDto {
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { IsEmail, IsString } from "@nestjs/class-validator";
|
||||||
|
|
||||||
|
export class VerifyEmailVerificationCodeRequestDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
code: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { BaseResponseDto } from "../base-response.dto";
|
||||||
|
|
||||||
|
export class VerifyEmailVerificationCodeResponseDto extends BaseResponseDto{
|
||||||
|
verified: boolean;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { IsEmail, IsString } from "@nestjs/class-validator"
|
||||||
|
|
||||||
|
export class VerifyResetPasswordCodeRequestDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
code: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { BaseResponseDto } from "../base-response.dto";
|
||||||
|
|
||||||
|
export class VerifyResetPasswordCodeResponseDto extends BaseResponseDto {
|
||||||
|
verified: boolean;
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Global, Module } from "@nestjs/common";
|
import { Global, Inject, Module, OnApplicationShutdown } from "@nestjs/common";
|
||||||
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||||
import Redis from "ioredis";
|
import Redis from "ioredis";
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@@ -6,14 +7,21 @@ import Redis from "ioredis";
|
|||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
provide: "REDIS",
|
provide: "REDIS",
|
||||||
useFactory: () => {
|
useFactory: (configService: ConfigService): Redis => {
|
||||||
return new Redis({
|
return new Redis({
|
||||||
host: process.env.RD_HOST!,
|
host: configService.get<string>('RD_HOST')!,
|
||||||
port: Number(process.env.RD_PORT || 6779)
|
port: configService.get<number>('RD_PORT')
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
|
inject: [ConfigService]
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
exports: ["REDIS"]
|
exports: ["REDIS"]
|
||||||
})
|
})
|
||||||
export class RedisModule{}
|
export class RedisModule implements OnApplicationShutdown {
|
||||||
|
constructor(@Inject("REDIS") private readonly redis: Redis) {}
|
||||||
|
|
||||||
|
async onApplicationShutdown(signal?: string) {
|
||||||
|
await this.redis.quit();
|
||||||
|
}
|
||||||
|
}
|
||||||
11
src/util/converter.ts
Normal file
11
src/util/converter.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import bcrypt from 'bcrypt';
|
||||||
|
|
||||||
|
export class Converter {
|
||||||
|
static getHashedPassword(password: string) {
|
||||||
|
return bcrypt.hashSync(password, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
static comparePassword(rawPassword: string, hashedPassword: string) {
|
||||||
|
return bcrypt.compareSync(rawPassword, hashedPassword);
|
||||||
|
}
|
||||||
|
}
|
||||||
37
src/util/generator.ts
Normal file
37
src/util/generator.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
export class Generator {
|
||||||
|
static getVerificationCode() {
|
||||||
|
return Math.random().toString().slice(2, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static getRandomCharacter(string: string) {
|
||||||
|
return string[Math.floor(Math.random() * string.length)];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static getShuffledString(string: string) {
|
||||||
|
let arr = string.split('');
|
||||||
|
|
||||||
|
for (let i = arr.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.floor(Math.random() * (i + 1));
|
||||||
|
[arr[i], arr[j]] = [arr[j], arr[i]];
|
||||||
|
}
|
||||||
|
|
||||||
|
return arr.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
static getResetPasswordCode() {
|
||||||
|
const alphabets = 'abcdefghijklmnopqrstuvwxyz';
|
||||||
|
const numbers = '0123456789';
|
||||||
|
const specials = '!@#$%^';
|
||||||
|
const all = alphabets + numbers + specials;
|
||||||
|
|
||||||
|
let resetPasswordCode = Generator.getRandomCharacter(alphabets);
|
||||||
|
let requiredNumber = Generator.getRandomCharacter(numbers);
|
||||||
|
let requiredSpecial = Generator.getRandomCharacter(specials);
|
||||||
|
|
||||||
|
let shuffledRestPart = Generator.getShuffledString(all).slice(0, 5);
|
||||||
|
|
||||||
|
let shuffledRestCode = Generator.getShuffledString(requiredNumber + requiredSpecial + shuffledRestPart);
|
||||||
|
|
||||||
|
return resetPasswordCode + shuffledRestCode;
|
||||||
|
}
|
||||||
|
}
|
||||||
9
src/util/mailer/mailer.module.ts
Normal file
9
src/util/mailer/mailer.module.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { Module, Global } from '@nestjs/common';
|
||||||
|
import { MailerService } from './mailer.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [MailerService],
|
||||||
|
exports: [MailerService]
|
||||||
|
})
|
||||||
|
export class MailerModule {}
|
||||||
57
src/util/mailer/mailer.service.ts
Normal file
57
src/util/mailer/mailer.service.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import nodemailer from 'nodemailer';
|
||||||
|
import { google } from 'googleapis';
|
||||||
|
import { OAuth2Client } from 'google-auth-library';
|
||||||
|
import SMTPTransport from 'nodemailer/lib/smtp-transport';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MailerService {
|
||||||
|
private oauth2Client: OAuth2Client;
|
||||||
|
private readonly gmailUser: string;
|
||||||
|
|
||||||
|
constructor(private readonly configService: ConfigService) {
|
||||||
|
const clientId = this.configService.get<string>('GMAIL_CLIENT_ID');
|
||||||
|
const clientSecret = this.configService.get<string>('GMAIL_CLIENT_SECRET');
|
||||||
|
const refreshToken = this.configService.get<string>('GMAIL_REFRESH_TOKEN');
|
||||||
|
|
||||||
|
this.gmailUser = this.configService.get<string>('GMAIL_USER')!;
|
||||||
|
|
||||||
|
this.oauth2Client = new google.auth.OAuth2(
|
||||||
|
clientId,
|
||||||
|
clientSecret,
|
||||||
|
'https://developers.google.com/oauthplayground'
|
||||||
|
);
|
||||||
|
|
||||||
|
this.oauth2Client.setCredentials({
|
||||||
|
refresh_token: refreshToken,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendMail(to: string, subject: string, html: string) {
|
||||||
|
const accessToken = await this.oauth2Client.getAccessToken();
|
||||||
|
|
||||||
|
const options: SMTPTransport.Options = {
|
||||||
|
host: "smtp.gmail.com",
|
||||||
|
port: 465,
|
||||||
|
secure: true,
|
||||||
|
auth: {
|
||||||
|
type: "OAuth2",
|
||||||
|
user: this.gmailUser,
|
||||||
|
clientId: this.configService.get<string>('GMAIL_CLIENT_ID'),
|
||||||
|
clientSecret: this.configService.get<string>('GMAIL_CLIENT_SECRET'),
|
||||||
|
refreshToken: this.configService.get<string>('GMAIL_REFRESH_TOKEN'),
|
||||||
|
accessToken: accessToken?.token || '',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const transporter = nodemailer.createTransport(options);
|
||||||
|
|
||||||
|
return transporter.sendMail({
|
||||||
|
from: `Scheduler ${this.gmailUser}>`,
|
||||||
|
to,
|
||||||
|
subject,
|
||||||
|
html
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,12 @@
|
|||||||
{
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"noEmitOnError": true,
|
||||||
|
"sourceMap": false,
|
||||||
|
"incremental": false,
|
||||||
|
"noEmit": false,
|
||||||
|
"tsBuildInfoFile": ".tsbuildinfo",
|
||||||
|
"outDir": "./dist"
|
||||||
|
},
|
||||||
"extends": "./tsconfig.json",
|
"extends": "./tsconfig.json",
|
||||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,12 +14,13 @@
|
|||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"outDir": "./dist",
|
"outDir": "./dist",
|
||||||
"baseUrl": "./",
|
"baseUrl": "./",
|
||||||
"incremental": true,
|
"incremental": false,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"strictNullChecks": true,
|
"strictNullChecks": true,
|
||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
"noImplicitAny": false,
|
"noImplicitAny": false,
|
||||||
"strictBindCallApply": false,
|
"strictBindCallApply": false,
|
||||||
"noFallthroughCasesInSwitch": false
|
"noFallthroughCasesInSwitch": false,
|
||||||
|
"noEmit": false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user