Skip to content

Commit

Permalink
♻️ JWT 관련 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
tjdals4716 committed Jul 31, 2024
1 parent 0785c07 commit 5d6253f
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public ResponseEntity<Void> deleteUser(@PathVariable String uid, @Authentication
return ResponseEntity.noContent().build();
}

// 토큰 유효 시간 확인
//토큰 유효 시간 확인
@GetMapping("/token-remaining-time")
public ResponseEntity<Long> getTokenRemainingTime(@AuthenticationPrincipal UserDetails userDetails) {
Long remainingTime = userService.getTokenRemainingTime(userDetails);
Expand All @@ -107,47 +107,42 @@ public ResponseEntity<JWTDTO> getUserWithTokenInfo(@PathVariable String uid, @Re
return ResponseEntity.ok(userWithTokenInfo);
}

// 카카오 로그인 성공 시 호출되는 엔드포인트 (GET)
//카카오 로그인 성공 시 호출되는 엔드포인트 (GET)
@GetMapping("/oauth2/code/kakao")
public ResponseEntity<JWTDTO> kakaoCallback(@RequestParam String code) {
JWTDTO jwtDto = userService.loginWithOAuth2(code);
return ResponseEntity.ok(jwtDto);
}

// 카카오 로그인 성공 시 호출되는 엔드포인트 (POST)
//카카오 로그인 성공 시 호출되는 엔드포인트 (POST)
@PostMapping("/oauth2/code/kakao")
public ResponseEntity<JWTDTO> kakaoLoginPost(@RequestBody OAuth2CodeDTO codeDTO) {
JWTDTO jwtDto = userService.loginWithOAuth2(codeDTO.getCode());
return ResponseEntity.ok(jwtDto);
}

// 카카오 로그인 유저 정보 조회
//카카오 로그인 유저 정보 조회
@GetMapping("/kakao/{uid}")
public ResponseEntity<UserDTO> getKakaoUserInfo(@PathVariable String uid) {
UserDTO user = userService.getKakaoUserInfo(uid);
return ResponseEntity.ok(user);
}

// 카카오 유저 프로필 이미지 설정
//카카오 유저 프로필 이미지 설정
@SneakyThrows
@PostMapping(value = "/image", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<UserDTO> addImageToUser(@RequestPart("userData") String userData, @RequestPart("image") MultipartFile image, @RequestHeader("Authorization") String token) {
public ResponseEntity<UserDTO> addImageToUser(@RequestPart("userData") String userData, @RequestPart("image") MultipartFile image, @AuthenticationPrincipal UserDetails userDetails) {
ObjectMapper mapper = new ObjectMapper();
UserDTO userDTO = mapper.readValue(userData, UserDTO.class);
// 토큰에서 "Bearer" 접두사 제거
String actualToken = token.replace("Bearer ", "");
UserDTO updatedUser = userService.addImageToUser(userDTO.getUid(), image, actualToken);
UserDTO updatedUser = userService.addImageToUser(userDTO.getUid(), image, userDetails);
return ResponseEntity.status(HttpStatus.CREATED).body(updatedUser);
}

//카카오 유저 닉네임 설정
@PostMapping("/nickname/{uid}")
public ResponseEntity<UserDTO> updateNickname(@PathVariable String uid, @RequestBody Map<String, String> request, @RequestHeader("Authorization") String token) {
public ResponseEntity<UserDTO> updateNickname(@PathVariable String uid, @RequestBody Map<String, String> request, @AuthenticationPrincipal UserDetails userDetails) {
String nickname = request.get("nickname");
if (token.startsWith("Bearer ")) {
token = token.substring(7);
}
UserDTO updatedUser = userService.updateNickname(uid, nickname, token);
UserDTO updatedUser = userService.updateNickname(uid, nickname, userDetails);
return ResponseEntity.status(HttpStatus.OK).body(updatedUser);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.MangoWafflee.Global.Config.JWT;

import com.example.MangoWafflee.Service.UserDetailsServiceImpl;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
Expand Down Expand Up @@ -33,13 +34,9 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
String token = null;
String uid = null;

if (header != null && header.startsWith("Bearer ")) {
token = header.substring(7);
try {
uid = jwtTokenProvider.getUidFromToken(token);
} catch (Exception e) {
logger.error("토큰에서 사용자 ID를 추출하는 중 오류 발생", e);
}
if (header != null) {
token = header;
uid = jwtTokenProvider.getUidFromToken(token);
}

if (uid != null && SecurityContextHolder.getContext().getAuthentication() == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ public interface UserService {
Long refreshToken(UserDetails userDetails);
Long getTokenRemainingTime(UserDetails userDetails);
JWTDTO getUserWithTokenInfo(String uid, String token);
UserDTO updateNickname(String uid, String nickname, String token);
UserDTO updateNickname(String uid, String nickname, UserDetails userDetails);
String getAccessToken(String code);
JWTDTO loginWithOAuth2(String code);
UserDTO getKakaoUserInfo(String uid);
UserDTO addImageToUser(String uid, MultipartFile image, String token);
UserDTO addImageToUser(String uid, MultipartFile image, UserDetails userDetails);
UserDTO getUserById(Long userId);
}
37 changes: 11 additions & 26 deletions src/main/java/com/example/MangoWafflee/Service/UserServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ public void logKakaoOAuthSettings() {
logger.info("Kakao OAuth 설정 값 - clientId : {}, clientSecret : {}, redirectUri : {}", kakaoOAuthProperties.getClientId(), kakaoOAuthProperties.getClientSecret(), kakaoOAuthProperties.getRedirectUri());
}

// 카카오 인가 코드로 액세스 토큰 요청
//카카오 인가 코드로 액세스 토큰 요청
public String getAccessToken(String code) {
String url = "https://kauth.kakao.com/oauth/token";
HttpHeaders headers = new HttpHeaders();
Expand Down Expand Up @@ -211,7 +211,7 @@ public String getAccessToken(String code) {
}
}

// 액세스 토큰으로 사용자 정보 요청
//액세스 토큰으로 사용자 정보 요청
public Map<String, Object> getUserInfo(String accessToken) {
String url = "https://kapi.kakao.com/v2/user/me";
HttpHeaders headers = new HttpHeaders();
Expand Down Expand Up @@ -287,16 +287,10 @@ public UserDTO getKakaoUserInfo(String uid) {

//카카오 유저 프로필 이미지 설정
@Override
public UserDTO addImageToUser(String uid, MultipartFile image, String token) {
// 토큰 검증
if (!jwtTokenProvider.validateToken(token)) {
throw new RuntimeException("유효하지 않은 토큰입니다.");
}

// 토큰에서 사용자 정보 추출
String tokenUid = jwtTokenProvider.getUidFromToken(token);
if (!tokenUid.equals(uid)) {
throw new RuntimeException("토큰이 사용자와 일치하지 않습니다.");
public UserDTO addImageToUser(String uid, MultipartFile image, UserDetails userDetails) {
// 사용자 인증
if (!userDetails.getUsername().equals(uid)) {
throw new RuntimeException("권한이 없습니다.");
}

UserEntity userEntity = userRepository.findByUid(uid)
Expand Down Expand Up @@ -331,10 +325,6 @@ public UserDTO addImageToUser(String uid, MultipartFile image, String token) {
storage.create(blobInfo, image.getBytes());
String imageUrl = "https://storage.cloud.google.com/mangowafflee/" + fileName;
userEntity.setImage(imageUrl);
// 기존 닉네임 유지
if (userEntity.getNickname() == null) {
userEntity.setNickname(userEntity.getNickname());
}
userRepository.save(userEntity);
logger.info("사용자 프로필 이미지 업데이트 완료! " + userEntity);
} catch (IOException e) {
Expand All @@ -348,16 +338,10 @@ public UserDTO addImageToUser(String uid, MultipartFile image, String token) {

//카카오 유저 닉네임 설정
@Override
public UserDTO updateNickname(String uid, String nickname, String token) {
// 토큰 검증
if (!jwtTokenProvider.validateToken(token)) {
throw new RuntimeException("유효하지 않은 토큰입니다.");
}

// 토큰에서 사용자 정보 추출
String tokenUid = jwtTokenProvider.getUidFromToken(token);
if (!tokenUid.equals(uid)) {
throw new RuntimeException("토큰이 사용자와 일치하지 않습니다.");
public UserDTO updateNickname(String uid, String nickname, UserDetails userDetails) {
// 사용자 인증
if (!userDetails.getUsername().equals(uid)) {
throw new RuntimeException("권한이 없습니다.");
}

UserEntity userEntity = userRepository.findByUid(uid)
Expand All @@ -371,6 +355,7 @@ public UserDTO updateNickname(String uid, String nickname, String token) {
}



@Override
public UserDTO getUserById(Long userId) {
UserEntity userEntity = userRepository.findById(userId)
Expand Down

0 comments on commit 5d6253f

Please sign in to comment.