From 662bced4ccd669afde70df17d208c0f1d6ce5e6b Mon Sep 17 00:00:00 2001 From: leeyongwoo <95459741+softwareyong@users.noreply.github.com> Date: Mon, 2 Sep 2024 10:25:05 +0900 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20user=20SINGLE=5FTABLE=20=EA=B5=AC?= =?UTF-8?q?=EC=A1=B0=EB=A1=9C=20=EC=83=81=EC=86=8D=20=EB=AC=B8=EC=A0=9C=20?= =?UTF-8?q?=ED=95=B4=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 2 +- .../golagola/config/ApplicationConfig.java | 25 +- .../golagola/config/SecurityConfig.java | 1 - .../auth/Repository/UserRepository.java | 2 + .../auth/controller/AuthController.java | 100 ++--- .../domain/auth/entity/UserEntity.java | 57 ++- .../domain/auth/service/AuthService.java | 382 +++++++++--------- .../golagola/domain/buyer/entity/Buyer.java | 131 ++---- .../domain/buyer/service/BuyerService.java | 8 +- .../golagola/domain/order/entity/Order.java | 3 +- .../domain/product/entity/Product.java | 3 +- .../product/service/ProductService.java | 4 +- .../golagola/domain/review/entity/Review.java | 3 +- .../golagola/domain/seller/entity/Seller.java | 118 ++---- .../domain/seller/service/SellerService.java | 8 +- .../golagola/global/common/BaseEntity.java | 4 + .../security/ApplicationAuditAware.java | 4 +- .../filter/JwtAuthenticationFilter.java | 138 +++---- .../golagola/security/jwt/JWTFilter.java | 3 +- .../security/service/LogoutService.java | 156 +++---- .../security/token/TokenRepository.java | 50 +-- .../service/CustomOAuth2UserService.java | 6 +- 22 files changed, 578 insertions(+), 630 deletions(-) diff --git a/build.gradle b/build.gradle index 8e7e596..0a8b263 100644 --- a/build.gradle +++ b/build.gradle @@ -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' diff --git a/src/main/java/com/kakaoteck/golagola/config/ApplicationConfig.java b/src/main/java/com/kakaoteck/golagola/config/ApplicationConfig.java index 7420773..5576507 100644 --- a/src/main/java/com/kakaoteck/golagola/config/ApplicationConfig.java +++ b/src/main/java/com/kakaoteck/golagola/config/ApplicationConfig.java @@ -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; @@ -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); }; diff --git a/src/main/java/com/kakaoteck/golagola/config/SecurityConfig.java b/src/main/java/com/kakaoteck/golagola/config/SecurityConfig.java index c6213d6..8213e72 100644 --- a/src/main/java/com/kakaoteck/golagola/config/SecurityConfig.java +++ b/src/main/java/com/kakaoteck/golagola/config/SecurityConfig.java @@ -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; diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java b/src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java index 146da2f..a549637 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java @@ -5,9 +5,11 @@ 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 findByUsername(String username); // username을 전달하여 해당하는 엔티티 가져오기(JPA) diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/controller/AuthController.java b/src/main/java/com/kakaoteck/golagola/domain/auth/controller/AuthController.java index f05157b..d4368ef 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/controller/AuthController.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/controller/AuthController.java @@ -1,50 +1,50 @@ -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.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; - -@RequiredArgsConstructor -@RequestMapping("/api/v1/auth") -@RestController -@CrossOrigin("*") -public class AuthController { - - private final AuthService authService; - - @Operation(summary = "회원가입 기능", description = "gender 값: MALE or FEMALE") - @PostMapping("/join") - public ApiResponse join(@RequestBody JoinUserRequest request) { - authService.register(request); - return ApiResponse.onSuccess("회원가입 성공"); - } - - @Operation(summary = "이메일 중복 검사 버튼", description = "회원가입 과정에서 이메일 중복 검사를 진행합니다.\ntrue = 이미 존재하는 이메일, false = 가입 가능한 이메일") - @GetMapping("/join/email-check/{email}") - public ApiResponse checkEmailExists( - @PathVariable(name = "email") String email - ) { - return ApiResponse.onSuccess(authService.checkEmailExists(email)); - } - - @PostMapping("/login") - public ApiResponse 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); - } -} \ No newline at end of file +//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.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; +// +//@RequiredArgsConstructor +//@RequestMapping("/api/v1/auth") +//@RestController +//@CrossOrigin("*") +//public class AuthController { +// +// private final AuthService authService; +// +// @Operation(summary = "회원가입 기능", description = "gender 값: MALE or FEMALE") +// @PostMapping("/join") +// public ApiResponse join(@RequestBody JoinUserRequest request) { +// authService.register(request); +// return ApiResponse.onSuccess("회원가입 성공"); +// } +// +// @Operation(summary = "이메일 중복 검사 버튼", description = "회원가입 과정에서 이메일 중복 검사를 진행합니다.\ntrue = 이미 존재하는 이메일, false = 가입 가능한 이메일") +// @GetMapping("/join/email-check/{email}") +// public ApiResponse checkEmailExists( +// @PathVariable(name = "email") String email +// ) { +// return ApiResponse.onSuccess(authService.checkEmailExists(email)); +// } +// +// @PostMapping("/login") +// public ApiResponse 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); +// } +//} \ No newline at end of file diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java b/src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java index f460c3d..33f09b1 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java @@ -1,16 +1,28 @@ 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.global.common.BaseEntity; +import com.kakaoteck.golagola.global.common.enums.Gender; +import com.kakaoteck.golagola.global.common.enums.Role; +import jakarta.persistence.*; 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 { +@SuperBuilder // 추가 +@NoArgsConstructor +@Table(name = "users") +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "entity_type") +public class UserEntity extends BaseEntity implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -19,12 +31,45 @@ public class UserEntity { private String username; private String name; private String email; - private String role; + + private String phoneNum; + private String nickname; // @Column(nullable = false) + + @Enumerated(EnumType.STRING) + @Column(nullable = false) + private Gender gender = Gender.valueOf("MALE"); // 추가 private String refreshToken; // JWT 리프레시 토큰 발급 private boolean loginStatus; // 로그인 상태처리 + @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 getAuthorities() { + return List.of(); + } + @Override + public String getPassword() { + return ""; + } } diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/service/AuthService.java b/src/main/java/com/kakaoteck/golagola/domain/auth/service/AuthService.java index 8dcb7ab..7313bfa 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/service/AuthService.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/service/AuthService.java @@ -1,193 +1,189 @@ -package com.kakaoteck.golagola.domain.auth.service; - -import com.fasterxml.jackson.databind.ObjectMapper; -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.buyer.entity.Buyer; -import com.kakaoteck.golagola.domain.buyer.repository.BuyerRepository; -import com.kakaoteck.golagola.domain.seller.entity.Seller; -import com.kakaoteck.golagola.domain.seller.repository.SellerRepository; -import com.kakaoteck.golagola.global.common.code.status.ErrorStatus; -import com.kakaoteck.golagola.global.common.enums.Gender; -import com.kakaoteck.golagola.global.common.enums.Role; -import com.kakaoteck.golagola.global.common.exception.GeneralException; -import com.kakaoteck.golagola.security.service.JwtService; -import com.kakaoteck.golagola.security.token.Token; -import com.kakaoteck.golagola.security.token.TokenBlackListRepository; -import com.kakaoteck.golagola.security.token.TokenRepository; -import com.kakaoteck.golagola.security.token.enums.TokenType; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpHeaders; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; - -import java.io.IOException; -import java.time.LocalDate; -import java.util.NoSuchElementException; -import java.util.Optional; - -@Service -@RequiredArgsConstructor -public class AuthService { - private final BuyerRepository buyerRepository; - private final SellerRepository sellerRepository; - private final TokenRepository tokenRepository; - private final TokenBlackListRepository tokenBlackListRepository; - private final PasswordEncoder passwordEncoder; - private final JwtService jwtService; - private final AuthenticationManager authenticationManager; - - public void register(JoinUserRequest request) { - if ("BUYER".equals(request.role())) { - Buyer buyer = Buyer.builder() - .email(request.email()) - .password(passwordEncoder.encode(request.password())) - .nickname(request.nickname()) - .realName(request.realName()) - .phoneNum(request.phoneNum()) - .gender(Gender.valueOf(request.gender())) - .registerDate(LocalDate.now()) - .role(Role.valueOf(request.role())) - .address(request.address()) - .build(); - buyerRepository.save(buyer); - } else if ("SELLER".equals(request.role())) { - Seller seller = Seller.builder() - .email(request.email()) - .password(passwordEncoder.encode(request.password())) - .nickname(request.nickname()) - .realName(request.realName()) - .phoneNum(request.phoneNum()) - .gender(Gender.valueOf(request.gender())) - .registerDate(LocalDate.now()) - .address(request.address()) - .role(Role.valueOf(request.role())) - .build(); - sellerRepository.save(seller); - } - } - - public AuthResponse authenticate(AuthRequest request) { - System.out.println("Attempting authentication for: " + request.email()); - - try { - authenticationManager.authenticate( - new UsernamePasswordAuthenticationToken( - request.email(), - request.password() - ) - ); - } catch (AuthenticationException e) { - System.out.println("Authentication failed for email: " + request.email()); - throw new GeneralException(ErrorStatus._LOGIN_USER_INVALID); - } - - Buyer buyer = buyerRepository.findByEmail(request.email()).orElse(null); - Seller seller = sellerRepository.findByEmail(request.email()).orElse(null); - - if (buyer == null && seller == null) { - throw new GeneralException(ErrorStatus._INVALID_USER); - } - - System.out.println("Authentication successful for: " + request.email()); - - // Determine the UserDetails type and generate tokens - UserDetails user = buyer != null ? buyer : seller; - String jwtToken = jwtService.generateToken(user); - String refreshToken = jwtService.generateRefreshToken(user); - - revokeAllUserTokens(user); - saveUserToken(user, jwtToken); - - return AuthResponse.builder() - .accessToken(jwtToken) - .refreshToken(refreshToken) - .build(); - } - - private void saveUserToken(UserDetails user, String jwtToken) { - Token token = Token.builder() - .token(jwtToken) - .tokenType(TokenType.BEARER) - .expired(false) - .revoked(false) - .build(); - - if (user instanceof Buyer) { - token.setBuyer((Buyer) user); - } else if (user instanceof Seller) { - token.setSeller((Seller) user); - } - - tokenRepository.save(token); - } - - private void revokeAllUserTokens(UserDetails user) { - if (user instanceof Buyer) { - var validUserTokens = tokenRepository.findAllValidTokenByBuyer(((Buyer) user).getBuyerId()); - validUserTokens.forEach(token -> { - token.setExpired(true); - token.setRevoked(true); - }); - tokenRepository.saveAll(validUserTokens); - } else if (user instanceof Seller) { - var validUserTokens = tokenRepository.findAllValidTokenBySeller(((Seller) user).getSellerId()); - validUserTokens.forEach(token -> { - token.setExpired(true); - token.setRevoked(true); - }); - tokenRepository.saveAll(validUserTokens); - } - } - - public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException { - final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION); - if (authHeader == null || !authHeader.startsWith("Bearer ")) { - return; - } - String refreshToken = authHeader.substring(7); - if (tokenBlackListRepository.existsByToken(refreshToken)) { - throw new NoSuchElementException("유효하지 않은 접근입니다."); - } - - String userEmail = jwtService.extractUserName(refreshToken); - if (userEmail != null) { - var buyerOptional = buyerRepository.findByEmail(userEmail); - var sellerOptional = sellerRepository.findByEmail(userEmail); - - if (buyerOptional.isPresent()) { - processTokenRefresh(buyerOptional.get(), refreshToken, response); - } else if (sellerOptional.isPresent()) { - processTokenRefresh(sellerOptional.get(), refreshToken, response); - } else { - throw new NoSuchElementException("User not found for email: " + userEmail); - } - } - } - - private void processTokenRefresh(UserDetails user, String refreshToken, HttpServletResponse response) throws IOException { - if (jwtService.isTokenValid(refreshToken, user)) { - String accessToken = jwtService.generateToken(user); - revokeAllUserTokens(user); - saveUserToken(user, accessToken); - - AuthResponse authResponse = AuthResponse.builder() - .accessToken(accessToken) - .refreshToken(refreshToken) - .build(); - new ObjectMapper().writeValue(response.getOutputStream(), authResponse); - } - } - - public boolean checkEmailExists(String email) { - return buyerRepository.existsByEmail(email) || sellerRepository.existsByEmail(email); - } -} +//package com.kakaoteck.golagola.domain.auth.service; +// +//import com.fasterxml.jackson.databind.ObjectMapper; +//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.buyer.entity.Buyer; +//import com.kakaoteck.golagola.domain.buyer.repository.BuyerRepository; +//import com.kakaoteck.golagola.domain.seller.entity.Seller; +//import com.kakaoteck.golagola.domain.seller.repository.SellerRepository; +//import com.kakaoteck.golagola.global.common.code.status.ErrorStatus; +//import com.kakaoteck.golagola.global.common.enums.Gender; +//import com.kakaoteck.golagola.global.common.enums.Role; +//import com.kakaoteck.golagola.global.common.exception.GeneralException; +//import com.kakaoteck.golagola.security.service.JwtService; +//import com.kakaoteck.golagola.security.token.Token; +//import com.kakaoteck.golagola.security.token.TokenBlackListRepository; +//import com.kakaoteck.golagola.security.token.TokenRepository; +//import com.kakaoteck.golagola.security.token.enums.TokenType; +//import jakarta.servlet.http.HttpServletRequest; +//import jakarta.servlet.http.HttpServletResponse; +//import lombok.RequiredArgsConstructor; +//import org.springframework.http.HttpHeaders; +//import org.springframework.security.authentication.AuthenticationManager; +//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +//import org.springframework.security.core.AuthenticationException; +//import org.springframework.security.core.userdetails.UserDetails; +//import org.springframework.security.core.userdetails.UserDetailsService; +//import org.springframework.security.crypto.password.PasswordEncoder; +//import org.springframework.stereotype.Service; +// +//import java.io.IOException; +//import java.time.LocalDate; +//import java.util.NoSuchElementException; +//import java.util.Optional; +// +//@Service +//@RequiredArgsConstructor +//public class AuthService { +// private final BuyerRepository buyerRepository; +// private final SellerRepository sellerRepository; +// private final TokenRepository tokenRepository; +// private final TokenBlackListRepository tokenBlackListRepository; +// private final PasswordEncoder passwordEncoder; +// private final JwtService jwtService; +// private final AuthenticationManager authenticationManager; +// +// public void register(JoinUserRequest request) { +// if ("BUYER".equals(request.role())) { +// Buyer buyer = Buyer.builder() +// .email(request.email()) +// .nickname(request.nickname()) +// .username(request.realName()) +// .phoneNum(request.phoneNum()) +// .gender(Gender.valueOf(request.gender())) +// .role(Role.valueOf(request.role())) +// .address(request.address()) +// .build(); +// buyerRepository.save(buyer); +// } else if ("SELLER".equals(request.role())) { +// Seller seller = Seller.builder() +// .email(request.email()) +// .nickname(request.nickname()) +// .username(request.realName()) +// .phoneNum(request.phoneNum()) +// .gender(Gender.valueOf(request.gender())) +// .address(request.address()) +// .role(Role.valueOf(request.role())) +// .build(); +// sellerRepository.save(seller); +// } +// } +// +// public AuthResponse authenticate(AuthRequest request) { +// System.out.println("Attempting authentication for: " + request.email()); +// +// try { +// authenticationManager.authenticate( +// new UsernamePasswordAuthenticationToken( +// request.email(), +// request.password() +// ) +// ); +// } catch (AuthenticationException e) { +// System.out.println("Authentication failed for email: " + request.email()); +// throw new GeneralException(ErrorStatus._LOGIN_USER_INVALID); +// } +// +// Buyer buyer = buyerRepository.findByEmail(request.email()).orElse(null); +// Seller seller = sellerRepository.findByEmail(request.email()).orElse(null); +// +// if (buyer == null && seller == null) { +// throw new GeneralException(ErrorStatus._INVALID_USER); +// } +// +// System.out.println("Authentication successful for: " + request.email()); +// +// // Determine the UserDetails type and generate tokens +// UserDetails user = buyer != null ? buyer : seller; +// String jwtToken = jwtService.generateToken(user); +// String refreshToken = jwtService.generateRefreshToken(user); +// +// revokeAllUserTokens(user); +// saveUserToken(user, jwtToken); +// +// return AuthResponse.builder() +// .accessToken(jwtToken) +// .refreshToken(refreshToken) +// .build(); +// } +// +// private void saveUserToken(UserDetails user, String jwtToken) { +// Token token = Token.builder() +// .token(jwtToken) +// .tokenType(TokenType.BEARER) +// .expired(false) +// .revoked(false) +// .build(); +// +// if (user instanceof Buyer) { +// token.setBuyer((Buyer) user); +// } else if (user instanceof Seller) { +// token.setSeller((Seller) user); +// } +// +// tokenRepository.save(token); +// } +// +// private void revokeAllUserTokens(UserDetails user) { +// if (user instanceof Buyer) { +// var validUserTokens = tokenRepository.findAllValidTokenByBuyer(((Buyer) user).getId()); +// validUserTokens.forEach(token -> { +// token.setExpired(true); +// token.setRevoked(true); +// }); +// tokenRepository.saveAll(validUserTokens); +// } else if (user instanceof Seller) { +// var validUserTokens = tokenRepository.findAllValidTokenBySeller(((Seller) user).getId()); // .getSellerId() 원래 이거임 +// validUserTokens.forEach(token -> { +// token.setExpired(true); +// token.setRevoked(true); +// }); +// tokenRepository.saveAll(validUserTokens); +// } +// } +// +// public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException { +// final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION); +// if (authHeader == null || !authHeader.startsWith("Bearer ")) { +// return; +// } +// String refreshToken = authHeader.substring(7); +// if (tokenBlackListRepository.existsByToken(refreshToken)) { +// throw new NoSuchElementException("유효하지 않은 접근입니다."); +// } +// +// String userEmail = jwtService.extractUserName(refreshToken); +// if (userEmail != null) { +// var buyerOptional = buyerRepository.findByEmail(userEmail); +// var sellerOptional = sellerRepository.findByEmail(userEmail); +// +// if (buyerOptional.isPresent()) { +// processTokenRefresh(buyerOptional.get(), refreshToken, response); +// } else if (sellerOptional.isPresent()) { +// processTokenRefresh(sellerOptional.get(), refreshToken, response); +// } else { +// throw new NoSuchElementException("User not found for email: " + userEmail); +// } +// } +// } +// +// private void processTokenRefresh(UserDetails user, String refreshToken, HttpServletResponse response) throws IOException { +// if (jwtService.isTokenValid(refreshToken, user)) { +// String accessToken = jwtService.generateToken(user); +// revokeAllUserTokens(user); +// saveUserToken(user, accessToken); +// +// AuthResponse authResponse = AuthResponse.builder() +// .accessToken(accessToken) +// .refreshToken(refreshToken) +// .build(); +// new ObjectMapper().writeValue(response.getOutputStream(), authResponse); +// } +// } +// +// public boolean checkEmailExists(String email) { +// return buyerRepository.existsByEmail(email) || sellerRepository.existsByEmail(email); +// } +//} diff --git a/src/main/java/com/kakaoteck/golagola/domain/buyer/entity/Buyer.java b/src/main/java/com/kakaoteck/golagola/domain/buyer/entity/Buyer.java index ec1386f..344dadf 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/buyer/entity/Buyer.java +++ b/src/main/java/com/kakaoteck/golagola/domain/buyer/entity/Buyer.java @@ -1,5 +1,6 @@ package com.kakaoteck.golagola.domain.buyer.entity; +import com.kakaoteck.golagola.domain.auth.entity.UserEntity; import com.kakaoteck.golagola.domain.buyer.dto.BuyerRequest; import com.kakaoteck.golagola.domain.cart.entity.Cart; import com.kakaoteck.golagola.domain.cart.entity.CartProduct; @@ -8,61 +9,34 @@ import com.kakaoteck.golagola.domain.review.entity.Review; import com.kakaoteck.golagola.global.common.enums.Gender; import com.kakaoteck.golagola.global.common.enums.Role; -import com.kakaoteck.golagola.global.common.BaseEntity; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; +import lombok.experimental.SuperBuilder; -import java.time.LocalDate; -import java.util.Collection; -import java.util.Collections; import java.util.List; @Entity @NoArgsConstructor @AllArgsConstructor @Getter -@Builder -@Table(name = "buyer_table") -public class Buyer extends BaseEntity implements UserDetails { +@SuperBuilder +//@Table(name = "buyer_table") +@DiscriminatorValue("BUYER") +public class Buyer extends UserEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long buyerId; +// @Id +// @GeneratedValue(strategy = GenerationType.IDENTITY) +// private Long buyerId; - @Column(nullable = false) - private String nickname; - @Column(nullable = false) - private String realName; + private String address; // @Column(nullable = false) @Enumerated(EnumType.STRING) @Column(nullable = false) - private Gender gender; - - @Column(nullable = false) - private String email; - - @Column(nullable = false) - private String password; - - @Column(nullable = false) - private String address; - - @Column(nullable = false) - private String phoneNum; - - @Enumerated(EnumType.STRING) - @Column(nullable = false) - private Role role; - - @Column(nullable = false) - private LocalDate registerDate; + private Role role = Role.valueOf("SELLER"); @OneToOne(mappedBy = "buyer", cascade = CascadeType.ALL, orphanRemoval = true) private Cart cart; @@ -73,45 +47,10 @@ public class Buyer extends BaseEntity implements UserDetails { @OneToMany(mappedBy = "buyer", cascade = CascadeType.ALL) private List orderList; - @Override - public Collection getAuthorities() { - return Collections.singleton(new SimpleGrantedAuthority(role.name())); - } - - @Override - public String getPassword() { - return this.password; - } - - @Override - public String getUsername() { - return this.email; - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return true; - } - public void updateProfile(BuyerRequest.MyPagePutDto request) { - this.nickname = request.nickname(); this.address = request.address(); - this.phoneNum = request.phoneNum(); + this.setNickname(request.nickname()); // 상위클래스인 UserEntity에 업데이트 + this.setPhoneNum(request.phoneNum()); // 상위클래스인 UserEntity에 업데이트 } public void assignCart(Cart cart) { @@ -145,19 +84,33 @@ public void addProductToCart(Product product) { cart.addProduct(product); } - public static Buyer from(Long buyerId, String nickname, String realName, Gender gender, String email, String password, - String address, String phoneNum, Role role, LocalDate registerDate) { - return Buyer.builder() - .buyerId(buyerId) - .nickname(nickname) - .realName(realName) - .gender(gender) - .email(email) - .password(password) - .address(address) - .phoneNum(phoneNum) - .role(role) - .registerDate(registerDate) - .build(); - } +// @Builder +// public Buyer(Long id, String nickname, String realName, Gender gender, String email, +// String address, String phoneNum, Role role) { +// this.setId(id); // UserEntity의 필드 설정 +// this.setNickname(nickname); // UserEntity의 필드 설정 +// this.setName(realName); // UserEntity의 필드 설정 +// this.setGender(gender); // UserEntity의 필드 설정 +// this.setEmail(email); // UserEntity의 필드 설정 +// this.setPhoneNum(phoneNum); // UserEntity의 필드 설정 +// this.setRole(role); // UserEntity의 필드 설정 +// +// this.address = address; // Buyer 클래스의 필드 설정 +// } +// +// public static Buyer from(Long buyerId, String nickname, String realName, Gender gender, String email, String password, +// String address, String phoneNum, Role role) { +// return Buyer.builder() +// .buyerId(buyerId) +// .nickname(nickname) +// .realName(realName) +// .gender(gender) +// .email(email) +// .password(password) +// .address(address) +// .phoneNum(phoneNum) +// .role(role) +// .build(); +// } +// } diff --git a/src/main/java/com/kakaoteck/golagola/domain/buyer/service/BuyerService.java b/src/main/java/com/kakaoteck/golagola/domain/buyer/service/BuyerService.java index 50407b2..11ce4e5 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/buyer/service/BuyerService.java +++ b/src/main/java/com/kakaoteck/golagola/domain/buyer/service/BuyerService.java @@ -22,8 +22,8 @@ public static BuyerResponse getMyPage(Buyer buyer) { .email(buyer.getEmail()) .role(buyer.getRole()) .address(buyer.getAddress()) - .registerDate(buyer.getRegisterDate()) - .realName(buyer.getRealName()) +// .registerDate(buyer.getRegisterDate()) + .realName(buyer.getUsername()) .gender(buyer.getGender()) .phoneNum(buyer.getPhoneNum()) .nickname(buyer.getNickname()) @@ -37,8 +37,8 @@ public BuyerResponse updateMyPage(Buyer buyer, BuyerRequest.MyPagePutDto request .email(savedBuyer.getEmail()) .role(savedBuyer.getRole()) .address(savedBuyer.getAddress()) - .registerDate(savedBuyer.getRegisterDate()) - .realName(savedBuyer.getRealName()) +// .registerDate(savedBuyer.getRegisterDate()) + .realName(savedBuyer.getUsername()) .gender(savedBuyer.getGender()) .phoneNum(savedBuyer.getPhoneNum()) .nickname(savedBuyer.getNickname()) diff --git a/src/main/java/com/kakaoteck/golagola/domain/order/entity/Order.java b/src/main/java/com/kakaoteck/golagola/domain/order/entity/Order.java index 6ba8ed5..8c54322 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/order/entity/Order.java +++ b/src/main/java/com/kakaoteck/golagola/domain/order/entity/Order.java @@ -10,6 +10,7 @@ import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.experimental.SuperBuilder; import java.time.LocalDate; import java.util.List; @@ -18,7 +19,7 @@ @NoArgsConstructor @AllArgsConstructor @Getter -@Builder +@SuperBuilder @Table(name = "order_table") // order가 mySQL 예약어임 이슈 ! public class Order extends BaseEntity { diff --git a/src/main/java/com/kakaoteck/golagola/domain/product/entity/Product.java b/src/main/java/com/kakaoteck/golagola/domain/product/entity/Product.java index 52db5a0..8b5ed07 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/product/entity/Product.java +++ b/src/main/java/com/kakaoteck/golagola/domain/product/entity/Product.java @@ -13,6 +13,7 @@ import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.experimental.SuperBuilder; import java.time.LocalTime; import java.util.List; @@ -21,7 +22,7 @@ @NoArgsConstructor @AllArgsConstructor @Getter -@Builder +@SuperBuilder @Table(name = "product_table") public class Product extends BaseEntity { diff --git a/src/main/java/com/kakaoteck/golagola/domain/product/service/ProductService.java b/src/main/java/com/kakaoteck/golagola/domain/product/service/ProductService.java index 5166ba8..48e3c10 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/product/service/ProductService.java +++ b/src/main/java/com/kakaoteck/golagola/domain/product/service/ProductService.java @@ -55,7 +55,7 @@ public ProductResponse modifyProduct(Seller seller, Long productId, ProductReque .orElseThrow(() -> new GeneralException(ErrorStatus._NOT_FOUND_PRODUCT)); // 해당 상품이 현재 로그인한 seller가 등록한 것인지 확인 - if (!product.getSeller().getSellerId().equals(seller.getSellerId())) { + if (!product.getSeller().getId().equals(seller.getId())) { throw new GeneralException(ErrorStatus._UNAUTHORIZED_ACCESS); } @@ -96,7 +96,7 @@ public void deleteProduct(Seller seller, Long productId) { .orElseThrow(() -> new GeneralException(ErrorStatus._NOT_FOUND_PRODUCT)); // 해당 Product가 현재 로그인된 seller가 등록한 제품인지 확인 - if (!product.getSeller().getSellerId().equals(seller.getSellerId())) { + if (!product.getSeller().getId().equals(seller.getId())) { throw new GeneralException(ErrorStatus._UNAUTHORIZED_ACCESS); } diff --git a/src/main/java/com/kakaoteck/golagola/domain/review/entity/Review.java b/src/main/java/com/kakaoteck/golagola/domain/review/entity/Review.java index c568087..b600369 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/review/entity/Review.java +++ b/src/main/java/com/kakaoteck/golagola/domain/review/entity/Review.java @@ -9,13 +9,14 @@ import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.experimental.SuperBuilder; import java.time.LocalDate; @Entity @NoArgsConstructor @AllArgsConstructor -@Builder +@SuperBuilder @Getter @Table(name = "review_table") public class Review extends BaseEntity { diff --git a/src/main/java/com/kakaoteck/golagola/domain/seller/entity/Seller.java b/src/main/java/com/kakaoteck/golagola/domain/seller/entity/Seller.java index bef1ad2..5abb67f 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/seller/entity/Seller.java +++ b/src/main/java/com/kakaoteck/golagola/domain/seller/entity/Seller.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.databind.ser.Serializers; +import com.kakaoteck.golagola.domain.auth.entity.UserEntity; import com.kakaoteck.golagola.domain.buyer.dto.BuyerRequest; import com.kakaoteck.golagola.domain.order.entity.Order; import com.kakaoteck.golagola.domain.product.entity.Product; @@ -14,6 +15,7 @@ import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.experimental.SuperBuilder; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @@ -27,43 +29,20 @@ @Entity @NoArgsConstructor @AllArgsConstructor -@Builder @Getter -@Table(name = "seller_table") -public class Seller extends BaseEntity implements UserDetails { +@SuperBuilder +//@Table(name = "seller_table") +@DiscriminatorValue("SELLER") +public class Seller extends UserEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long sellerId; - - @Column(nullable = false) - private String nickname; - - @Column(nullable = false) - private String password; - - @Enumerated(EnumType.STRING) - @Column(nullable = false) - private Gender gender; - - @Column(nullable = false) - private String email; - - @Column(nullable = false) - private String address; - - @Column(nullable = false) - private String phoneNum; +// @Id +// @GeneratedValue(strategy = GenerationType.IDENTITY) +// private Long sellerId; + private String address; // @Column(nullable = false) @Enumerated(EnumType.STRING) @Column(nullable = false) - private Role role; - - @Column(nullable = false) - private String realName; - - @Column(nullable = false) - private LocalDate registerDate; + private Role role = Role.valueOf("SELLER"); @OneToMany(mappedBy = "seller", cascade = CascadeType.ALL) @JsonManagedReference @@ -72,63 +51,28 @@ public class Seller extends BaseEntity implements UserDetails { @OneToMany(mappedBy = "seller", cascade = CascadeType.ALL) private List orderList = new ArrayList<>(); - @Override - public Collection getAuthorities() { - return Collections.singleton(new SimpleGrantedAuthority(role.name())); - } - - @Override - public String getPassword() { - return this.password; - } - - @Override - public String getUsername() { - return this.email; - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return true; - } - public void updateProfile(SellerRequest.MyPagePutDto request) { - this.nickname = request.nickname(); this.address = request.address(); - this.phoneNum = request.phoneNum(); + this.setNickname(request.nickname()); // 상위클래스인 UserEntity에 업데이트 + this.setPhoneNum(request.phoneNum()); // 상위클래스인 UserEntity에 업데이트 } - public static Seller from(Long sellerId, String nickname, Gender gender, String email, String password, - String address, String phoneNum, Role role, String realName, - LocalDate registerDate, List productList, List orderList) { - return Seller.builder() - .sellerId(sellerId) - .nickname(nickname) - .password(password) - .gender(gender) - .email(email) - .address(address) - .phoneNum(phoneNum) - .role(role) - .realName(realName) - .registerDate(registerDate) - .productList(productList) - .orderList(orderList) - .build(); - } +// public static Seller from(Long sellerId, String nickname, Gender gender, String email, String password, +// String address, String phoneNum, Role role, String realName, +// LocalDate registerDate, List productList, List orderList) { +// return Seller.builder() +// .sellerId(sellerId) +// .nickname(nickname) +// .password(password) +// .gender(gender)\ +// .email(email) +// .address(address) +// .phoneNum(phoneNum) +// .role(role) +// .realName(realName) +// .registerDate(registerDate) +// .productList(productList) +// .orderList(orderList) +// .build(); +// } } diff --git a/src/main/java/com/kakaoteck/golagola/domain/seller/service/SellerService.java b/src/main/java/com/kakaoteck/golagola/domain/seller/service/SellerService.java index ad0d889..00acf50 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/seller/service/SellerService.java +++ b/src/main/java/com/kakaoteck/golagola/domain/seller/service/SellerService.java @@ -22,8 +22,8 @@ public SellerResponse getMyPage(Seller seller) { .email(seller.getEmail()) .role(seller.getRole()) .address(seller.getAddress()) - .registerDate(seller.getRegisterDate()) - .realName(seller.getRealName()) +// .registerDate(seller.getRegisterDate()) + .realName(seller.getUsername()) .gender(seller.getGender()) .phoneNum(seller.getPhoneNum()) .nickname(seller.getNickname()) @@ -37,8 +37,8 @@ public SellerResponse updateMyPage(Seller seller, SellerRequest.MyPagePutDto req .email(savedSeller.getEmail()) .role(savedSeller.getRole()) .address(savedSeller.getAddress()) - .registerDate(savedSeller.getRegisterDate()) - .realName(savedSeller.getRealName()) +// .registerDate(savedSeller.getRegisterDate()) + .realName(savedSeller.getUsername()) .gender(savedSeller.getGender()) .phoneNum(savedSeller.getPhoneNum()) .nickname(savedSeller.getNickname()) diff --git a/src/main/java/com/kakaoteck/golagola/global/common/BaseEntity.java b/src/main/java/com/kakaoteck/golagola/global/common/BaseEntity.java index 87b6c79..63997d0 100644 --- a/src/main/java/com/kakaoteck/golagola/global/common/BaseEntity.java +++ b/src/main/java/com/kakaoteck/golagola/global/common/BaseEntity.java @@ -3,12 +3,16 @@ import jakarta.persistence.EntityListeners; import jakarta.persistence.MappedSuperclass; import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.experimental.SuperBuilder; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import java.time.LocalDateTime; +@SuperBuilder +@NoArgsConstructor @MappedSuperclass @EntityListeners(AuditingEntityListener.class) @Getter diff --git a/src/main/java/com/kakaoteck/golagola/security/ApplicationAuditAware.java b/src/main/java/com/kakaoteck/golagola/security/ApplicationAuditAware.java index 6c5590f..1993bf1 100644 --- a/src/main/java/com/kakaoteck/golagola/security/ApplicationAuditAware.java +++ b/src/main/java/com/kakaoteck/golagola/security/ApplicationAuditAware.java @@ -25,10 +25,10 @@ public Optional getCurrentAuditor() { if (principal instanceof Seller) { Seller seller = (Seller) principal; - return Optional.ofNullable(seller.getSellerId()); + return Optional.ofNullable(seller.getId()); } else if (principal instanceof Buyer) { Buyer buyer = (Buyer) principal; - return Optional.ofNullable(buyer.getBuyerId()); + return Optional.ofNullable(buyer.getId()); } else { return Optional.empty(); } diff --git a/src/main/java/com/kakaoteck/golagola/security/filter/JwtAuthenticationFilter.java b/src/main/java/com/kakaoteck/golagola/security/filter/JwtAuthenticationFilter.java index e155841..2f1f77a 100644 --- a/src/main/java/com/kakaoteck/golagola/security/filter/JwtAuthenticationFilter.java +++ b/src/main/java/com/kakaoteck/golagola/security/filter/JwtAuthenticationFilter.java @@ -1,69 +1,69 @@ -package com.kakaoteck.golagola.security.filter; - -import com.kakaoteck.golagola.security.service.JwtService; -import com.kakaoteck.golagola.security.token.TokenRepository; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; -import org.springframework.stereotype.Component; -import org.springframework.web.filter.OncePerRequestFilter; -import java.io.IOException; - -@Component -@RequiredArgsConstructor -public class JwtAuthenticationFilter extends OncePerRequestFilter { - - private final JwtService jwtService; - private final UserDetailsService userDetailsService; - private final TokenRepository tokenRepository; - - @Override - protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { - - final String authHeader = request.getHeader("Authorization"); - final String jwt; - final String userEmail; - - if (request.getServletPath().contains("/api/v1/auth")) { - filterChain.doFilter(request, response); - return; - } - - if (authHeader == null || !authHeader.startsWith("Bearer")) { - filterChain.doFilter(request, response); - return; - } - - jwt = authHeader.substring(7); - userEmail = jwtService.extractUserName(jwt); - - if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) { - UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail); - - var isTokenValid = tokenRepository.findByToken(jwt) - .map(t -> !t.isExpired() && !t.isRevoked()) - .orElse(false); - - if (jwtService.isTokenValid(jwt, userDetails) && isTokenValid) { - UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( - userDetails, - null, - userDetails.getAuthorities() - ); - authToken.setDetails( - new WebAuthenticationDetailsSource().buildDetails(request) - ); - SecurityContextHolder.getContext().setAuthentication(authToken); - } - } - filterChain.doFilter(request, response); - } -} +//package com.kakaoteck.golagola.security.filter; +// +//import com.kakaoteck.golagola.security.service.JwtService; +//import com.kakaoteck.golagola.security.token.TokenRepository; +//import jakarta.servlet.FilterChain; +//import jakarta.servlet.ServletException; +//import jakarta.servlet.http.HttpServletRequest; +//import jakarta.servlet.http.HttpServletResponse; +//import lombok.NonNull; +//import lombok.RequiredArgsConstructor; +//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +//import org.springframework.security.core.context.SecurityContextHolder; +//import org.springframework.security.core.userdetails.UserDetails; +//import org.springframework.security.core.userdetails.UserDetailsService; +//import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +//import org.springframework.stereotype.Component; +//import org.springframework.web.filter.OncePerRequestFilter; +//import java.io.IOException; +// +//@Component +//@RequiredArgsConstructor +//public class JwtAuthenticationFilter extends OncePerRequestFilter { +// +// private final JwtService jwtService; +// private final UserDetailsService userDetailsService; +// private final TokenRepository tokenRepository; +// +// @Override +// protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { +// +// final String authHeader = request.getHeader("Authorization"); +// final String jwt; +// final String userEmail; +// +// if (request.getServletPath().contains("/api/v1/auth")) { +// filterChain.doFilter(request, response); +// return; +// } +// +// if (authHeader == null || !authHeader.startsWith("Bearer")) { +// filterChain.doFilter(request, response); +// return; +// } +// +// jwt = authHeader.substring(7); +// userEmail = jwtService.extractUserName(jwt); +// +// if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) { +// UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail); +// +// var isTokenValid = tokenRepository.findByToken(jwt) +// .map(t -> !t.isExpired() && !t.isRevoked()) +// .orElse(false); +// +// if (jwtService.isTokenValid(jwt, userDetails) && isTokenValid) { +// UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( +// userDetails, +// null, +// userDetails.getAuthorities() +// ); +// authToken.setDetails( +// new WebAuthenticationDetailsSource().buildDetails(request) +// ); +// SecurityContextHolder.getContext().setAuthentication(authToken); +// } +// } +// filterChain.doFilter(request, response); +// } +//} diff --git a/src/main/java/com/kakaoteck/golagola/security/jwt/JWTFilter.java b/src/main/java/com/kakaoteck/golagola/security/jwt/JWTFilter.java index 8d3b6d5..3033328 100644 --- a/src/main/java/com/kakaoteck/golagola/security/jwt/JWTFilter.java +++ b/src/main/java/com/kakaoteck/golagola/security/jwt/JWTFilter.java @@ -76,7 +76,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse // userDTO를 생성하여 값 set UserDTO userDTO = new UserDTO(); userDTO.setUsername(username); - userDTO.setRole(role); +// userDTO.setRole(role); // buyer, seller받아오는걸로 바꾸기 + // UserDetails에 회원 정보 객체 담기 CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDTO); diff --git a/src/main/java/com/kakaoteck/golagola/security/service/LogoutService.java b/src/main/java/com/kakaoteck/golagola/security/service/LogoutService.java index c7ef107..e0f1a55 100644 --- a/src/main/java/com/kakaoteck/golagola/security/service/LogoutService.java +++ b/src/main/java/com/kakaoteck/golagola/security/service/LogoutService.java @@ -1,78 +1,78 @@ -package com.kakaoteck.golagola.security.service; - -import com.kakaoteck.golagola.security.token.TokenBlackList; -import com.kakaoteck.golagola.security.token.TokenBlackListRepository; -import com.kakaoteck.golagola.security.token.TokenRepository; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.authentication.logout.LogoutHandler; -import org.springframework.stereotype.Service; - -import java.io.IOException; - -@Service -@RequiredArgsConstructor -public class LogoutService implements LogoutHandler { - - private final TokenRepository tokenRepository; - private final TokenBlackListRepository tokenBlackListRepository; - private static final Logger logger = LoggerFactory.getLogger(LogoutService.class); - - @Override - public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { - final String authHeader = request.getHeader("Authorization"); - if (authHeader == null || !authHeader.startsWith("Bearer ")) { - sendErrorResponse(response, "Token is missing or invalid"); - return; - } - - final String jwt = authHeader.substring(7); - var storedToken = tokenRepository.findByToken(jwt).orElse(null); - if (storedToken == null || storedToken.isExpired()) { - sendErrorResponse(response, "Token is missing or invalid"); - } else { - if (!tokenBlackListRepository.existsByToken(jwt) ) { - TokenBlackList blackList = new TokenBlackList(); - blackList.setToken(jwt); - tokenBlackListRepository.save(blackList); - storedToken.setExpired(true); - storedToken.setRevoked(true); - tokenRepository.save(storedToken); - SecurityContextHolder.clearContext(); - - sendSuccessResponse(response); - - } else { - sendErrorResponse(response, "Can't use this token"); - } - } - } - - private void sendErrorResponse(HttpServletResponse response, String message) { - try { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - response.setContentType("application/json"); - response.getWriter().write("{\"message\": \"" + message + "\"}"); - response.getWriter().flush(); - } catch (IOException e) { - logger.error("Error writing response", e); - } - } - - private void sendSuccessResponse(HttpServletResponse response) { - try { - response.setStatus(HttpServletResponse.SC_OK); // 200 OK - response.setContentType("application/json"); - response.getWriter().write("{\"message\": \"" + "logout" + "\"}"); - response.getWriter().flush(); - } catch (IOException e) { - logger.error("Error writing response", e); - } - } - -} \ No newline at end of file +//package com.kakaoteck.golagola.security.service; +// +//import com.kakaoteck.golagola.security.token.TokenBlackList; +//import com.kakaoteck.golagola.security.token.TokenBlackListRepository; +//import com.kakaoteck.golagola.security.token.TokenRepository; +//import jakarta.servlet.http.HttpServletRequest; +//import jakarta.servlet.http.HttpServletResponse; +//import lombok.RequiredArgsConstructor; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +//import org.springframework.security.core.Authentication; +//import org.springframework.security.core.context.SecurityContextHolder; +//import org.springframework.security.web.authentication.logout.LogoutHandler; +//import org.springframework.stereotype.Service; +// +//import java.io.IOException; +// +//@Service +//@RequiredArgsConstructor +//public class LogoutService implements LogoutHandler { +// +// private final TokenRepository tokenRepository; +// private final TokenBlackListRepository tokenBlackListRepository; +// private static final Logger logger = LoggerFactory.getLogger(LogoutService.class); +// +// @Override +// public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { +// final String authHeader = request.getHeader("Authorization"); +// if (authHeader == null || !authHeader.startsWith("Bearer ")) { +// sendErrorResponse(response, "Token is missing or invalid"); +// return; +// } +// +// final String jwt = authHeader.substring(7); +// var storedToken = tokenRepository.findByToken(jwt).orElse(null); +// if (storedToken == null || storedToken.isExpired()) { +// sendErrorResponse(response, "Token is missing or invalid"); +// } else { +// if (!tokenBlackListRepository.existsByToken(jwt) ) { +// TokenBlackList blackList = new TokenBlackList(); +// blackList.setToken(jwt); +// tokenBlackListRepository.save(blackList); +// storedToken.setExpired(true); +// storedToken.setRevoked(true); +// tokenRepository.save(storedToken); +// SecurityContextHolder.clearContext(); +// +// sendSuccessResponse(response); +// +// } else { +// sendErrorResponse(response, "Can't use this token"); +// } +// } +// } +// +// private void sendErrorResponse(HttpServletResponse response, String message) { +// try { +// response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); +// response.setContentType("application/json"); +// response.getWriter().write("{\"message\": \"" + message + "\"}"); +// response.getWriter().flush(); +// } catch (IOException e) { +// logger.error("Error writing response", e); +// } +// } +// +// private void sendSuccessResponse(HttpServletResponse response) { +// try { +// response.setStatus(HttpServletResponse.SC_OK); // 200 OK +// response.setContentType("application/json"); +// response.getWriter().write("{\"message\": \"" + "logout" + "\"}"); +// response.getWriter().flush(); +// } catch (IOException e) { +// logger.error("Error writing response", e); +// } +// } +// +//} \ No newline at end of file diff --git a/src/main/java/com/kakaoteck/golagola/security/token/TokenRepository.java b/src/main/java/com/kakaoteck/golagola/security/token/TokenRepository.java index 6e9ad38..9b64902 100644 --- a/src/main/java/com/kakaoteck/golagola/security/token/TokenRepository.java +++ b/src/main/java/com/kakaoteck/golagola/security/token/TokenRepository.java @@ -1,25 +1,25 @@ -package com.kakaoteck.golagola.security.token; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import java.util.List; -import java.util.Optional; - -public interface TokenRepository extends JpaRepository { - - @Query(value = """ - select t from Token t inner join Buyer u on t.buyer.buyerId = u.buyerId - where u.buyerId = :id and (t.expired = false or t.revoked = false) - """) - List findAllValidTokenByBuyer(@Param("id") Long id); - - @Query(value = """ - select t from Token t inner join Seller u on t.seller.sellerId = u.sellerId - where u.sellerId = :id and (t.expired = false or t.revoked = false) - """) - List findAllValidTokenBySeller(@Param("id") Long id); - - Optional findByToken(String token); -} +//package com.kakaoteck.golagola.security.token; +// +//import org.springframework.data.jpa.repository.JpaRepository; +//import org.springframework.data.jpa.repository.Query; +//import org.springframework.data.repository.query.Param; +// +//import java.util.List; +//import java.util.Optional; +// +//public interface TokenRepository extends JpaRepository { +// +// @Query(value = """ +// select t from Token t inner join Buyer u on t.buyer.buyerId = u.buyerId +// where u.buyerId = :id and (t.expired = false or t.revoked = false) +// """) +// List findAllValidTokenByBuyer(@Param("id") Long id); +// +// @Query(value = """ +// select t from Token t inner join Seller u on t.seller.sellerId = u.sellerId +// where u.sellerId = :id and (t.expired = false or t.revoked = false) +// """) +// List findAllValidTokenBySeller(@Param("id") Long id); +// +// Optional findByToken(String token); +//} diff --git a/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java b/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java index c57f6a8..0251030 100644 --- a/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java +++ b/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java @@ -51,7 +51,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic userEntity.setUsername(username); // ex) kakao 3664463254 userEntity.setEmail(oAuth2Response.getEmail()); // ex) tiger1650@naver.com userEntity.setName(oAuth2Response.getName()); // ex) 이용우 - userEntity.setRole("ROLE_USER"); // ex) ROLE_USER +// userEntity.setRole("ROLE_USER"); // ex) ROLE_USER // 리프레시 토큰 넣기 @@ -60,7 +60,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic UserDTO userDTO = new UserDTO(); userDTO.setUsername(username); userDTO.setName(oAuth2Response.getName()); - userDTO.setRole("ROLE_USER"); +// userDTO.setRole("ROLE_USER"); return new CustomOAuth2User(userDTO); } @@ -76,7 +76,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic UserDTO userDTO = new UserDTO(); userDTO.setUsername(username); userDTO.setName(oAuth2Response.getName()); - userDTO.setRole("ROLE_USER"); +// userDTO.setRole("ROLE_USER"); return new CustomOAuth2User(userDTO); } From c53890cd6591d0a25279b0c62a38ac6482eff35c Mon Sep 17 00:00:00 2001 From: leeyongwoo <95459741+softwareyong@users.noreply.github.com> Date: Thu, 5 Sep 2024 17:04:06 +0900 Subject: [PATCH 2/2] =?UTF-8?q?SCRUM-77=20feat:=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=ED=95=84=20=EC=82=AC=EC=A7=84=20=EC=A0=80=EC=9E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/Repository/UserRepository.java | 10 +++ .../auth/controller/AuthController.java | 85 ++++++++----------- .../golagola/domain/auth/dto/AuthRequest.java | 8 +- .../domain/auth/dto/CustomOAuth2User.java | 34 +++++++- .../domain/auth/dto/KakaoResponse.java | 7 ++ .../domain/auth/dto/NaverResponse.java | 5 ++ .../domain/auth/dto/OAuth2KakaoResponse.java | 11 +++ .../domain/auth/dto/OAuth2Response.java | 3 +- .../golagola/domain/auth/dto/UserDTO.java | 4 +- .../domain/auth/entity/UserEntity.java | 16 ++-- .../domain/auth/service/AuthService1.java | 29 +++++++ .../buyer/controller/BuyerController.java | 25 +++++- .../golagola/domain/buyer/entity/Buyer.java | 25 +++--- .../buyer/repository/BuyerRepository.java | 13 ++- .../domain/buyer/service/BuyerService.java | 22 ++--- .../golagola/domain/order/entity/Order.java | 2 +- .../domain/product/entity/Product.java | 4 +- .../product/service/ProductService.java | 4 +- .../golagola/domain/review/entity/Review.java | 2 +- .../golagola/domain/seller/entity/Seller.java | 23 +++-- .../seller/repository/SellerRepository.java | 13 ++- .../domain/seller/service/SellerService.java | 21 ++--- .../golagola/global/common/BaseEntity.java | 4 +- .../security/ApplicationAuditAware.java | 4 +- .../handler/signin/CustomSuccessHandler.java | 2 +- .../service/CustomOAuth2UserService.java | 8 +- src/main/resources/application.properties | 2 +- 27 files changed, 263 insertions(+), 123 deletions(-) create mode 100644 src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2KakaoResponse.java create mode 100644 src/main/java/com/kakaoteck/golagola/domain/auth/service/AuthService1.java diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java b/src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java index a549637..c0ea669 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java @@ -1,6 +1,8 @@ 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; @@ -20,6 +22,14 @@ public interface UserRepository extends JpaRepository { 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); + } diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/controller/AuthController.java b/src/main/java/com/kakaoteck/golagola/domain/auth/controller/AuthController.java index d4368ef..dfb1f7a 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/controller/AuthController.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/controller/AuthController.java @@ -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.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; -// -//@RequiredArgsConstructor -//@RequestMapping("/api/v1/auth") -//@RestController -//@CrossOrigin("*") -//public class AuthController { -// -// private final AuthService authService; -// -// @Operation(summary = "회원가입 기능", description = "gender 값: MALE or FEMALE") -// @PostMapping("/join") -// public ApiResponse join(@RequestBody JoinUserRequest request) { -// authService.register(request); -// return ApiResponse.onSuccess("회원가입 성공"); -// } -// -// @Operation(summary = "이메일 중복 검사 버튼", description = "회원가입 과정에서 이메일 중복 검사를 진행합니다.\ntrue = 이미 존재하는 이메일, false = 가입 가능한 이메일") -// @GetMapping("/join/email-check/{email}") -// public ApiResponse checkEmailExists( -// @PathVariable(name = "email") String email -// ) { -// return ApiResponse.onSuccess(authService.checkEmailExists(email)); -// } -// -// @PostMapping("/login") -// public ApiResponse 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); -// } -//} \ No newline at end of file +package com.kakaoteck.golagola.domain.auth.controller; + + +import com.kakaoteck.golagola.domain.auth.dto.AuthRequest; +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 lombok.RequiredArgsConstructor; +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 +@RestController +@RequestMapping("/api/v1/auth") +public class AuthController { + + private final AuthService1 authService; + + @Operation(summary = "회원가입 추가정보 진행", description = "(nickname, gender) 저장") + @PostMapping("/join") + public ApiResponse join(@RequestBody AuthRequest authRequest) { + // 1. jwt 세션 접근 + CustomOAuth2User customUser = (CustomOAuth2User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + String username = customUser.getUsername(); + + // 2. UserService를 통해 (nickname, gender) 저장 + authService.saveUserDetails(username, authRequest); + + return ApiResponse.onSuccess("회원가입 성공"); + } +} diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/AuthRequest.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/AuthRequest.java index f94e011..de3641e 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/AuthRequest.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/AuthRequest.java @@ -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 ) { } diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/CustomOAuth2User.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/CustomOAuth2User.java index 0747c8d..27b79b0 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/CustomOAuth2User.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/CustomOAuth2User.java @@ -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 getAttribute(String name) { + return OAuth2User.super.getAttribute(name); + } + @Override public Map getAttributes() { return Map.of(); diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/KakaoResponse.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/KakaoResponse.java index 3448c19..0129595 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/KakaoResponse.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/KakaoResponse.java @@ -37,4 +37,11 @@ public String getName() { Map profile = (Map) kakaoAccount.get("profile"); return profile.get("nickname").toString(); } + + @Override + public String getImage() { + Map kakaoAccount = (Map) attribute.get("kakao_account"); + Map profile = (Map) kakaoAccount.get("profile"); + return profile.get("profile_image_url").toString(); + } } diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/NaverResponse.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/NaverResponse.java index 9187b11..a0949cb 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/NaverResponse.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/NaverResponse.java @@ -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(); + } } diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2KakaoResponse.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2KakaoResponse.java new file mode 100644 index 0000000..d66ebfd --- /dev/null +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2KakaoResponse.java @@ -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(); //사용자 실명 (설정한 이름) + +} diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2Response.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2Response.java index 423ed92..90d9286 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2Response.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2Response.java @@ -10,5 +10,6 @@ public interface OAuth2Response { String getEmail(); //사용자 실명 (설정한 이름) String getName(); - + //사용자 프로필 사진 + String getImage(); } diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/UserDTO.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/UserDTO.java index 53ae51d..8912a25 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/dto/UserDTO.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/UserDTO.java @@ -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 추가 } diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java b/src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java index 33f09b1..9eac6d2 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java @@ -1,9 +1,12 @@ package com.kakaoteck.golagola.domain.auth.entity; +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; @@ -17,12 +20,8 @@ @Entity @Getter @Setter -@SuperBuilder // 추가 -@NoArgsConstructor @Table(name = "users") -@Inheritance(strategy = InheritanceType.SINGLE_TABLE) -@DiscriminatorColumn(name = "entity_type") -public class UserEntity extends BaseEntity implements UserDetails { +public class UserEntity implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -34,6 +33,7 @@ public class UserEntity extends BaseEntity implements UserDetails { private String phoneNum; private String nickname; // @Column(nullable = false) + private String image; @Enumerated(EnumType.STRING) @Column(nullable = false) @@ -43,6 +43,12 @@ public class UserEntity extends BaseEntity implements UserDetails { 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(); diff --git a/src/main/java/com/kakaoteck/golagola/domain/auth/service/AuthService1.java b/src/main/java/com/kakaoteck/golagola/domain/auth/service/AuthService1.java new file mode 100644 index 0000000..22b1df4 --- /dev/null +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/service/AuthService1.java @@ -0,0 +1,29 @@ +package com.kakaoteck.golagola.domain.auth.service; + +import com.kakaoteck.golagola.domain.auth.Repository.UserRepository; +import com.kakaoteck.golagola.domain.auth.dto.AuthRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class AuthService1 { + + private final UserRepository userRepository; + + @Transactional + public void saveUserDetails(String username, AuthRequest authRequest) { + // 1. username으로 해당 유저가 존재하는지 확인 + userRepository.findByUsername(username).ifPresentOrElse(user -> { + // 2. 유저가 존재하면 닉네임과 성별을 업데이트 + userRepository.updateUserInfo(username, authRequest.nickName(), authRequest.gender()); + }, () -> { + // 3. 존재하지 않을 경우 예외 처리 또는 다른 로직 수행 + throw new IllegalArgumentException("User with username " + username + " not found."); + }); + } + + + +} diff --git a/src/main/java/com/kakaoteck/golagola/domain/buyer/controller/BuyerController.java b/src/main/java/com/kakaoteck/golagola/domain/buyer/controller/BuyerController.java index 5531ec0..5d63ac6 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/buyer/controller/BuyerController.java +++ b/src/main/java/com/kakaoteck/golagola/domain/buyer/controller/BuyerController.java @@ -1,5 +1,6 @@ package com.kakaoteck.golagola.domain.buyer.controller; +import com.kakaoteck.golagola.domain.auth.dto.CustomOAuth2User; import com.kakaoteck.golagola.domain.buyer.dto.BuyerRequest; import com.kakaoteck.golagola.domain.buyer.dto.BuyerResponse; import com.kakaoteck.golagola.domain.buyer.entity.Buyer; @@ -8,8 +9,11 @@ import io.swagger.v3.oas.annotations.Operation; import lombok.RequiredArgsConstructor; import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; +import java.sql.SQLOutput; + @RestController @RequiredArgsConstructor @RequestMapping("/api/v1/buyer") @@ -17,12 +21,25 @@ public class BuyerController { private final BuyerService buyerService; +// @Operation(summary = "구매자 마이페이지 조회", description = "구매자의 정보를 조회합니다.") +// @GetMapping("/mypage") +// public ApiResponse getMyPage() { +// // 1. jwt 세션 접근 +// CustomOAuth2User customUser = (CustomOAuth2User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); +// String username = customUser.getUsername(); +// +// return ApiResponse.onSuccess(BuyerService.getMyPage(username)); +// } + @Operation(summary = "구매자 마이페이지 조회", description = "구매자의 정보를 조회합니다.") @GetMapping("/mypage") - public ApiResponse getMyPage( - @AuthenticationPrincipal Buyer buyer - ) { - return ApiResponse.onSuccess(BuyerService.getMyPage(buyer)); + public String getMyPage(@AuthenticationPrincipal CustomOAuth2User customUser) { + // 1. jwt 세션 접근 +// CustomOAuth2User customUser = (CustomOAuth2User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + String username = customUser.getUsername(); + System.out.println("username: " + username); +// return ApiResponse.onSuccess(BuyerService.getMyPage(username)); + return "good"; } @Operation(summary = "구매자 마이페이지 수정", description = "구매자의 정보를 수정합니다.") diff --git a/src/main/java/com/kakaoteck/golagola/domain/buyer/entity/Buyer.java b/src/main/java/com/kakaoteck/golagola/domain/buyer/entity/Buyer.java index 344dadf..173cafb 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/buyer/entity/Buyer.java +++ b/src/main/java/com/kakaoteck/golagola/domain/buyer/entity/Buyer.java @@ -7,6 +7,7 @@ import com.kakaoteck.golagola.domain.order.entity.Order; import com.kakaoteck.golagola.domain.product.entity.Product; import com.kakaoteck.golagola.domain.review.entity.Review; +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.*; @@ -22,21 +23,25 @@ @NoArgsConstructor @AllArgsConstructor @Getter -@SuperBuilder -//@Table(name = "buyer_table") -@DiscriminatorValue("BUYER") -public class Buyer extends UserEntity { +@Builder +//@SuperBuilder +@Table(name = "buyer_table") +//@DiscriminatorValue("BUYER") +public class Buyer extends BaseEntity { -// @Id -// @GeneratedValue(strategy = GenerationType.IDENTITY) -// private Long buyerId; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long buyerId; + @OneToOne // Buyer는 하나의 UserEntity와만 연결됩니다. + @JoinColumn(name = "user_id", nullable = false) + private UserEntity user; private String address; // @Column(nullable = false) @Enumerated(EnumType.STRING) @Column(nullable = false) - private Role role = Role.valueOf("SELLER"); + private Role role = Role.valueOf("BUYER"); @OneToOne(mappedBy = "buyer", cascade = CascadeType.ALL, orphanRemoval = true) private Cart cart; @@ -49,8 +54,8 @@ public class Buyer extends UserEntity { public void updateProfile(BuyerRequest.MyPagePutDto request) { this.address = request.address(); - this.setNickname(request.nickname()); // 상위클래스인 UserEntity에 업데이트 - this.setPhoneNum(request.phoneNum()); // 상위클래스인 UserEntity에 업데이트 + this.user.setNickname(request.nickname()); // 참조entity에서 UserEntity에 업데이트 + this.user.setPhoneNum(request.phoneNum()); // 참조entity에서 UserEntity에 업데이트 } public void assignCart(Cart cart) { diff --git a/src/main/java/com/kakaoteck/golagola/domain/buyer/repository/BuyerRepository.java b/src/main/java/com/kakaoteck/golagola/domain/buyer/repository/BuyerRepository.java index c21a78f..65544c8 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/buyer/repository/BuyerRepository.java +++ b/src/main/java/com/kakaoteck/golagola/domain/buyer/repository/BuyerRepository.java @@ -1,13 +1,22 @@ package com.kakaoteck.golagola.domain.buyer.repository; import com.kakaoteck.golagola.domain.buyer.entity.Buyer; +import io.lettuce.core.dynamic.annotation.Param; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface BuyerRepository extends JpaRepository { - Optional findByEmail(String email); - boolean existsByEmail(String email); +// Optional findByEmail(String email); +// boolean existsByEmail(String email); + + + @Query("SELECT b FROM Buyer b WHERE b.user.email = :email") + Optional findByEmail(@Param("email") String email); + + @Query("SELECT CASE WHEN COUNT(b) > 0 THEN true ELSE false END FROM Buyer b WHERE b.user.email = :email") + boolean existsByEmail(@Param("email") String email); } diff --git a/src/main/java/com/kakaoteck/golagola/domain/buyer/service/BuyerService.java b/src/main/java/com/kakaoteck/golagola/domain/buyer/service/BuyerService.java index 11ce4e5..e674784 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/buyer/service/BuyerService.java +++ b/src/main/java/com/kakaoteck/golagola/domain/buyer/service/BuyerService.java @@ -18,15 +18,17 @@ public class BuyerService { private final BuyerRepository buyerRepository; public static BuyerResponse getMyPage(Buyer buyer) { + + return BuyerResponse.builder() - .email(buyer.getEmail()) + .email(buyer.getUser().getEmail()) .role(buyer.getRole()) .address(buyer.getAddress()) // .registerDate(buyer.getRegisterDate()) - .realName(buyer.getUsername()) - .gender(buyer.getGender()) - .phoneNum(buyer.getPhoneNum()) - .nickname(buyer.getNickname()) + .realName(buyer.getUser().getName()) + .gender(buyer.getUser().getGender()) + .phoneNum(buyer.getUser().getPhoneNum()) + .nickname(buyer.getUser().getNickname()) .build(); } @@ -34,14 +36,14 @@ public BuyerResponse updateMyPage(Buyer buyer, BuyerRequest.MyPagePutDto request buyer.updateProfile(request); Buyer savedBuyer = buyerRepository.save(buyer); return BuyerResponse.builder() - .email(savedBuyer.getEmail()) + .email(savedBuyer.getUser().getEmail()) .role(savedBuyer.getRole()) .address(savedBuyer.getAddress()) // .registerDate(savedBuyer.getRegisterDate()) - .realName(savedBuyer.getUsername()) - .gender(savedBuyer.getGender()) - .phoneNum(savedBuyer.getPhoneNum()) - .nickname(savedBuyer.getNickname()) + .realName(savedBuyer.getUser().getName()) + .gender(savedBuyer.getUser().getGender()) + .phoneNum(savedBuyer.getUser().getPhoneNum()) + .nickname(savedBuyer.getUser().getNickname()) .build(); } diff --git a/src/main/java/com/kakaoteck/golagola/domain/order/entity/Order.java b/src/main/java/com/kakaoteck/golagola/domain/order/entity/Order.java index 8c54322..bc02576 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/order/entity/Order.java +++ b/src/main/java/com/kakaoteck/golagola/domain/order/entity/Order.java @@ -17,9 +17,9 @@ @Entity @NoArgsConstructor +@Builder @AllArgsConstructor @Getter -@SuperBuilder @Table(name = "order_table") // order가 mySQL 예약어임 이슈 ! public class Order extends BaseEntity { diff --git a/src/main/java/com/kakaoteck/golagola/domain/product/entity/Product.java b/src/main/java/com/kakaoteck/golagola/domain/product/entity/Product.java index 8b5ed07..4d0313c 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/product/entity/Product.java +++ b/src/main/java/com/kakaoteck/golagola/domain/product/entity/Product.java @@ -19,10 +19,10 @@ import java.util.List; @Entity -@NoArgsConstructor @AllArgsConstructor +@NoArgsConstructor @Getter -@SuperBuilder +@Builder @Table(name = "product_table") public class Product extends BaseEntity { diff --git a/src/main/java/com/kakaoteck/golagola/domain/product/service/ProductService.java b/src/main/java/com/kakaoteck/golagola/domain/product/service/ProductService.java index 48e3c10..6a249e4 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/product/service/ProductService.java +++ b/src/main/java/com/kakaoteck/golagola/domain/product/service/ProductService.java @@ -55,7 +55,7 @@ public ProductResponse modifyProduct(Seller seller, Long productId, ProductReque .orElseThrow(() -> new GeneralException(ErrorStatus._NOT_FOUND_PRODUCT)); // 해당 상품이 현재 로그인한 seller가 등록한 것인지 확인 - if (!product.getSeller().getId().equals(seller.getId())) { + if (!product.getSeller().getUser().getSeller().getSellerId().equals(seller.getSellerId())) { throw new GeneralException(ErrorStatus._UNAUTHORIZED_ACCESS); } @@ -96,7 +96,7 @@ public void deleteProduct(Seller seller, Long productId) { .orElseThrow(() -> new GeneralException(ErrorStatus._NOT_FOUND_PRODUCT)); // 해당 Product가 현재 로그인된 seller가 등록한 제품인지 확인 - if (!product.getSeller().getId().equals(seller.getId())) { + if (!product.getSeller().getUser().getSeller().getSellerId().equals(seller.getSellerId())) { throw new GeneralException(ErrorStatus._UNAUTHORIZED_ACCESS); } diff --git a/src/main/java/com/kakaoteck/golagola/domain/review/entity/Review.java b/src/main/java/com/kakaoteck/golagola/domain/review/entity/Review.java index b600369..ef93308 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/review/entity/Review.java +++ b/src/main/java/com/kakaoteck/golagola/domain/review/entity/Review.java @@ -16,7 +16,7 @@ @Entity @NoArgsConstructor @AllArgsConstructor -@SuperBuilder +@Builder @Getter @Table(name = "review_table") public class Review extends BaseEntity { diff --git a/src/main/java/com/kakaoteck/golagola/domain/seller/entity/Seller.java b/src/main/java/com/kakaoteck/golagola/domain/seller/entity/Seller.java index 5abb67f..71b6954 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/seller/entity/Seller.java +++ b/src/main/java/com/kakaoteck/golagola/domain/seller/entity/Seller.java @@ -30,20 +30,25 @@ @NoArgsConstructor @AllArgsConstructor @Getter -@SuperBuilder -//@Table(name = "seller_table") -@DiscriminatorValue("SELLER") -public class Seller extends UserEntity { +//@SuperBuilder +@Table(name = "seller_table") +//@DiscriminatorValue("SELLER") +public class Seller extends BaseEntity{ + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long sellerId; -// @Id -// @GeneratedValue(strategy = GenerationType.IDENTITY) -// private Long sellerId; private String address; // @Column(nullable = false) @Enumerated(EnumType.STRING) @Column(nullable = false) private Role role = Role.valueOf("SELLER"); + @OneToOne // Seller는 하나의 UserEntity와만 연결됩니다. + @JoinColumn(name = "user_id", nullable = false) + private UserEntity user; + @OneToMany(mappedBy = "seller", cascade = CascadeType.ALL) @JsonManagedReference private List productList = new ArrayList<>(); @@ -53,8 +58,8 @@ public class Seller extends UserEntity { public void updateProfile(SellerRequest.MyPagePutDto request) { this.address = request.address(); - this.setNickname(request.nickname()); // 상위클래스인 UserEntity에 업데이트 - this.setPhoneNum(request.phoneNum()); // 상위클래스인 UserEntity에 업데이트 + this.user.setNickname(request.nickname()); // 참조entity에서 UserEntity에 업데이트 + this.user.setPhoneNum(request.phoneNum()); // 참조entity에서 UserEntity에 업데이트 } // public static Seller from(Long sellerId, String nickname, Gender gender, String email, String password, diff --git a/src/main/java/com/kakaoteck/golagola/domain/seller/repository/SellerRepository.java b/src/main/java/com/kakaoteck/golagola/domain/seller/repository/SellerRepository.java index f4ea8c4..e3b8ff1 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/seller/repository/SellerRepository.java +++ b/src/main/java/com/kakaoteck/golagola/domain/seller/repository/SellerRepository.java @@ -1,13 +1,22 @@ package com.kakaoteck.golagola.domain.seller.repository; +import com.kakaoteck.golagola.domain.buyer.entity.Buyer; import com.kakaoteck.golagola.domain.seller.entity.Seller; +import io.lettuce.core.dynamic.annotation.Param; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface SellerRepository extends JpaRepository { - Optional findByEmail(String email); - boolean existsByEmail(String email); +// Optional findByEmail(String email); +// boolean existsByEmail(String email); + + @Query("SELECT b FROM Seller b WHERE b.user.email = :email") + Optional findByEmail(@Param("email") String email); + + @Query("SELECT CASE WHEN COUNT(b) > 0 THEN true ELSE false END FROM Seller b WHERE b.user.email = :email") + boolean existsByEmail(@Param("email") String email); } diff --git a/src/main/java/com/kakaoteck/golagola/domain/seller/service/SellerService.java b/src/main/java/com/kakaoteck/golagola/domain/seller/service/SellerService.java index 00acf50..6e36647 100644 --- a/src/main/java/com/kakaoteck/golagola/domain/seller/service/SellerService.java +++ b/src/main/java/com/kakaoteck/golagola/domain/seller/service/SellerService.java @@ -19,29 +19,30 @@ public class SellerService { public SellerResponse getMyPage(Seller seller) { return SellerResponse.builder() - .email(seller.getEmail()) + .email(seller.getUser().getEmail()) .role(seller.getRole()) .address(seller.getAddress()) // .registerDate(seller.getRegisterDate()) - .realName(seller.getUsername()) - .gender(seller.getGender()) - .phoneNum(seller.getPhoneNum()) - .nickname(seller.getNickname()) + .realName(seller.getUser().getName()) + .gender(seller.getUser().getGender()) + .phoneNum(seller.getUser().getPhoneNum()) + .nickname(seller.getUser().getNickname()) .build(); + } public SellerResponse updateMyPage(Seller seller, SellerRequest.MyPagePutDto request) { seller.updateProfile(request); Seller savedSeller = sellerRepository.save(seller); return SellerResponse.builder() - .email(savedSeller.getEmail()) + .email(savedSeller.getUser().getEmail()) .role(savedSeller.getRole()) .address(savedSeller.getAddress()) // .registerDate(savedSeller.getRegisterDate()) - .realName(savedSeller.getUsername()) - .gender(savedSeller.getGender()) - .phoneNum(savedSeller.getPhoneNum()) - .nickname(savedSeller.getNickname()) + .realName(savedSeller.getUser().getName()) + .gender(savedSeller.getUser().getGender()) + .phoneNum(savedSeller.getUser().getPhoneNum()) + .nickname(savedSeller.getUser().getNickname()) .build(); } } diff --git a/src/main/java/com/kakaoteck/golagola/global/common/BaseEntity.java b/src/main/java/com/kakaoteck/golagola/global/common/BaseEntity.java index 63997d0..8e6180c 100644 --- a/src/main/java/com/kakaoteck/golagola/global/common/BaseEntity.java +++ b/src/main/java/com/kakaoteck/golagola/global/common/BaseEntity.java @@ -11,11 +11,9 @@ import java.time.LocalDateTime; -@SuperBuilder -@NoArgsConstructor +@Getter @MappedSuperclass @EntityListeners(AuditingEntityListener.class) -@Getter public class BaseEntity { @CreatedDate diff --git a/src/main/java/com/kakaoteck/golagola/security/ApplicationAuditAware.java b/src/main/java/com/kakaoteck/golagola/security/ApplicationAuditAware.java index 1993bf1..6c5590f 100644 --- a/src/main/java/com/kakaoteck/golagola/security/ApplicationAuditAware.java +++ b/src/main/java/com/kakaoteck/golagola/security/ApplicationAuditAware.java @@ -25,10 +25,10 @@ public Optional getCurrentAuditor() { if (principal instanceof Seller) { Seller seller = (Seller) principal; - return Optional.ofNullable(seller.getId()); + return Optional.ofNullable(seller.getSellerId()); } else if (principal instanceof Buyer) { Buyer buyer = (Buyer) principal; - return Optional.ofNullable(buyer.getId()); + return Optional.ofNullable(buyer.getBuyerId()); } else { return Optional.empty(); } diff --git a/src/main/java/com/kakaoteck/golagola/security/handler/signin/CustomSuccessHandler.java b/src/main/java/com/kakaoteck/golagola/security/handler/signin/CustomSuccessHandler.java index 4b071f4..eccea0d 100644 --- a/src/main/java/com/kakaoteck/golagola/security/handler/signin/CustomSuccessHandler.java +++ b/src/main/java/com/kakaoteck/golagola/security/handler/signin/CustomSuccessHandler.java @@ -60,7 +60,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo // 쿠키 설정 response.addCookie(createCookie("Authorization", token)); // 쿠키를 넣어준다. response.addCookie(createCookie("RefreshToken", refreshToken)); // 리프레시 토큰도 쿠키로 추가 - response.sendRedirect("http://localhost:8080/"); // 프론트쪽으로 특정 uri로 리다이렉트 + response.sendRedirect("http://localhost:3000"); // 프론트쪽으로 특정 uri로 리다이렉트 } private Cookie createCookie(String key, String value) { diff --git a/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java b/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java index 0251030..2a7331c 100644 --- a/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java +++ b/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java @@ -3,12 +3,17 @@ import com.kakaoteck.golagola.domain.auth.Repository.UserRepository; import com.kakaoteck.golagola.domain.auth.dto.*; import com.kakaoteck.golagola.domain.auth.entity.UserEntity; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.stereotype.Service; +import java.util.Collection; +import java.util.List; import java.util.Optional; // DefaultOAuth2UserService: OAuth2에서 기본적으로 유저를 저장하는 메서드를 가지고 있다. @@ -51,10 +56,10 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic userEntity.setUsername(username); // ex) kakao 3664463254 userEntity.setEmail(oAuth2Response.getEmail()); // ex) tiger1650@naver.com userEntity.setName(oAuth2Response.getName()); // ex) 이용우 + userEntity.setImage(oAuth2Response.getImage()); // ex) 프로필 이미지 // userEntity.setRole("ROLE_USER"); // ex) ROLE_USER // 리프레시 토큰 넣기 - userRepository.save(userEntity); UserDTO userDTO = new UserDTO(); @@ -70,6 +75,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic UserEntity existData = optionalUserEntity.get(); existData.setEmail(oAuth2Response.getEmail()); existData.setName(oAuth2Response.getName()); + existData.setImage(oAuth2Response.getImage()); userRepository.save(existData); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 7095e06..a225c72 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -6,7 +6,7 @@ spring.datasource.url=jdbc:mysql://localhost:3306/golagola?useSSL=false&useUnico spring.datasource.username=root spring.datasource.password=00000000 -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl # JWT