Skip to content

Commit

Permalink
Refactor : kakaoId -> socialId Renaming for naver login
Browse files Browse the repository at this point in the history
  • Loading branch information
Suhun0331 committed Dec 18, 2024
1 parent 723189e commit 2b2c8fa
Show file tree
Hide file tree
Showing 12 changed files with 61 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public ResponseEntity<Map<String, Object>> kakaoCallback(@RequestParam("code") S
Map<String, Object> tokens = new HashMap<>();
tokens.put("Token", kakaoAuthService.generateTokens(member));

log.info("카카오 로그인 성공: 사용자 이름={}, 카카오 ID={}", member.getName(), member.getKakaoId());
log.info("카카오 로그인 성공: 사용자 이름={}, 카카오 ID={}", member.getName(), member.getSocialId());
return ResponseEntity.ok(tokens);

} catch (Exception e) {
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/umc/kkijuk/server/auth/jwt/JwtFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,16 @@ protected void doFilterInternal(

if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
kakaoId = jwtUtil.extractKakaoId(jwt);
kakaoId = jwtUtil.extractSocialId(jwt);
}

if (kakaoId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
Member member = memberRepository.findByKakaoId(kakaoId).orElse(null);
Member member = memberRepository.findBySocialId(kakaoId).orElse(null);

if (member != null && jwtUtil.validateToken(jwt, String.valueOf(member.getKakaoId()))) {
if (member != null && jwtUtil.validateToken(jwt, String.valueOf(member.getSocialId()))) {
UserDetails userDetails =
new org.springframework.security.core.userdetails.User(
String.valueOf(member.getKakaoId()),
String.valueOf(member.getSocialId()),
"",
Collections.singletonList(new SimpleGrantedAuthority(member.getRole().name())));

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/umc/kkijuk/server/auth/jwt/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public boolean validateToken(String token, String socialId) {
}
}

public Long extractKakaoId(String token) {
public Long extractSocialId(String token) {
return Long.valueOf(
Jwts.parserBuilder()
.setSigningKey(getSigningKey())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,15 @@ public Member processKakaoUser(String accessToken) {

log.info("카카오 사용자 정보 추출 - 이메일: {}, 이름: {}, 카카오 ID: {}, 전화번호: {}, 생년월일: {}", email, name, kakaoId, phoneNumber, birthDate);

return memberRepository.findByKakaoId(kakaoId)
return memberRepository.findBySocialId(kakaoId)
.orElseGet(() -> {
log.info("신규 사용자 생성 - 카카오 ID: {}", kakaoId);
return memberService.createUserWithKakaoId(kakaoId, kakaoUserInfo);
});
}

public Map<String, String> generateTokens(Member member) {
String kakaoId = String.valueOf(member.getKakaoId());
String kakaoId = String.valueOf(member.getSocialId());

String accessToken = jwtUtil.createAccessToken(kakaoId);
String refreshToken = jwtUtil.createRefreshToken(kakaoId);
Expand Down
30 changes: 28 additions & 2 deletions src/main/java/umc/kkijuk/server/common/LoginUser.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,46 @@
package umc.kkijuk.server.common;

import lombok.Getter;
import umc.kkijuk.server.auth.jwt.JwtUtil;
import umc.kkijuk.server.member.domain.Member;
import umc.kkijuk.server.member.service.MemberService;

@Getter
public class LoginUser {

private final JwtUtil jwtUtil;
private final MemberService memberService;
private Long id;
private static final LoginUser LOGIN_USER = new LoginUser(1L);

public LoginUser(Long id) {
public LoginUser(JwtUtil jwtUtil, MemberService memberService, Long id) {
this.jwtUtil = jwtUtil;
this.memberService = memberService;
this.id = id;
}

private static final LoginUser LOGIN_USER = new LoginUser( null, null,1L);


public static LoginUser get() {
return LOGIN_USER;
}

public Long extractMemberId(String bearerToken) {
if (bearerToken == null || !bearerToken.startsWith("Bearer ")) {
throw new IllegalArgumentException("Authorization 헤더에 올바른 토큰이 없습니다.");
}

String token = bearerToken.substring(7);
Long socialId = jwtUtil.extractSocialId(token);

if (socialId == null) {
throw new IllegalArgumentException("유효하지 않은 토큰입니다.");
}

Member member = memberService.findBySocialId(socialId);
return member.getId();
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -15,13 +13,11 @@
import umc.kkijuk.server.auth.jwt.JwtUtil;
import umc.kkijuk.server.common.LoginUser;
import umc.kkijuk.server.member.controller.response.*;
import umc.kkijuk.server.member.domain.Member;
import umc.kkijuk.server.member.dto.*;
import umc.kkijuk.server.member.emailauth.MailServiceImpl;
import umc.kkijuk.server.member.service.MemberService;
import lombok.RequiredArgsConstructor;

import java.util.Collections;
import java.util.List;


Expand Down Expand Up @@ -141,7 +137,7 @@ public ResponseEntity<MemberEmailResponse> getEmail() {
public ResponseEntity<AuthResponse> refreshToken(@RequestBody RefreshTokenRequest request) {

String refreshToken = request.getRefreshToken();
Long kakaoId = jwtUtil.extractKakaoId(refreshToken);
Long kakaoId = jwtUtil.extractSocialId(refreshToken);

AuthResponse response = memberService.refreshAuthToken(refreshToken, kakaoId);

Expand All @@ -159,8 +155,8 @@ public ResponseEntity<AuthResponse> refreshToken(@RequestBody RefreshTokenReques
summary = "내 정보 조회",
description = "마이페이지에서 내 정보들을 가져옵니다.")
@GetMapping("/myPage/info")
public ResponseEntity<MemberInfoResponse> getInfo() {
Long loginUser = LoginUser.get().getId();
public ResponseEntity<MemberInfoResponse> getInfo(@RequestHeader("Authorization") String bearerToken) {
Long loginUser = LoginUser.get().extractMemberId(bearerToken);
MemberInfoResponse memberInfoResponse = memberService.getMemberInfo(loginUser);
return ResponseEntity
.status(HttpStatus.OK)
Expand Down Expand Up @@ -200,7 +196,7 @@ public ResponseEntity<Boolean> postField(@RequestBody MemberFieldDto memberField
@Operation(summary = "로그아웃", description = "사용자 로그아웃")
@PostMapping("/logout")
public ResponseEntity<String> logout(@RequestHeader("Authorization") String token) {
Long kakaoId = jwtUtil.extractKakaoId(token.substring(7));
Long kakaoId = jwtUtil.extractSocialId(token.substring(7));
memberService.invalidateRefreshToken(kakaoId);
return ResponseEntity.ok("로그아웃 완료");
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/umc/kkijuk/server/member/domain/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class Member extends BaseEntity {
@Column(name = "member_id")
private Long id;

private Long kakaoId;
private Long socialId;

@NotNull
private String email;
Expand Down Expand Up @@ -98,8 +98,8 @@ public void deleteRecruitTag(String tag) {
this.recruitTags.remove(tag);
}

public void setKakaoId(Long kakaoId) {
this.kakaoId = kakaoId;
public void setSocialId(Long kakaoId) {
this.socialId = kakaoId;
}

public void setEmail(String email) {this.email = email;}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ public interface MemberJpaRepository extends JpaRepository<Member, Long>{
Optional<Member> findById(Long id);
Optional<Member> findByEmail(String email);
Optional<Member> findByPhoneNumber(String phoneNumber);
Optional<Member> findByKakaoId(Long kakaoId);
Optional<Member> findBySocialId(Long socialId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ public interface MemberRepository {
Optional<Member> findByEmail(String email);
Member save(Member member);
Optional<Member> findByPhoneNumber(String phoneNumber);
Optional<Member> findByKakaoId(Long kakaoId);
Optional<Member> findBySocialId(Long socialId);
void deleteById(Long id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ public Optional<Member> findByPhoneNumber(String phoneNumber) {
return memberJpaRepository.findByPhoneNumber(phoneNumber);
}
@Override
public Optional<Member> findByKakaoId(Long kakaoId) {
return memberJpaRepository.findByKakaoId(kakaoId);
public Optional<Member> findBySocialId(Long socialId) {
return memberJpaRepository.findBySocialId(socialId);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
package umc.kkijuk.server.member.service;

import umc.kkijuk.server.auth.dto.AuthResponse;
import umc.kkijuk.server.auth.dto.RefreshTokenRequest;
import umc.kkijuk.server.member.controller.response.EmailAuthResponse;
import umc.kkijuk.server.member.controller.response.MemberEmailResponse;
import umc.kkijuk.server.member.controller.response.MemberInfoResponse;
import umc.kkijuk.server.member.controller.response.MemberStateResponse;
import umc.kkijuk.server.member.domain.Member;
import umc.kkijuk.server.member.dto.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public interface MemberService {
Member getById(Long memberId);
Expand All @@ -37,8 +33,7 @@ public interface MemberService {
void invalidateRefreshToken(Long kakaoId);
void updateRefreshToken(Long kakaoId, String refreshToken);
Long extractMemberId(String bearerToken);
Member findByKakaoId(Long kakaoId);
Member findMemberByKakaoId(Long kakaoId);
Member findBySocialId(Long socialId);
AuthResponse refreshAuthToken(String refreshToken, Long kakaoId);

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import umc.kkijuk.server.auth.dto.AuthResponse;
import umc.kkijuk.server.auth.dto.RefreshTokenRequest;
import umc.kkijuk.server.auth.jwt.JwtUtil;
import umc.kkijuk.server.common.domian.exception.*;
import umc.kkijuk.server.member.controller.response.EmailAuthResponse;
import umc.kkijuk.server.member.controller.response.MemberEmailResponse;
import umc.kkijuk.server.member.controller.response.MemberInfoResponse;
import umc.kkijuk.server.member.controller.response.MemberStateResponse;
Expand Down Expand Up @@ -229,7 +227,7 @@ public Member createUserWithKakaoId(Long kakaoId, Map<String, Object> kakaoUserI
}

Member newMember = new Member();
newMember.setKakaoId(kakaoId);
newMember.setSocialId(kakaoId);
newMember.setEmail(email);
newMember.setName(name);
newMember.setPhoneNumber(phoneNumber);
Expand All @@ -243,9 +241,9 @@ public Member createUserWithKakaoId(Long kakaoId, Map<String, Object> kakaoUserI
@Override
@Transactional
public MemberInfoResponse getMemberInfo(Long kakaoId) {
Member member = findMemberByKakaoId(kakaoId);
Member member = this.findBySocialId(kakaoId);
return MemberInfoResponse.builder()
.kakaoId(member.getKakaoId())
.kakaoId(member.getSocialId())
.email(member.getEmail())
.name(member.getName())
.phoneNumber(member.getPhoneNumber())
Expand All @@ -258,15 +256,15 @@ public MemberInfoResponse getMemberInfo(Long kakaoId) {
@Override
@Transactional
public void invalidateRefreshToken(Long kakaoId) {
Member member = findMemberByKakaoId(kakaoId);
Member member = this.findBySocialId(kakaoId);
member.setRefreshToken(null);
log.info("Refresh Token 삭제 완료 - Kakao ID: {}", kakaoId);
}

@Override
@Transactional
public void updateRefreshToken(Long kakaoId, String refreshToken) {
Member member = findMemberByKakaoId(kakaoId);
Member member = this.findBySocialId(kakaoId);
member.setRefreshToken(refreshToken);
log.info("Refresh Token 업데이트 완료 - Kakao ID: {}, Refresh Token: {}", kakaoId, refreshToken);
}
Expand All @@ -285,35 +283,29 @@ public Long extractMemberId(String bearerToken) {
throw new IllegalArgumentException("Authorization 헤더에 올바른 토큰이 없습니다.");
}

Long kakaoId = jwtUtil.extractKakaoId(bearerToken.substring(7));
return findMemberByKakaoId(kakaoId).getId();
Long kakaoId = jwtUtil.extractSocialId(bearerToken.substring(7));
return this.findBySocialId(kakaoId).getId();
}

@Override
@Transactional
public Member findByKakaoId(Long kakaoId) {
return findMemberByKakaoId(kakaoId);
}

@Override
@Transactional
public Member findMemberByKakaoId(Long kakaoId) {
return memberRepository.findByKakaoId(kakaoId)
.orElseThrow(() -> new RuntimeException("Member not found with Kakao ID: " + kakaoId));
public Member findBySocialId(Long SocialId) {
return memberRepository.findBySocialId(SocialId)
.orElseThrow(() -> new RuntimeException("Member not found with Social ID: " + SocialId));
}

@Override
@Transactional
public AuthResponse refreshAuthToken(String refreshToken, Long kakaoId) {
// Refresh Token 검증
if (!jwtUtil.validateToken(refreshToken, String.valueOf(kakaoId))) {
log.warn("유효하지 않은 Refresh Token - Kakao ID: {}", kakaoId);
log.warn("유효하지 않은 Refresh Token - Social ID: {}", kakaoId);
throw new IllegalArgumentException("유효하지 않은 Refresh Token입니다.");
}

// Member 조회
Member member = memberRepository.findByKakaoId(kakaoId)
.orElseThrow(() -> new RuntimeException("Member not found with Kakao ID: " + kakaoId));
Member member = memberRepository.findBySocialId(kakaoId)
.orElseThrow(() -> new RuntimeException("Member not found with Social ID: " + kakaoId));

// 새로운 Access Token과 Refresh Token 발급 (Refresh Token Rotation)
String newAccessToken = jwtUtil.createAccessToken(String.valueOf(kakaoId));
Expand Down

0 comments on commit 2b2c8fa

Please sign in to comment.