Skip to content

Commit

Permalink
Merge branch 'main' into portainer-migration
Browse files Browse the repository at this point in the history
  • Loading branch information
BlueHorn07 authored Apr 25, 2024
2 parents b8321ad + bf7e7d2 commit 7506f79
Show file tree
Hide file tree
Showing 45 changed files with 358 additions and 263 deletions.
28 changes: 8 additions & 20 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,17 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
env: {
browser: true,
es2021: true,
node: true,
},
plugins: ['@typescript-eslint/eslint-plugin'],
settings: {},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/ban-types': 'off',
'@typescript-eslint/no-unused-vars': 'warn',
'@typescript-eslint/no-empty-function': 'off',
"no-warning-comments": 'off',
'prettier/prettier': 'off'
'prettier/prettier': ['error', { 'endOfLine': 'auto' }],
'@typescript-eslint/no-explicit-any': 'warn',
},
};
18 changes: 18 additions & 0 deletions .github/workflows/github-action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,26 @@ env:
ECR_REPOSITORY: popo-nest-api

jobs:
lint:
name: Prettier and ESLint check
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm install
- name: Run Prettier
run: npx prettier --check **/*.ts
- name: Run ESLint
run: npx eslint . --ext .ts --ignore-pattern dist/

docker_build_and_push:
name: Docker build and push
needs: lint
runs-on: ubuntu-latest
steps:
- name: Checkout
Expand Down
7 changes: 4 additions & 3 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 2,
"semi": true,
"endOfLine": "lf"
"useTabs": false,
"tabWidth": 2,
"trailingComma": "all",
"printWidth": 80
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"format": "prettier --w **/*.ts",
"lint": "eslint . --ext .ts --ignore-pattern dist/",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
Expand Down
2 changes: 1 addition & 1 deletion src/admin/admin.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import { Module } from '@nestjs/common';
import { AdminController } from './admin.controller';

@Module({
controllers: [AdminController]
controllers: [AdminController],
})
export class AdminModule {}
5 changes: 3 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config'
import { ConfigModule, ConfigService } from '@nestjs/config';

import { AppController } from './app.controller';
import { AppService } from './app.service';
Expand All @@ -18,7 +18,8 @@ import configuration from './config/configurations';
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => configService.get('database'),
useFactory: (configService: ConfigService) =>
configService.get('database'),
inject: [ConfigService],
}),
PopoModule,
Expand Down
8 changes: 6 additions & 2 deletions src/app.service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { Injectable } from '@nestjs/common';
import * as moment from 'moment';
import * as momentTz from "moment-timezone";
import * as momentTz from 'moment-timezone';

@Injectable()
export class AppService {
getHello(): string {
return `Hello POPO! (popo-${process.env.POPO_VERSION}) (server now: ${moment().format('YYYY-MM-DD HH:mm:ss')}, KST now: ${momentTz().tz("Asia/Seoul").format('YYYY-MM-DD HH:mm:ss')})`;
return `Hello POPO! (popo-${
process.env.POPO_VERSION
}) (server now: ${moment().format(
'YYYY-MM-DD HH:mm:ss',
)}, KST now: ${momentTz().tz('Asia/Seoul').format('YYYY-MM-DD HH:mm:ss')})`;
}
}
42 changes: 26 additions & 16 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import { MailService } from '../mail/mail.service';
import { ReservePlaceService } from '../popo/reservation/place/reserve.place.service';
import { ReserveEquipService } from '../popo/reservation/equip/reserve.equip.service';
import { ApiTags } from '@nestjs/swagger';
import {JwtPayload} from "./strategies/jwt.payload";
import {PasswordResetRequest, PasswordUpdateRequest} from "./auth.dto";
import { JwtPayload } from './strategies/jwt.payload';
import { PasswordResetRequest, PasswordUpdateRequest } from './auth.dto';

const requiredRoles = [UserType.admin, UserType.association, UserType.staff];

Expand Down Expand Up @@ -95,7 +95,7 @@ export class AuthController {
// update Login History
const existUser = await this.userService.findOneByUuidOrFail(user.uuid);
await this.userService.updateLogin(existUser.uuid);

return res.send(user);
}

