Skip to content

Commit

Permalink
카카오 로그인 기능 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
HwangHoYoon committed Dec 9, 2023
1 parent e140d19 commit b80b6ba
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
@Slf4j
public class JwtProvider {

private final long ACCESS_TOKEN_EXPIRE_TIME; // 30분
private final long ACCESS_TOKEN_EXPIRE_TIME; // 30분
private final long REFRESH_TOKEN_EXPIRE_TIME; // 7일

private final Key key;
Expand Down
12 changes: 7 additions & 5 deletions src/main/java/com/chwipoClova/common/response/MessageCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,17 @@
@AllArgsConstructor
public enum MessageCode {

SUCCESS_SAVE("SS", "정상적으로 저장되었습니다."),
SUCCESS_SAVE("600", "정상적으로 저장되었습니다."),

SUCCESS_DELETE("SD", "정상적으로 삭제되었습니다."),
SUCCESS_DELETE("601", "정상적으로 삭제되었습니다."),

FAIL_SAVE("FS", "저장에 실패하였습니다."),
FAIL_SAVE("602", "저장에 실패하였습니다."),

FAIL_DELETE("FD", "삭제에 실패하였습니다."),
FAIL_DELETE("603", "삭제에 실패하였습니다."),

SUCCESS("S", "정상적으로 처리되었습니다.")
SUCCESS("604", "정상적으로 처리되었습니다."),

NEW_USER("700", "신규 가입되었습니다.")
;

private static final MessageCode[] VALUES;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType
if (selectedContentType.isCompatibleWith(MediaType.APPLICATION_JSON) && !StringUtils.startsWith(request.getURI().getPath(), "/api-docs/")) {
if (body instanceof CommonException) {
return ResponseUtil.response(((CommonException) body).getErrorCode(), null, ((CommonException) body).getMessage());
} else if (body instanceof CommonResponse) {
return ResponseUtil.response(((CommonResponse) body).getCode(), ((CommonResponse) body).getData(), ((CommonResponse) body).getMessage());
} else {
return ResponseUtil.response(String.valueOf(HttpStatus.OK.value()), body, HttpStatus.OK.getReasonPhrase());
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/chwipoClova/common/utils/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class JwtUtil {
private final UserDetailsServiceImpl userDetailsService;
private final TokenRepository tokenRepository;

private static final long ACCESS_TIME = 2 * 60 * 60 * 1000L;
private static final long ACCESS_TIME = 30 * 60 * 1000L;
private static final long REFRESH_TIME = 14 * 24 * 60 * 60 * 1000L;
public static final String ACCESS_TOKEN = "AccessToken";
public static final String REFRESH_TOKEN = "RefreshToken";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.chwipoClova.user.controller;

import com.chwipoClova.common.response.CommonResponse;
import com.chwipoClova.user.response.UserLoginRes;
import com.chwipoClova.user.response.UserSnsUrlRes;
import com.chwipoClova.user.service.UserService;
Expand Down Expand Up @@ -36,9 +37,14 @@ public class UserController {
public UserSnsUrlRes getKakaoUrl() throws Exception {
return userService.getKakaoUrl();
}
@Hidden

@Operation(summary = "카카오 로그인", description = "카카오 로그인")
@GetMapping("/kakaoCallback")
public UserLoginRes kakaoCallback(@RequestParam(name = "code") String code, HttpServletResponse response) throws Exception {
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "OK")
}
)
public CommonResponse kakaoCallback(@RequestParam(name = "code") String code, HttpServletResponse response) throws Exception {
return userService.kakaoLogin(code, response);
}

Expand Down
70 changes: 38 additions & 32 deletions src/main/java/com/chwipoClova/user/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.chwipoClova.common.dto.Token;
import com.chwipoClova.common.dto.TokenDto;
import com.chwipoClova.common.repository.TokenRepository;
import com.chwipoClova.common.response.CommonResponse;
import com.chwipoClova.common.response.MessageCode;
import com.chwipoClova.common.utils.JwtUtil;
import com.chwipoClova.user.dto.KakaoToken;
import com.chwipoClova.user.dto.KakaoUserInfo;
Expand All @@ -16,6 +18,7 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
Expand Down Expand Up @@ -70,7 +73,7 @@ public UserSnsUrlRes getKakaoUrl() {
return userSnsUrlRes;
}

public UserLoginRes kakaoLogin(String code, HttpServletResponse response) {
public CommonResponse kakaoLogin(String code, HttpServletResponse response) {
KakaoToken kakaoToken = requestAccessToken(code);
KakaoUserInfo kakaoUserInfo = requestOauthInfo(kakaoToken);

Expand All @@ -81,10 +84,40 @@ public UserLoginRes kakaoLogin(String code, HttpServletResponse response) {

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

User userInfoRst;
// 유저 정보가 있다면 업데이트 없으면 등록
if (userInfo.isPresent()) {
userInfoRst = userInfo.get();
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 넣음
setHeader(response, tokenDto);

UserLoginRes userLoginRes = UserLoginRes.builder()
.snsId(userInfoRst.getSnsId())
.userId(userId)
.email(userInfoRst.getEmail())
.name(userInfoRst.getName())
.snsType(userInfoRst.getSnsType())
.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()
Expand All @@ -94,37 +127,10 @@ public UserLoginRes kakaoLogin(String code, HttpServletResponse response) {
.snsType(kakaoUserInfo.getOAuthProvider().getCode())
.regDate(new Date())
.build();
userInfoRst = userRepository.save(user);
}

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);
userRepository.save(user);
return new CommonResponse<>(MessageCode.NEW_USER.getCode(), null, MessageCode.NEW_USER.getMessage());
}

// response 헤더에 Access Token / Refresh Token 넣음
setHeader(response, tokenDto);

return UserLoginRes.builder()
.snsId(userInfoRst.getSnsId())
.userId(userId)
.email(userInfoRst.getEmail())
.name(userInfoRst.getName())
.snsType(userInfoRst.getSnsType())
.regDate(userInfoRst.getRegDate())
.modifyDate(userInfoRst.getModifyDate())
.build();
}

public KakaoToken requestAccessToken(String code) {
Expand Down

0 comments on commit b80b6ba

Please sign in to comment.