Skip to content

Commit

Permalink
Merge pull request #51 from Kakaotech-18-Ecommerce/SCRUM-77-Entity-In…
Browse files Browse the repository at this point in the history
…heritance-Problem

Scrum 77 entity inheritance problem
  • Loading branch information
softwareyong authored Sep 7, 2024
2 parents e120e5d + c53890c commit 42aadc8
Show file tree
Hide file tree
Showing 34 changed files with 723 additions and 635 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-impl:0.12.3'
implementation 'io.jsonwebtoken:jjwt-jackson:0.12.3'


implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
compileOnly 'org.projectlombok:lombok'
Expand Down
25 changes: 13 additions & 12 deletions src/main/java/com/kakaoteck/golagola/config/ApplicationConfig.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.kakaoteck.golagola.config;

import com.kakaoteck.golagola.domain.auth.Repository.UserRepository;
import com.kakaoteck.golagola.domain.auth.entity.UserEntity;
import com.kakaoteck.golagola.domain.buyer.entity.Buyer;
import com.kakaoteck.golagola.domain.buyer.repository.BuyerRepository;
import com.kakaoteck.golagola.domain.seller.entity.Seller;
Expand All @@ -25,27 +27,26 @@
@RequiredArgsConstructor
public class ApplicationConfig {

private final BuyerRepository buyerRepository;
private final SellerRepository sellerRepository;
private final UserRepository userRepository;

@Bean
public UserDetailsService userDetailsService() {
return username -> {
// Try to find the user as a Buyer
Buyer buyer = buyerRepository.findByEmail(username).orElse(null);

if (buyer != null) {
System.out.println("Buyer found: " + username);
return buyer; // Buyer 객체를 반환
UserEntity userEntity = userRepository.findByUsername(username).orElse(null);

if (userEntity != null) {
System.out.println("userEntity found: " + username);
return userEntity; // Buyer 객체를 반환
}

// Try to find the user as a Seller
Seller seller = sellerRepository.findByEmail(username).orElse(null);
// Seller seller = sellerRepository.findByEmail(username).orElse(null);

if (seller != null) {
System.out.println("Seller loaded: " + seller.getEmail());
return seller; // Seller 객체를 반환
}
// if (seller != null) {
// System.out.println("Seller loaded: " + seller.getEmail());
// return seller; // Seller 객체를 반환
// }

throw new UsernameNotFoundException("User not found with username: " + username);
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.kakaoteck.golagola.config;

import com.kakaoteck.golagola.security.filter.JwtAuthenticationFilter;
import com.kakaoteck.golagola.security.handler.signout.CustomSignOutProcessHandler;
import com.kakaoteck.golagola.security.jwt.JWTFilter;
import com.kakaoteck.golagola.security.jwt.JWTUtil;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package com.kakaoteck.golagola.domain.auth.Repository;

import com.kakaoteck.golagola.domain.auth.entity.UserEntity;
import com.kakaoteck.golagola.global.common.enums.Gender;
import com.kakaoteck.golagola.global.common.enums.Role;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
// UserEntity findByUsername(String username); // username을 전달하여 해당하는 엔티티 가져오기(JPA)

Expand All @@ -18,6 +22,14 @@ public interface UserRepository extends JpaRepository<UserEntity, Long> {
void updateRefreshTokenAndLoginStatus(@Param("userName") String username,
@Param("refreshToken") String refreshToken,
@Param("loginStatus") boolean loginStatus);

@Modifying
@Query("UPDATE UserEntity u SET u.nickname = :nickName, u.gender = :gender WHERE u.username = :username")

int updateUserInfo(@Param("username") String username,
@Param("nickName") String nickName,
@Param("gender") Gender gender);

}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,50 +1,35 @@
package com.kakaoteck.golagola.domain.auth.controller;


import com.kakaoteck.golagola.domain.auth.dto.AuthRequest;
import com.kakaoteck.golagola.domain.auth.dto.AuthResponse;
import com.kakaoteck.golagola.domain.auth.dto.JoinUserRequest;
import com.kakaoteck.golagola.domain.auth.service.AuthService;
import com.kakaoteck.golagola.domain.auth.dto.CustomOAuth2User;
import com.kakaoteck.golagola.domain.auth.service.AuthService1;
import com.kakaoteck.golagola.global.common.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import lombok.RequiredArgsConstructor;

import java.io.IOException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RequestMapping("/api/v1/auth")
@RestController
@CrossOrigin("*")
@RequestMapping("/api/v1/auth")
public class AuthController {

private final AuthService authService;
private final AuthService1 authService;

@Operation(summary = "회원가입 기능", description = "gender 값: MALE or FEMALE")
@Operation(summary = "회원가입 추가정보 진행", description = "(nickname, gender) 저장")
@PostMapping("/join")
public ApiResponse<String> join(@RequestBody JoinUserRequest request) {
authService.register(request);
return ApiResponse.onSuccess("회원가입 성공");
}
public ApiResponse<String> join(@RequestBody AuthRequest authRequest) {
// 1. jwt 세션 접근
CustomOAuth2User customUser = (CustomOAuth2User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = customUser.getUsername();

@Operation(summary = "이메일 중복 검사 버튼", description = "회원가입 과정에서 이메일 중복 검사를 진행합니다.\ntrue = 이미 존재하는 이메일, false = 가입 가능한 이메일")
@GetMapping("/join/email-check/{email}")
public ApiResponse<?> checkEmailExists(
@PathVariable(name = "email") String email
) {
return ApiResponse.onSuccess(authService.checkEmailExists(email));
}
// 2. UserService를 통해 (nickname, gender) 저장
authService.saveUserDetails(username, authRequest);

@PostMapping("/login")
public ApiResponse<AuthResponse> login(@RequestBody AuthRequest request) {
return ApiResponse.onSuccess(authService.authenticate(request));
}

@Operation(summary = "리프레시 토큰 발급")
@PostMapping("/refresh-token")
public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
authService.refreshToken(request, response);
return ApiResponse.onSuccess("회원가입 성공");
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.kakaoteck.golagola.domain.auth.dto;

import com.kakaoteck.golagola.global.common.enums.Gender;
import com.kakaoteck.golagola.global.common.enums.Role;

public record AuthRequest(
String email,
String password
String nickName,
Gender gender
// Role role
) {
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,51 @@
package com.kakaoteck.golagola.domain.auth.dto;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.user.OAuth2User;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

public class CustomOAuth2User implements OAuth2User{
public class CustomOAuth2User implements UserDetails, OAuth2User{

private final UserDTO userDTO;

public CustomOAuth2User(UserDTO userDTO) {

this.userDTO = userDTO;
}

@Override
public String getPassword() {
return "";
}

@Override
public boolean isAccountNonExpired() {
return UserDetails.super.isAccountNonExpired();
}

@Override
public boolean isAccountNonLocked() {
return UserDetails.super.isAccountNonLocked();
}

@Override
public boolean isCredentialsNonExpired() {
return UserDetails.super.isCredentialsNonExpired();
}

@Override
public boolean isEnabled() {
return UserDetails.super.isEnabled();
}

@Override
public <A> A getAttribute(String name) {
return OAuth2User.super.getAttribute(name);
}

@Override
public Map<String, Object> getAttributes() {
return Map.of();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,11 @@ public String getName() {
Map<String, Object> profile = (Map<String, Object>) kakaoAccount.get("profile");
return profile.get("nickname").toString();
}

@Override
public String getImage() {
Map<String, Object> kakaoAccount = (Map<String, Object>) attribute.get("kakao_account");
Map<String, Object> profile = (Map<String, Object>) kakaoAccount.get("profile");
return profile.get("profile_image_url").toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,9 @@ public String getEmail() {
public String getName() {
return attribute.get("name").toString();
}

@Override
public String getImage() {
return attribute.get("profile_image").toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.kakaoteck.golagola.domain.auth.dto;

public interface OAuth2KakaoResponse {

String getProvider(); //제공자 (Ex. naver, google, ...)
String getProviderId(); //제공자에서 발급해주는 아이디(번호)
String getEmail(); //이메일
String getName(); //사용자 실명 (설정한 이름)
String getImage(); //사용자 실명 (설정한 이름)

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ public interface OAuth2Response {
String getEmail();
//사용자 실명 (설정한 이름)
String getName();

//사용자 프로필 사진
String getImage();
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ public class UserDTO {
private String name;
private String username;
private String email; // 엔티티의 email 추가
private String refreshToken; // 엔티티의 refreshToken 추가
private boolean loginStatus; // 엔티티의 loginStatus 추가
// private String refreshToken; // 엔티티의 refreshToken 추가
// private boolean loginStatus; // 엔티티의 loginStatus 추가
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
package com.kakaoteck.golagola.domain.auth.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import com.kakaoteck.golagola.domain.buyer.entity.Buyer;
import com.kakaoteck.golagola.domain.seller.entity.Seller;
import com.kakaoteck.golagola.global.common.BaseEntity;
import com.kakaoteck.golagola.global.common.enums.Gender;
import com.kakaoteck.golagola.global.common.enums.Role;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

@Entity
@Getter
@Setter
public class UserEntity {
@Table(name = "users")
public class UserEntity implements UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Expand All @@ -19,12 +30,52 @@ public class UserEntity {
private String username;
private String name;
private String email;
private String role;

private String phoneNum;
private String nickname; // @Column(nullable = false)
private String image;

@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Gender gender = Gender.valueOf("MALE");

// 추가
private String refreshToken; // JWT 리프레시 토큰 발급
private boolean loginStatus; // 로그인 상태처리

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private Seller seller;

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private Buyer buyer;

@Override
public boolean isAccountNonExpired() {
return UserDetails.super.isAccountNonExpired();
}

@Override
public boolean isAccountNonLocked() {
return UserDetails.super.isAccountNonLocked();
}

@Override
public boolean isCredentialsNonExpired() {
return UserDetails.super.isCredentialsNonExpired();
}

@Override
public boolean isEnabled() {
return UserDetails.super.isEnabled();
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of();
}

@Override
public String getPassword() {
return "";
}
}
Loading

0 comments on commit 42aadc8

Please sign in to comment.