Skip to content

Commit

Permalink
Merge pull request #29 from potenday-project/develop
Browse files Browse the repository at this point in the history
카카오 로그인 운영 개발 분리
  • Loading branch information
HwangHoYoon authored Dec 16, 2023
2 parents b11f0cd + 7e7a5f6 commit dbb92ca
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 2 deletions.
2 changes: 1 addition & 1 deletion server_config
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public SecurityFilterChain securityFilterChain(final @NotNull HttpSecurity http
authorize
//.requestMatchers("/**").permitAll().anyRequest().authenticated()
.requestMatchers("/"
,"/user/getKakaoUrl","/user/kakaoLogin","/user/kakaoCallback","/user/logout"
,"/user/getKakaoUrl","/user/kakaoLogin", "/user/getKakaoDevUrl", "/user/kakaoDevLogin", "/user/kakaoCallback","/user/logout"
).permitAll().anyRequest().authenticated()
//.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()

Expand Down
22 changes: 22 additions & 0 deletions src/main/java/com/chwipoClova/user/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ public UserSnsUrlRes getKakaoUrl() throws Exception {
return userService.getKakaoUrl();
}

@Operation(summary = "카카오 개발 로그인 URL", description = "카카오 개발 로그인 URL")
@GetMapping("/getKakaoDevUrl")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "OK")
}
)
public UserSnsUrlRes getKakaoDevUrl() throws Exception {
return userService.getKakaoLocalUrl();
}

@Operation(summary = "카카오 로그인", description = "카카오 로그인 (카카오 로그인 URL 호출해서 로그인 성공하면 나오는 코드를 입력)")
@GetMapping("/kakaoLogin")
@ApiResponses(value = {
Expand All @@ -66,6 +76,18 @@ public CommonResponse kakaoLogin(@Schema(description = "로그인코드", exampl
return userService.kakaoLogin(code, response);
}

@Operation(summary = "카카오 개발 로그인", description = "카카오 개발 로그인 (카카오 로그인 URL 호출해서 로그인 성공하면 나오는 코드를 입력)")
@GetMapping("/kakaoDevLogin")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = UserLoginRes.class))),
@ApiResponse(responseCode = "700", description = "신규 가입되었습니다.", content = @Content(schema = @Schema(implementation = String.class)))
}
)
public CommonResponse kakaoDevLogin(@Schema(description = "로그인코드", example = "1", name = "code") @RequestParam(name = "code") String code, HttpServletResponse response) throws Exception {
return userService.kakaoDevLogin(code, response);
}


@Hidden
@Operation(summary = "카카오 로그인 콜백", description = "카카오 로그인 콜백")
@GetMapping("/kakaoCallback")
Expand Down
98 changes: 98 additions & 0 deletions src/main/java/com/chwipoClova/user/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ public class UserService {
@Value("${kakao.redirect_uri}")
private String redirectUri;

@Value("${kakao.redirect_local_uri}")
private String redirectLocalUri;


public UserSnsUrlRes getKakaoUrl() {
String kakaoUrl = kakaoAuthUrl + "?response_type=code" + "&client_id=" + clientId
Expand Down Expand Up @@ -229,4 +232,99 @@ public UserInfoRes selectUserInfoForUserId(Long userId) {
.modifyDate(user.getModifyDate())
.build();
}

public UserSnsUrlRes getKakaoLocalUrl() {
String kakaoUrl = kakaoAuthUrl + "?response_type=code" + "&client_id=" + clientId
+ "&redirect_uri=" + redirectLocalUri;
UserSnsUrlRes userSnsUrlRes = UserSnsUrlRes.builder()
.url(kakaoUrl)
.build();
return userSnsUrlRes;
}

public CommonResponse kakaoDevLogin(String code, HttpServletResponse response) {
KakaoToken kakaoToken = requestDevAccessToken(code);
KakaoUserInfo kakaoUserInfo = requestOauthInfo(kakaoToken);

long snsId = kakaoUserInfo.getId();
String email = kakaoUserInfo.getEmail();
String nickname = kakaoUserInfo.getNickname();
Integer snsType = kakaoUserInfo.getOAuthProvider().getCode();
String thumbnailImageUrl = kakaoUserInfo.getThumbnailImageUrl();
String profileImageUrl = kakaoUserInfo.getProfileImageUrl();

Optional<User> userInfo = userRepository.findBySnsTypeAndSnsId(snsType, snsId);

// 유저 정보가 있다면 업데이트 없으면 등록
if (userInfo.isPresent()) {
User userInfoRst = userInfo.get();

Long userId = userInfoRst.getUserId();

TokenDto tokenDto = jwtUtil.createAllToken(String.valueOf(userId));

// Refresh토큰 있는지 확인
Optional<Token> refreshToken = tokenRepository.findByUserUserId(userInfoRst.getUserId());

// 있다면 새토큰 발급후 업데이트
// 없다면 새로 만들고 디비 저장
if(refreshToken.isPresent()) {
tokenRepository.save(refreshToken.get().updateToken(tokenDto.getRefreshToken()));
}else {
Token newToken = new Token(tokenDto.getRefreshToken(), User.builder().userId(userInfoRst.getUserId()).build());
tokenRepository.save(newToken);
}

// response 헤더에 Access Token / Refresh Token 넣음
jwtUtil.setResonseJwtToken(response, tokenDto.getAccessToken(), tokenDto.getRefreshToken());

UserLoginRes userLoginRes = UserLoginRes.builder()
.snsId(userInfoRst.getSnsId())
.userId(userId)
.email(userInfoRst.getEmail())
.name(userInfoRst.getName())
.snsType(userInfoRst.getSnsType())
.thumbnailImage(userInfoRst.getThumbnailImage())
.profileImage(userInfoRst.getProfileImage())
.regDate(userInfoRst.getRegDate())
.modifyDate(userInfoRst.getModifyDate())
.build();

return new CommonResponse<>(String.valueOf(HttpStatus.OK.value()), userLoginRes, HttpStatus.OK.getReasonPhrase());
} else {
log.info("신규유저 등록 {}", nickname);
User user = User.builder()
.snsId(snsId)
.email(email)
.name(nickname)
.snsType(snsType)
.thumbnailImage(thumbnailImageUrl)
.profileImage(profileImageUrl)
.regDate(new Date())
.build();
userRepository.save(user);
return new CommonResponse<>(MessageCode.NEW_USER.getCode(), null, MessageCode.NEW_USER.getMessage());
}
}

private KakaoToken requestDevAccessToken(String code) {

HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> body = new LinkedMultiValueMap<>();;
body.add("grant_type", grantType);
body.add("client_id", clientId);
body.add("client_secret", clientSecret);
body.add("redirect_uri", redirectLocalUri);
body.add("code", code);

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, httpHeaders);

KakaoToken response = restTemplate.postForObject(tokenUrl, request, KakaoToken.class);

// TODO 토큰 정보를 가져오지 못하면 예외발생 처리 추가
assert response != null;
return response;
}
}

0 comments on commit dbb92ca

Please sign in to comment.