Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BE] kakao 로그인시 회원 가입 기능 추가 #86

Merged
merged 4 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions BE/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,14 @@ export class AuthController {
@ApiOperation({ summary: 'Kakao 로그인 API' })
@Get('/kakao')
@UseGuards(AuthGuard('kakao'))
async kakaoLogin(
@Body() authCredentialsDto: AuthCredentialsDto,
@Res() res: Response,
) {
async kakaoLogin(@Req() req: Request, @Res() res: Response) {
const authCredentialsDto: AuthCredentialsDto = {
Copy link
Collaborator

@sieunie sieunie Nov 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 맞다 이거 말씀드리려 했는데 깜빡했네요!!
authCredentialsDto를 카카오 로그인에서도 사용하고 일반 로그인에서도 사용하는 걸로 알고 있는데 의도하신 부분 맞을까요?
저희 스웨거 보니까 아래처럼 떠서 질문드려요...!
image

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아..! 잘못 이해 했는데 둘다 똑같은 Dto를 사용하고 있긴 합니다..! 뭔가 swagger 상에서 보면 이상하긴 하네요

email: req.user.email,
kakaoId: req.user.kakaoId,
};
const { accessToken, refreshToken } =
await this.authService.kakaoLoginUser(authCredentialsDto);

res.cookie('accessToken', accessToken, { httpOnly: true });
res.cookie('refreshToken', refreshToken, { httpOnly: true });
res.cookie('isRefreshToken', true, { httpOnly: true });
Expand Down
7 changes: 7 additions & 0 deletions BE/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ export class AuthService {
async kakaoLoginUser(
authCredentialsDto: AuthCredentialsDto,
): Promise<{ accessToken: string; refreshToken: string }> {
const user = await this.userRepository.findOne({
where: { kakaoId: authCredentialsDto.kakaoId },
});

if (!user) {
await this.userRepository.registerKakaoUser(authCredentialsDto);
}
return this.getJWTToken(authCredentialsDto);
}

Expand Down
2 changes: 2 additions & 0 deletions BE/src/auth/dto/auth-credentials.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,15 @@ export class AuthCredentialsDto {

@ApiProperty({
description: '카카오 ID',
required: false,
})
@IsString()
@IsOptional()
kakaoId?: string;

@ApiProperty({
description: '카카오 액세스 토큰',
required: false,
})
@IsString()
@IsOptional()
Expand Down
6 changes: 6 additions & 0 deletions BE/src/auth/strategy/kakao.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ interface KakaoProfile extends Profile {
id: number;
_json: {
id: number;
kakao_account: {
email: string;
};
};
}

Expand Down Expand Up @@ -44,7 +47,10 @@ export class KakaoStrategy extends PassportStrategy<Strategy>(
try {
// eslint-disable-next-line no-underscore-dangle
const kakaoId = profile._json.id;
// eslint-disable-next-line no-underscore-dangle
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 이런 린트 규칙 오류는 바로바로 추가하셔도 괜찮을 거 같아요!
우리가 코딩 잘못해서 생긴 오류가 아니라 kakao OAuth 쓰면서 있는 값 그대로 가지고 오려고 했는데 린트가 마음에 안든다고 고치라고 하는거니까!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

맞아요! 그래서 정말 넣기 싫었지만 어쩔 수 없이 ignore 하고 있습니다 ㅠ

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

린트 규칙에 바로 추가하셔서 깃에 올리셔도 될 거 같아요!
off로 해가지구

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여긴 특수한 경우지만 보통의 경우엔 __ 쓰는건 지양해야할 거 같아서 린트 규칙에 추가하진 않았는데 추가할까요?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

다른 외부 API 사용할 때도 저런 이슈가 발생하면 ignore 한줄 한줄 또 써야 하니.. 이번 프로젝트에서는 off 해도 괜찮을 것 같습니다.
저는 이미 한투 api 에서 _ 로 구분하는거 카멜케이스 등으로 바꿔써라고 지적하는거 린트 규칙에 off로 바꿨어요..ㅎ

const { email } = profile._json.kakao_account;
const user = {
email,
kakaoId,
};
done(null, user);
Expand Down
6 changes: 3 additions & 3 deletions BE/src/auth/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export class User extends BaseEntity {
@Column({ default: false })
tutorial: boolean;

@Column({ default: -1 })
kakaoId: number;
@Column({ default: '' })
kakaoId: string;

@Column({ default: '' })
currentRefreshToken: string;
Expand All @@ -25,7 +25,7 @@ export class User extends BaseEntity {
currentRefreshTokenExpiresAt: Date;

toAuthCredentialsDto(): AuthCredentialsDto {
if (this.kakaoId === -1) {
if (this.kakaoId === '') {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 비어있는 문자열은 if (!this.kakaoId) 이런 식으로 체크해도 되는 거로 알고 있는데 명시적으로 하기 위해서 이렇게 하신걸까요?!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

엇 그런가요? 저는 몰랐던 내용이라.. 이후에 리팩토링할 때 차차 수정해보겠습니다. 감사합니다!

Copy link
Collaborator

@uuuo3o uuuo3o Nov 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

명시적으로 저렇게 나타내주시는 분들도 많더라구요! 딱히 수정할 필요는 없어보이지만, 만약에 db에서 kakaoId가 nullable한 값이다! 이런거면
!this.kakaoId 체크하는게 코드 수정할 필요가 없으니 편하긴 하죠 ㅎㅎ

js, ts에서 빈값 체크

이런 식으로 if문으로 체크 했을 때 빈문자열도 null 같은 친구들이랑 동일하게 false 값으로 나와서 제가 말씀드린거처럼 확인이 가능합니다!

return {
email: this.email,
password: this.password,
Expand Down
8 changes: 8 additions & 0 deletions BE/src/auth/user.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ export class UserRepository extends Repository<User> {
await this.save(user);
}

async registerKakaoUser(authCredentialsDto: AuthCredentialsDto) {
const { kakaoId, email } = authCredentialsDto;
const salt: string = await bcrypt.genSalt();
const hashedPassword: string = await bcrypt.hash(String(kakaoId), salt);
const user = this.create({ email, kakaoId, password: hashedPassword });
await this.save(user);
}

async updateUserWithRefreshToken(
id: number,
{
Expand Down
1 change: 0 additions & 1 deletion BE/src/stock/order/stock-order.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
Injectable,
} from '@nestjs/common';
import { NotFoundError } from 'rxjs';
import { Injectable } from '@nestjs/common';
import { StockOrderRequestDto } from './dto/stock-order-request.dto';
import { StockOrderRepository } from './stock-order.repository';
import { TradeType } from './enum/trade-type';
Expand Down
3 changes: 2 additions & 1 deletion BE/src/types/express.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { UUID } from 'crypto';
declare module 'express' {
interface Request extends Req {
user: {
kakaoId?: number;
kakaoId?: string;
userId?: UUID;
email?: string;
};
}
}
Loading