Skip to content

Commit

Permalink
Merge pull request #6 from team-nabi/NABI-102--yejin--refactor--oauth…
Browse files Browse the repository at this point in the history
…2-google-kakao

NABI-102-refsctor : 카카오 로그인 아키텍쳐 수정
  • Loading branch information
BeommoKoo-dev authored Oct 31, 2023
2 parents 7b18898 + 28ec6b1 commit 0635adc
Show file tree
Hide file tree
Showing 39 changed files with 209 additions and 286 deletions.
7 changes: 6 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,20 @@ dependencies {
runtimeOnly 'com.h2database:h2'
runtimeOnly 'com.mysql:mysql-connector-j'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

// Json을 결과로 매핑하기 위한 의존성
implementation 'com.google.code.gson:gson:2.8.8'

implementation 'org.springframework.boot:spring-boot-starter-freemarker:2.5.4'

// 다국어 제공을 위한 i18n을 yml 파일로 적용하기 위한 의존성
implementation 'net.rakugakibox.util:yaml-resource-bundle:1.1'

// jwt 의존성 - JWT의 생성 및 유효성 검사와 관련된 기본적인 기능
implementation 'io.jsonwebtoken:jjwt:0.9.1'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ public static void main(String[] args) {
SpringApplication.run(NabiMarketBeApplication.class, args);
}


@Bean
public RestTemplate getRestTemplate() {
public RestTemplate restTemplate() {
return new RestTemplate();
}

}
67 changes: 0 additions & 67 deletions src/main/java/org/prgrms/nabimarketbe/config/SecurityConfig.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package org.prgrms.nabimarketbe.domain.user.controller;
package org.prgrms.nabimarketbe.domain.user.api;

import lombok.RequiredArgsConstructor;

import org.prgrms.nabimarketbe.domain.user.dto.UserRequestDto;
import org.prgrms.nabimarketbe.domain.user.dto.UserResponseDto;
import org.prgrms.nabimarketbe.domain.user.service.UserService;
import org.prgrms.nabimarketbe.global.model.CommonResult;
import org.prgrms.nabimarketbe.global.model.ListResult;
import org.prgrms.nabimarketbe.global.model.SingleResult;
import org.prgrms.nabimarketbe.global.ResponseService;
import org.prgrms.nabimarketbe.global.util.model.CommonResult;
import org.prgrms.nabimarketbe.global.util.model.ListResult;
import org.prgrms.nabimarketbe.global.util.model.SingleResult;
import org.prgrms.nabimarketbe.global.util.ResponseFactory;

import org.springframework.web.bind.annotation.*;

Expand All @@ -18,21 +18,21 @@
public class UserController {
private final UserService userService;

private final ResponseService responseService;
private final ResponseFactory responseFactory;

@GetMapping("/user/id/{userId}")
public SingleResult<UserResponseDto> findUserById(@PathVariable Long userId) {
return responseService.getSingleResult(userService.findById(userId));
return responseFactory.getSingleResult(userService.findById(userId));
}

@GetMapping("/user/nickname/{nickname}")
public SingleResult<UserResponseDto> findUserByNickName(@PathVariable String nickname) {
return responseService.getSingleResult(userService.findByNickName(nickname));
return responseFactory.getSingleResult(userService.findByNickName(nickname));
}

@GetMapping("/users")
public ListResult<UserResponseDto> findAllUser() {
return responseService.getListResult(userService.findAllUser());
return responseFactory.getListResult(userService.findAllUser());
}

@PutMapping("/user")
Expand All @@ -44,13 +44,13 @@ public SingleResult<Long> update (
.nickName(nickname)
.build();

return responseService.getSingleResult(userService.update(userId, userRequestDto));
return responseFactory.getSingleResult(userService.update(userId, userRequestDto));
}

@DeleteMapping("/user/{userId}")
public CommonResult delete(@PathVariable Long userId) {
userService.delete(userId);

return responseService.getSuccessResult();
return responseFactory.getSuccessResult();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.prgrms.nabimarketbe.domain.user.BaseEntity;
import org.prgrms.nabimarketbe.global.BaseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
Expand All @@ -30,6 +30,12 @@ public class User extends BaseEntity implements UserDetails {
@Column(name = "nick_name", nullable = false, length = 20)
private String nickname;

@Column(name = "user_email")
private String email;

@Column(name = "user_image_url")
private String image_url;

@Column(length = 100)
private String provider;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
@Repository
public interface UserJpaRepo extends JpaRepository<User, Long> {
Optional<User> findByNickname(String name);
Optional<User> findByEmail(String email);
Optional<User> findByNicknameAndProvider(String name, String provider);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,47 +2,75 @@

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.prgrms.nabimarketbe.global.security.jwt.dto.TokenRequestDto;
import org.prgrms.nabimarketbe.oauth2.kakao.dto.KakaoProfile;
import org.prgrms.nabimarketbe.oauth2.kakao.service.OAuth2Service;
import org.prgrms.nabimarketbe.domain.user.dto.sign.UserSignupRequestDto;
import org.prgrms.nabimarketbe.domain.security.jwt.JwtProvider;
import org.prgrms.nabimarketbe.domain.security.entity.RefreshToken;
import org.prgrms.nabimarketbe.domain.security.repository.RefreshTokenJpaRepo;
import org.prgrms.nabimarketbe.domain.security.jwt.dto.TokenResponseDto;
import org.prgrms.nabimarketbe.domain.security.jwt.dto.TokenRequestDto;
import org.prgrms.nabimarketbe.global.security.jwt.provider.JwtProvider;
import org.prgrms.nabimarketbe.global.security.entity.RefreshToken;
import org.prgrms.nabimarketbe.oauth2.kakao.repository.RefreshTokenJpaRepo;
import org.prgrms.nabimarketbe.global.security.jwt.dto.TokenDto;
import org.prgrms.nabimarketbe.domain.user.entity.User;
import org.prgrms.nabimarketbe.domain.user.repository.UserJpaRepo;
import org.prgrms.nabimarketbe.global.util.ResponseFactory;
import org.prgrms.nabimarketbe.global.util.model.CommonResult;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class SignService {
private final UserJpaRepo userJpaRepo;

private final OAuth2Service OAuth2Service;

private final ResponseFactory responseFactory;

private final JwtProvider jwtProvider;

private final RefreshTokenJpaRepo tokenJpaRepo;

@Transactional
public Long socialSignup(UserSignupRequestDto userSignupRequestDto) {
if (userJpaRepo
.findByNicknameAndProvider(userSignupRequestDto.nickname(), userSignupRequestDto.provider())
.isPresent()
) throw new RuntimeException("이미 존재하는 회원입니다.");
public CommonResult signupBySocial(String accessToken) {
KakaoProfile kakaoProfile = OAuth2Service.getKakaoProfile(accessToken);

if (kakaoProfile == null) throw new RuntimeException("카카오에 해당 회원이 없습니다.");

CommonResult result = socialSignup(UserSignupRequestDto.builder()
.nickname(kakaoProfile.getProperties().getNickname())
.provider("kakao")
.build());

return responseFactory.getSingleResult(result);
}
@Transactional
public CommonResult socialSignup(UserSignupRequestDto userSignupRequestDto) {
Optional<User> user = userJpaRepo.findByNicknameAndProvider(
userSignupRequestDto.nickname(),
userSignupRequestDto.provider()
);

if (user.isPresent()) {
return responseFactory.getSingleResult(jwtProvider.createTokenDto(user.get().getUserId(), user.get().getRoles()));
}

return userJpaRepo.save(userSignupRequestDto.toEntity()).getUserId();
userJpaRepo.save(userSignupRequestDto.toEntity());
return responseFactory.getSingleResult(jwtProvider.createTokenDto(user.get().getUserId(), user.get().getRoles()));
}

@Transactional
public TokenResponseDto reissue(TokenRequestDto tokenRequestDto) {
public TokenDto reissue(TokenRequestDto tokenRequestDto) {
// 만료된 refresh token 에러
if (!jwtProvider.validationToken(tokenRequestDto.refreshToken())) {
if (!jwtProvider.validationToken(tokenRequestDto.getAccessToken())) {
throw new RuntimeException("RefreshTokenException");
}

// AccessToken 에서 Username (pk) 가져오기
String accessToken = tokenRequestDto.accessToken();
String accessToken = tokenRequestDto.getAccessToken();
Authentication authentication = jwtProvider.getAuthentication(accessToken);

// user pk로 유저 검색 / repo 에 저장된 Refresh Token 이 없음
Expand All @@ -53,11 +81,11 @@ public TokenResponseDto reissue(TokenRequestDto tokenRequestDto) {
.orElseThrow(() ->new RuntimeException("RefreshTokenException"));

// 리프레시 토큰 불일치 에러
if (!refreshToken.getToken().equals(tokenRequestDto.refreshToken()))
if (!refreshToken.getToken().equals(tokenRequestDto.getRefreshToken()))
throw new RuntimeException("RefreshTokenException");

// AccessToken, RefreshToken 토큰 재발급, 리프레쉬 토큰 저장
TokenResponseDto newCreatedToken = jwtProvider.createTokenDto(user.getUserId(), user.getRoles());
TokenDto newCreatedToken = jwtProvider.createTokenDto(user.getUserId(), user.getRoles());
RefreshToken updateRefreshToken = refreshToken.updateToken(newCreatedToken.getRefreshToken());

tokenJpaRepo.save(updateRefreshToken);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

package org.prgrms.nabimarketbe.domain.user;
package org.prgrms.nabimarketbe.global;

import lombok.Getter;
import org.springframework.data.annotation.CreatedDate;
Expand Down
Loading

0 comments on commit 0635adc

Please sign in to comment.