Skip to content

Commit

Permalink
fix(#173): console 출력 삭제
Browse files Browse the repository at this point in the history
  • Loading branch information
kimhji committed Nov 28, 2024
1 parent 98e3c73 commit 4daf433
Show file tree
Hide file tree
Showing 7 changed files with 610 additions and 611 deletions.
211 changes: 105 additions & 106 deletions apps/backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,106 +1,105 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { isString } from 'class-validator';
import { randomBytes } from 'crypto';
import { Request } from 'express';
import { RedisRepository } from '@/redis/redis.repository';
import { UserService } from '@/user/user.service';

@Injectable()
export class AuthService {
constructor(
private readonly userService: UserService,
private configService: ConfigService,
private jwtService: JwtService,
private redisRepository: RedisRepository
) {}

private JWT_SECRET_KEY = this.configService.get<string>('JWT_SECRET_KEY');

initLoginTokens(userId: string) {
const sortV = this.generateRandomKey(64);
const accessToken = this.createAccess(userId, sortV);
const refreshToken = this.createRefresh(userId, sortV);
console.log(accessToken);
this.setRedisData(accessToken, refreshToken);
return accessToken;
}

async setRedisData(access: string, refresh: string) {
await this.redisRepository.set(access, refresh);
}

createAccess(userId: string, sortValue: string): string {
const payload = { userId };
return this.createJwt(payload, '1h', sortValue);
}

createRefresh(userId: string, sortValue: string): string {
const payload = { userId, sortValue };
return this.createJwt(payload, '1d');
}

createJwt(payload: any, expireTime: string, secretKey: string = this.JWT_SECRET_KEY): string {
return this.jwtService.sign(payload, {
secret: secretKey,
expiresIn: expireTime
});
}

generateRandomKey(length: number): string {
return randomBytes(length)
.toString('base64') // base64 또는 hex로 인코딩 가능
.slice(0, length) // 원하는 길이만큼 자르기
.replace(/[^a-zA-Z0-9]/g, ''); // 특수문자 제거 (선택 사항)
}

async verifyJwt(token: string) {
if (!token) {
throw new HttpException('token is not found', HttpStatus.UNAUTHORIZED);
}
const refreshToken = await this.redisRepository.get(token);
let decodedRefresh = { sortValue: '', userId: '' };
try {
decodedRefresh = this.jwtService.verify(refreshToken, {
secret: this.JWT_SECRET_KEY
});
} catch (e) {
if (e.name === 'TokenExpiredError') throw new HttpException('token expired', HttpStatus.UNAUTHORIZED);
else {
throw new HttpException('invalid token', HttpStatus.UNAUTHORIZED);
}
}
try {
const decoded = this.jwtService.verify(token, {
secret: decodedRefresh.sortValue
});
if (!decoded.userId) throw new Error();
return decoded.userId;
} catch (e) {
if (e.name === 'TokenExpiredError') {
const newAccess = this.createAccess(decodedRefresh.userId, decodedRefresh.sortValue);
this.setRedisData(refreshToken, newAccess);
return decodedRefresh.userId;
} else {
throw new HttpException('invalid token', HttpStatus.UNAUTHORIZED);
}
}
}

async getIdFromRequest(req: Request) {
const auth = req.header('Authorization');
if (!auth) {
throw new HttpException('token is not found', HttpStatus.UNAUTHORIZED);
}
const token = req.header('Authorization').split(' ')[1].trim();
if (!isString(token)) {
throw new HttpException('invalid token', HttpStatus.UNAUTHORIZED);
}
return await this.verifyJwt(token);
}

async getUserGitToken(userId: string): Promise<string> {
return await this.userService.findUserGistToken(userId);
}
}
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { isString } from 'class-validator';
import { randomBytes } from 'crypto';
import { Request } from 'express';
import { RedisRepository } from '@/redis/redis.repository';
import { UserService } from '@/user/user.service';

@Injectable()
export class AuthService {
constructor(
private readonly userService: UserService,
private configService: ConfigService,
private jwtService: JwtService,
private redisRepository: RedisRepository
) {}

private JWT_SECRET_KEY = this.configService.get<string>('JWT_SECRET_KEY');

initLoginTokens(userId: string) {
const sortV = this.generateRandomKey(64);
const accessToken = this.createAccess(userId, sortV);
const refreshToken = this.createRefresh(userId, sortV);
this.setRedisData(accessToken, refreshToken);
return accessToken;
}

async setRedisData(access: string, refresh: string) {
await this.redisRepository.set(access, refresh);
}

createAccess(userId: string, sortValue: string): string {
const payload = { userId };
return this.createJwt(payload, '1h', sortValue);
}

createRefresh(userId: string, sortValue: string): string {
const payload = { userId, sortValue };
return this.createJwt(payload, '1d');
}

createJwt(payload: any, expireTime: string, secretKey: string = this.JWT_SECRET_KEY): string {
return this.jwtService.sign(payload, {
secret: secretKey,
expiresIn: expireTime
});
}

generateRandomKey(length: number): string {
return randomBytes(length)
.toString('base64') // base64 또는 hex로 인코딩 가능
.slice(0, length) // 원하는 길이만큼 자르기
.replace(/[^a-zA-Z0-9]/g, ''); // 특수문자 제거 (선택 사항)
}

async verifyJwt(token: string) {
if (!token) {
throw new HttpException('token is not found', HttpStatus.UNAUTHORIZED);
}
const refreshToken = await this.redisRepository.get(token);
let decodedRefresh = { sortValue: '', userId: '' };
try {
decodedRefresh = this.jwtService.verify(refreshToken, {
secret: this.JWT_SECRET_KEY
});
} catch (e) {
if (e.name === 'TokenExpiredError') throw new HttpException('token expired', HttpStatus.UNAUTHORIZED);
else {
throw new HttpException('invalid token', HttpStatus.UNAUTHORIZED);
}
}
try {
const decoded = this.jwtService.verify(token, {
secret: decodedRefresh.sortValue
});
if (!decoded.userId) throw new Error();
return decoded.userId;
} catch (e) {
if (e.name === 'TokenExpiredError') {
const newAccess = this.createAccess(decodedRefresh.userId, decodedRefresh.sortValue);
this.setRedisData(newAccess, refreshToken);
return decodedRefresh.userId;
} else {
throw new HttpException('invalid token', HttpStatus.UNAUTHORIZED);
}
}
}

async getIdFromRequest(req: Request) {
const auth = req.header('Authorization');
if (!auth) {
throw new HttpException('token is not found', HttpStatus.UNAUTHORIZED);
}
const token = req.header('Authorization').split(' ')[1].trim();
if (!isString(token)) {
throw new HttpException('invalid token', HttpStatus.UNAUTHORIZED);
}
return await this.verifyJwt(token);
}

async getUserGitToken(userId: string): Promise<string> {
return await this.userService.findUserGistToken(userId);
}
}
16 changes: 8 additions & 8 deletions apps/backend/src/config/queue.config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ConfigService } from '@nestjs/config';

