Skip to content

Commit

Permalink
♻️ refactor: lint 에 위배되는 코드 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
jinddings committed Nov 11, 2024
1 parent 1fe2082 commit b872066
Show file tree
Hide file tree
Showing 11 changed files with 75 additions and 44 deletions.
3 changes: 3 additions & 0 deletions BE/package-lock.json

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

1 change: 1 addition & 0 deletions BE/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"cross-env": "^7.0.3",
"docker": "^1.0.0",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"fastify-swagger": "^5.1.1",
"mysql2": "^3.11.3",
"passport": "^0.7.0",
Expand Down
1 change: 0 additions & 1 deletion BE/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { ScheduleModule } from '@nestjs/schedule';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { User } from './auth/user.entity';
import { StockIndexModule } from './stock/index/stock-index.module';
import { StockTopfiveModule } from './stock/topfive/stock-topfive.module';
import { KoreaInvestmentModule } from './koreaInvestment/korea-investment.module';
Expand Down
16 changes: 9 additions & 7 deletions BE/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import {
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiOperation } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { Request, Response } from 'express';
import { ConfigService } from '@nestjs/config';
import { AuthService } from './auth.service';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';

@Controller('auth')
export class AuthController {
Expand Down Expand Up @@ -62,13 +62,15 @@ export class AuthController {
@ApiOperation({ summary: 'Refresh Token 요청 API' })
@Get('/refresh')
async refresh(@Req() req: Request, @Res() res: Response) {
const refreshToken = req.cookies['refreshToken'];
const accessToken = req.cookies['accessToken'];

if (!refreshToken || !accessToken) {
return res.status(401).send();
if (
typeof req.cookies.refreshToken !== 'string' ||
typeof req.cookies.accessToken !== 'string'
) {
return res.status(400).send();
}

const { refreshToken } = req.cookies;

const newAccessToken = await this.authService.refreshToken(refreshToken);

res.cookie('accessToken', newAccessToken, { httpOnly: true });
Expand Down
4 changes: 2 additions & 2 deletions BE/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { User } from './user.entity';
import { UserRepository } from './user.repository';
import { JwtStrategy } from './strategy/jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { KakaoStrategy } from './strategy/kakao.strategy';

@Module({
Expand All @@ -17,7 +17,7 @@ import { KakaoStrategy } from './strategy/kakao.strategy';
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
useFactory: (configService: ConfigService) => ({
secret: configService.get<string>('JWT_SECRET'),
signOptions: {
expiresIn: configService.get<string>('JWT_ACCESS_EXPIRATION_TIME'),
Expand Down
41 changes: 22 additions & 19 deletions BE/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { ConfigService } from '@nestjs/config';
import { UserRepository } from './user.repository';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AuthService {
Expand All @@ -29,7 +29,7 @@ export class AuthService {
const { accessToken, refreshToken } =
await this.getJWTToken(authCredentialsDto);

this.setCurrentRefreshToken(refreshToken, user.id);
await this.setCurrentRefreshToken(refreshToken, user.id);

return { accessToken, refreshToken };
}
Expand All @@ -39,8 +39,9 @@ export class AuthService {
async kakaoLoginUser(
authCredentialsDto: AuthCredentialsDto,
): Promise<{ accessToken: string; refreshToken: string }> {
return await this.getJWTToken(authCredentialsDto);
return this.getJWTToken(authCredentialsDto);
}

async getJWTToken(authCredentialsDto: AuthCredentialsDto) {
const accessToken = await this.generateAccessToken(authCredentialsDto);
const refreshToken = await this.generateRefreshToken(authCredentialsDto);
Expand All @@ -51,15 +52,15 @@ export class AuthService {
authCredentialsDto: AuthCredentialsDto,
): Promise<string> {
return authCredentialsDto.email
? this.jwtService.sign({ email: authCredentialsDto.email })
: this.jwtService.sign({ kakaoId: authCredentialsDto.kakaoId });
? this.jwtService.signAsync({ email: authCredentialsDto.email })
: this.jwtService.signAsync({ kakaoId: authCredentialsDto.kakaoId });
}

async generateRefreshToken(
authCredentialsDto: AuthCredentialsDto,
): Promise<string> {
if (authCredentialsDto.email) {
return this.jwtService.sign(
return this.jwtService.signAsync(
{ email: authCredentialsDto.email },
{
secret: this.configService.get<string>('JWT_REFRESH_SECRET'),
Expand All @@ -68,17 +69,16 @@ export class AuthService {
),
},
);
} else {
return this.jwtService.sign(
{ kakaoId: authCredentialsDto.kakaoId },
{
secret: this.configService.get<string>('JWT_REFRESH_SECRET'),
expiresIn: this.configService.get<string>(
'JWT_REFRESH_EXPIRATION_TIME',
),
},
);
}
return this.jwtService.signAsync(
{ kakaoId: authCredentialsDto.kakaoId },
{
secret: this.configService.get<string>('JWT_REFRESH_SECRET'),
expiresIn: this.configService.get<string>(
'JWT_REFRESH_EXPIRATION_TIME',
),
},
);
}

async setCurrentRefreshToken(refreshToken: string, userId: number) {
Expand All @@ -87,10 +87,13 @@ export class AuthService {
const currentRefreshToken = await bcrypt.hash(refreshToken, salt);
const currentRefreshTokenExpiresAt = new Date(
currentDate.getTime() +
parseInt(this.configService.get<string>('JWT_REFRESH_EXPIRATION_TIME')),
parseInt(
this.configService.get<string>('JWT_REFRESH_EXPIRATION_TIME'),
10,
),
);

this.userRepository.update(userId, {
await this.userRepository.update(userId, {
currentRefreshToken,
currentRefreshTokenExpiresAt,
});
Expand Down Expand Up @@ -120,7 +123,7 @@ export class AuthService {
}

const accessToken = this.generateAccessToken(user.toAuthCredentialsDto());
return accessToken;
return await accessToken;
} catch (error) {
throw new UnauthorizedException('Invalid Token');
}
Expand Down
2 changes: 0 additions & 2 deletions BE/src/auth/dto/auth-credentials.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import {
Matches,
MaxLength,
MinLength,
IsEmail,
ValidateNested,
IsOptional,
} from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
Expand Down
45 changes: 34 additions & 11 deletions BE/src/auth/strategy/kakao.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,53 @@ import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { Profile, Strategy } from 'passport-kakao';

interface KakaoStrategyOptions {
clientID: string;
clientSecret: string;
callbackURL: string;
}

interface KakaoProfile extends Profile {
id: number;
_json: {
id: number;
};
}

interface KakaoUser {
kakaoId: number;
}

@Injectable()
export class KakaoStrategy extends PassportStrategy(Strategy) {
export class KakaoStrategy extends PassportStrategy<Strategy>(
Strategy,
'kakao',
) {
constructor(private readonly configService: ConfigService) {
super({
clientID: configService.get('KAKAO_CLIENT_ID'),
const options: KakaoStrategyOptions = {
clientID: configService.get<string>('KAKAO_CLIENT_ID') || '',
clientSecret: '',
callbackURL: `${configService.get('BACKEND_URL')}/auth/kakao`,
});
callbackURL: `${configService.get<string>('BACKEND_URL') || ''}/auth/kakao`,
};

super(options);
}

async validate(
validate(
accessToken: string,
refreshToken: string,
profile: Profile,
done: (error: any, user?: any, info?: any) => void,
profile: KakaoProfile,
done: (error: Error, user?: KakaoUser) => void,
) {
try {
const { _json } = profile;
// eslint-disable-next-line no-underscore-dangle
const kakaoId = profile._json.id;
const user = {
kakaoId: _json.id,
kakaoId,
};
done(null, user);
} catch (error) {
done(error);
done(error instanceof Error ? error : new Error(String(error)));
}
}
}
2 changes: 2 additions & 0 deletions BE/src/auth/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,7 @@ export class User extends BaseEntity {
password: this.password,
};
}

throw new Error('Cannot convert Kakao user to auth credentials');
}
}
2 changes: 1 addition & 1 deletion BE/src/configs/typeorm.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ export const typeOrmConfig: TypeOrmModuleOptions = {
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWD,
database: process.env.DB_DATABASE,
entities: [__dirname + '/../**/*.entity{.js,.ts}'],
entities: [`${__dirname}/../**/*.entity{.js,.ts}`],
synchronize: true,
};
2 changes: 1 addition & 1 deletion BE/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { NestFactory } from '@nestjs/core';
import { Logger } from '@nestjs/common';
import * as cookieParser from 'cookie-parser';
import { AppModule } from './app.module';
import { setupSwagger } from './util/swagger';
import * as cookieParser from 'cookie-parser';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
Expand Down

0 comments on commit b872066

Please sign in to comment.