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

feat: kakao-login 구현 완료 #17

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ public enum ErrorMessage {
/**
* user
*/
CANT_GET_USERINFO("유저 아이디를 갖고올 수 없습니다.");
CANT_GET_USERINFO("유저 아이디를 갖고올 수 없습니다."),

/*
social login
*/
CHECK_KAKAO_USER_FAIL("카카오 계정 확인 실패");

private final String message;
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ public enum ResponseMessage {
/*
user
*/
GET_USER_INFO("유저 정보 갖고오기 성공");
GET_USER_INFO("유저 정보 갖고오기 성공"),

/*
social login
*/
SOCIAL_SIGNIN_SUCCESS("소셜 로그인 성공");

private final String message;
}
16 changes: 10 additions & 6 deletions src/main/java/com/with/picme/controller/AuthController.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package com.with.picme.controller;

import com.with.picme.common.ApiResponse;
import com.with.picme.dto.auth.AuthSignInRequestDto;
import com.with.picme.dto.auth.AuthSignInResponseDto;
import com.with.picme.dto.auth.AuthSignUpRequestDto;
import com.with.picme.dto.auth.AuthSignUpResponseDto;
import com.with.picme.dto.auth.*;
import com.with.picme.service.AuthServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
Expand All @@ -13,8 +10,8 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import static com.with.picme.common.message.ResponseMessage.SUCCESS_SIGN_IN;
import static com.with.picme.common.message.ResponseMessage.SUCCESS_SIGN_UP;

import static com.with.picme.common.message.ResponseMessage.*;

@RestController
@RequestMapping("/auth")
Expand All @@ -33,4 +30,11 @@ public ResponseEntity<ApiResponse> signInUser(@RequestBody AuthSignInRequestDto
AuthSignInResponseDto response = authService.signInUser(request);
return ResponseEntity.ok(ApiResponse.success(SUCCESS_SIGN_IN.getMessage(), response));
}

@PostMapping("/kakao/signin")
public ResponseEntity<ApiResponse> loginSocialUser(@Valid @RequestBody AuthSocialSignInRequestDto request){
AuthSignUpResponseDto response = authService.loginSocialUser(request);
return ResponseEntity.ok(ApiResponse.success(SOCIAL_SIGNIN_SUCCESS.getMessage(), response));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.with.picme.dto.auth;

import javax.validation.constraints.NotBlank;

public record AuthSocialSignInRequestDto (
Long uid,
@NotBlank(message = "소셜타입은 필수 입력값입니다.")
String socialType
){
}
20 changes: 20 additions & 0 deletions src/main/java/com/with/picme/dto/auth/kakao/KakaoUser.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.with.picme.dto.auth.kakao;

import com.with.picme.entity.ProviderType;
import lombok.Builder;

@Builder
public record KakaoUser(
Long userId,
String email,
ProviderType providerType
) {
public static KakaoUser of(Long userId, String email){
return KakaoUser
.builder()
.userId(userId)
.email(email)
.providerType(ProviderType.kakao)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@
@Setter
@Entity
@NoArgsConstructor
@Table(name = "\"AuthenticationProvider\"")
public class AuthenticationProvider {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id")
private Long id;

@Column(name="provider_type")
@Enumerated(EnumType.STRING)
private ProviderType provider;

@OneToOne(fetch = FetchType.LAZY)
Expand Down
6 changes: 5 additions & 1 deletion src/main/java/com/with/picme/entity/ProviderType.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.with.picme.entity;

import javax.persistence.EnumType;
import javax.persistence.Enumerated;

public enum ProviderType {
@Enumerated(EnumType.STRING)
kakao, naver, google
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.with.picme.repository;

import com.with.picme.entity.AuthenticationProvider;
import com.with.picme.entity.ProviderType;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;


import java.util.Optional;

public interface AuthenticationProviderRepository extends JpaRepository<AuthenticationProvider, Long> {
@EntityGraph(attributePaths = "user")
Optional<AuthenticationProvider> findByIdAndProvider(Long id, ProviderType providerType);
}
7 changes: 3 additions & 4 deletions src/main/java/com/with/picme/service/AuthService.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
package com.with.picme.service;

import com.with.picme.dto.auth.AuthSignInRequestDto;
import com.with.picme.dto.auth.AuthSignInResponseDto;
import com.with.picme.dto.auth.AuthSignUpRequestDto;
import com.with.picme.dto.auth.AuthSignUpResponseDto;
import com.with.picme.dto.auth.*;

public interface AuthService {

AuthSignUpResponseDto createUser(AuthSignUpRequestDto request);
AuthSignInResponseDto signInUser(AuthSignInRequestDto request);

AuthSignUpResponseDto loginSocialUser(AuthSocialSignInRequestDto reqeust);
}
46 changes: 42 additions & 4 deletions src/main/java/com/with/picme/service/AuthServiceImpl.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package com.with.picme.service;

import com.with.picme.common.message.ErrorMessage;
import com.with.picme.config.SaltEncrypt;
import com.with.picme.config.jwt.JwtTokenProvider;
import com.with.picme.config.jwt.UserAuthentication;
import com.with.picme.dto.auth.AuthSignInRequestDto;
import com.with.picme.dto.auth.AuthSignInResponseDto;
import com.with.picme.dto.auth.AuthSignUpRequestDto;
import com.with.picme.dto.auth.AuthSignUpResponseDto;
import com.with.picme.dto.auth.*;
import com.with.picme.dto.auth.kakao.KakaoUser;
import com.with.picme.entity.AuthenticationProvider;
import com.with.picme.entity.User;
import com.with.picme.repository.AuthenticationProviderRepository;
import com.with.picme.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
Expand All @@ -16,6 +17,9 @@

import javax.persistence.EntityNotFoundException;

import java.util.Objects;
import java.util.Optional;

import static com.with.picme.common.message.ErrorMessage.*;

@RequiredArgsConstructor
Expand All @@ -25,6 +29,7 @@ public class AuthServiceImpl implements AuthService {
private final UserRepository userRepository;
private final SaltEncrypt saltEncrypt;
private final JwtTokenProvider tokenProvider;
private final AuthenticationProviderRepository authenticationProviderRepository;

@Override
public AuthSignUpResponseDto createUser(AuthSignUpRequestDto request) {
Expand Down Expand Up @@ -66,11 +71,44 @@ public AuthSignInResponseDto signInUser(AuthSignInRequestDto request) {
return AuthSignInResponseDto.of(user, accessToken);
}

@Override
public AuthSignUpResponseDto loginSocialUser(AuthSocialSignInRequestDto request){
User user = findByKey(KakaoUser.of(request.uid(), request.socialType()));
if (Objects.isNull(user))
throw new EntityNotFoundException(CHECK_KAKAO_USER_FAIL.getMessage());
String accessToken = updateAccessTokenAndRefreshToken(user);
return AuthSignUpResponseDto.of(user, accessToken);
}

public User findByKey(KakaoUser kakaoUser){
Optional<AuthenticationProvider> authenticationProvider = authenticationProviderRepository
.findByIdAndProvider(kakaoUser.userId(),
kakaoUser.providerType());
// 카카오 계정은 확인, 우리 서비스에 이미 로그인함
if(authenticationProvider.isPresent()) {
Long userId = authenticationProvider.get().getUser().getId();
//유저 테이블에서 찾기 , 못찾을 경우 에러 날려야 하는지 궁굼.. ->node에서는 return null로 날림
User user = userRepository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException(ErrorMessage.CANT_GET_USERINFO.getMessage()));
return user;
}
// 카카오 계정은 확인 됐지만, 우리 서비스에는 로그인 안됨
return null;
}

private User checkPassword(String email, String password) {
User user = userRepository.findByEmail(email);
if (saltEncrypt.isMatch(password, user.getPassword()))
return user;
else
throw new IllegalArgumentException(INVALID_PASSWORD.getMessage());
}

private String updateAccessTokenAndRefreshToken(User user){
Authentication authentication = new UserAuthentication(user.getId(), null, null);
String accessToken = tokenProvider.generateAccessToken(authentication);
String refreshToken = tokenProvider.generateRefreshToken(authentication);
user.updateRefreshToken(refreshToken);
return accessToken;
}
}