export const queueConfig = (configService: ConfigService) => ({
redis: {
host: configService.get<string>('REDIS_HOST', { infer: true }),
port: configService.get<number>('REDIS_PORT', { infer: true })
}
});
import { ConfigService } from '@nestjs/config';

export const queueConfig = (configService: ConfigService) => ({
redis: {
host: configService.get<string>('REDIS_HOST', { infer: true }),
port: configService.get<number>('REDIS_PORT', { infer: true })
}
});
36 changes: 18 additions & 18 deletions apps/backend/src/config/typeorm.config.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { ConfigService } from '@nestjs/config';
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { Comment } from '@/comment/comment.entity';
import { History } from '@/history/history.entity';
import { Lotus } from '@/lotus/lotus.entity';
import { Tag } from '@/tag/tag.entity';
import { User } from '@/user/user.entity';

export const typeORMConfig = async (configService: ConfigService): Promise<TypeOrmModuleOptions> => ({
type: 'mysql',
host: configService.get<string>('MYSQL_HOST'),
port: configService.get<number>('MYSQL_PORT'),
username: configService.get<string>('MYSQL_USER'),
password: configService.get<string>('MYSQL_PASSWORD'),
database: configService.get<string>('MYSQL_DATABASE'),
entities: [User, Lotus, Comment, Tag, History]
// synchronize: true //todo: env로 release에서는 false가 되도록 해야함
});
import { ConfigService } from '@nestjs/config';
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { Comment } from '@/comment/comment.entity';
import { History } from '@/history/history.entity';
import { Lotus } from '@/lotus/lotus.entity';
import { Tag } from '@/tag/tag.entity';
import { User } from '@/user/user.entity';

export const typeORMConfig = async (configService: ConfigService): Promise<TypeOrmModuleOptions> => ({
type: 'mysql',
host: configService.get<string>('MYSQL_HOST'),
port: configService.get<number>('MYSQL_PORT'),
username: configService.get<string>('MYSQL_USER'),
password: configService.get<string>('MYSQL_PASSWORD'),
database: configService.get<string>('MYSQL_DATABASE'),
entities: [User, Lotus, Comment, Tag, History]
// synchronize: true //todo: env로 release에서는 false가 되도록 해야함
});
Loading

0 comments on commit 4daf433

Please sign in to comment.