Expand All @@ -115,8 +115,8 @@ export class AuthController {

try {
await this.mailService.sendVerificationMail(
createUserDto.email,
saveUser.uuid,
createUserDto.email,
saveUser.uuid,
);
} catch (error) {
console.log('!! 유저 인증 메일 전송 실패 !!');
Expand All @@ -133,25 +133,36 @@ export class AuthController {
}

@Post('password/reset')
async resetPassword(
@Body() body: PasswordResetRequest,
) {
async resetPassword(@Body() body: PasswordResetRequest) {
const existUser = await this.userService.findOneByEmail(body.email);

if (!existUser) {
throw new BadRequestException('해당 이메일로 가입한 유저가 존재하지 않습니다.');
throw new BadRequestException(
'해당 이메일로 가입한 유저가 존재하지 않습니다.',
);
}

if (existUser.userStatus === UserStatus.password_reset) {
throw new BadRequestException('이미 비빌번호를 초기화 했습니다. 신규 비밀번호를 메일에서 확인해주세요.');
throw new BadRequestException(
'이미 비빌번호를 초기화 했습니다. 신규 비밀번호를 메일에서 확인해주세요.',
);
}

// generate 8-length random password
const temp_password = 'poapper_' + Math.random().toString(36).slice(-8);

await this.userService.updatePasswordByEmail(existUser.email, temp_password);
await this.userService.updateUserStatus(existUser.uuid, UserStatus.password_reset);
await this.mailService.sendPasswordResetMail(existUser.email, temp_password);
await this.userService.updatePasswordByEmail(
existUser.email,
temp_password,
);
await this.userService.updateUserStatus(
existUser.uuid,
UserStatus.password_reset,
);
await this.mailService.sendPasswordResetMail(
existUser.email,
temp_password,
);
}

@Post('password/update')
Expand All @@ -168,8 +179,7 @@ export class AuthController {
@UseGuards(JwtAuthGuard)
async getMyInfo(@Req() req: Request) {
const user = req.user as JwtPayload;
const { password, cryptoSalt, ...UserInfo } =
await this.userService.findOneByUuid(user.uuid);
const { ...UserInfo } = await this.userService.findOneByUuid(user.uuid);

return UserInfo;
}
Expand Down
29 changes: 14 additions & 15 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {Module} from '@nestjs/common';
import {JwtModule} from '@nestjs/jwt';
import {PassportModule} from '@nestjs/passport';
import {AuthService} from './auth.service';
import {jwtConstants} from './constants';
import {JwtStrategy} from './strategies/jwt.strategy';
import {LocalStrategy} from './strategies/local.strategy';
import {UserModule} from "../popo/user/user.module";
import {AuthController} from './auth.controller';
import {MailModule} from "../mail/mail.module";
import {ReservePlaceModule} from "../popo/reservation/place/reserve.place.module";
import { ReserveEquipModule } from "../popo/reservation/equip/reserve.equip.module";
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { jwtConstants } from './constants';
import { JwtStrategy } from './strategies/jwt.strategy';
import { LocalStrategy } from './strategies/local.strategy';
import { UserModule } from '../popo/user/user.module';
import { AuthController } from './auth.controller';
import { MailModule } from '../mail/mail.module';
import { ReservePlaceModule } from '../popo/reservation/place/reserve.place.module';
import { ReserveEquipModule } from '../popo/reservation/equip/reserve.equip.module';

@Module({
imports: [
Expand All @@ -20,12 +20,11 @@ import { ReserveEquipModule } from "../popo/reservation/equip/reserve.equip.modu
PassportModule,
JwtModule.register({
secret: jwtConstants.secret,
signOptions: {expiresIn: '360000s'},
signOptions: { expiresIn: '360000s' },
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
controllers: [AuthController],
})
export class AuthModule {
}
export class AuthModule {}
6 changes: 2 additions & 4 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class AuthService {
}

const cryptoSalt = user.cryptoSalt;

if (user.userStatus == UserStatus.password_reset) {
await this.usersService.updateUserStatus(user.uuid, UserStatus.activated);
} else if (user.userStatus != UserStatus.activated) {
Expand All @@ -32,15 +32,13 @@ export class AuthService {

const encryptedPassword = this.encryptPassword(password, cryptoSalt);
if (user.password === encryptedPassword) {
const { password, ...result } = user;
const { ...result } = user;
return result;
} else {
return null;
}
}



async generateJwtToken(user: any) {

Check warning on line 42 in src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / Prettier and ESLint check

Unexpected any. Specify a different type
const payload = {
uuid: user.uuid,
Expand Down
6 changes: 3 additions & 3 deletions src/auth/authroization/roles.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {SetMetadata} from "@nestjs/common";
import {UserType} from "../../popo/user/user.meta";
import { SetMetadata } from '@nestjs/common';
import { UserType } from '../../popo/user/user.meta';

export const Roles = (...roles: UserType[]) => SetMetadata('roles', roles);
export const Roles = (...roles: UserType[]) => SetMetadata('roles', roles);
16 changes: 8 additions & 8 deletions src/auth/authroization/roles.guard.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {CanActivate, ExecutionContext, Injectable} from "@nestjs/common";
import {Reflector} from '@nestjs/core';
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
constructor(
private readonly reflector: Reflector
) {
}
constructor(private readonly reflector: Reflector) {}

canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.get<string[]>('roles', context.getHandler());
const requiredRoles = this.reflector.get<string[]>(
'roles',
context.getHandler(),
);
// 모든 Role에서 접근 가능
if (!requiredRoles) {
return true;
Expand All @@ -20,4 +20,4 @@ export class RolesGuard implements CanActivate {

return requiredRoles.some((role) => user.userType?.includes(role));
}
}
}
10 changes: 5 additions & 5 deletions src/auth/strategies/local.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {Injectable, UnauthorizedException} from '@nestjs/common';
import {PassportStrategy} from '@nestjs/passport';
import {Strategy} from 'passport-local';
import {AuthService} from '../auth.service';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { AuthService } from '../auth.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({usernameField: 'email'});
super({ usernameField: 'email' });
}

async validate(email: string, password: string): Promise<any> {

Check warning on line 12 in src/auth/strategies/local.strategy.ts

View workflow job for this annotation

GitHub Actions / Prettier and ESLint check

Unexpected any. Specify a different type
Expand Down
14 changes: 6 additions & 8 deletions src/file/file.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ export class FileService {

constructor() {}



async queryOnS3(key: string, query: string) {
const res = await this.s3.send(
new SelectObjectContentCommand({
Expand All @@ -30,19 +28,19 @@ export class FileService {
Expression: query,
InputSerialization: {
CSV: {
FileHeaderInfo: "USE",
FileHeaderInfo: 'USE',
},
},
OutputSerialization: {
JSON: {
RecordDelimiter: ',',
},
},
})
)
}),
);

if (!res.Payload) {
throw new Error("No payload received from S3 SelectObjectContent");
throw new Error('No payload received from S3 SelectObjectContent');
}

const convertDataToJson = async (generator) => {
Expand All @@ -65,8 +63,8 @@ export class FileService {
new GetObjectCommand({
Bucket: this.bucket,
Key: key,
})
)
}),
);
return res.Body.transformToString();
}

Expand Down
Loading

0 comments on commit 7506f79

Please sign in to comment.