Skip to content

Commit

Permalink
SCRUM-77 feat: buyer Authentication으로 받기
Browse files Browse the repository at this point in the history
  • Loading branch information
softwareyong committed Sep 7, 2024
1 parent c53890c commit d6cdc81
Show file tree
Hide file tree
Showing 18 changed files with 286 additions and 71 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ public class GolagolaApplication {
public static void main(String[] args) {
SpringApplication.run(GolagolaApplication.class, args);
System.out.println("hello, world!");
System.out.println("GoodBye");
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.kakaoteck.golagola.config;

import com.kakaoteck.golagola.domain.auth.Repository.UserRepository;
import com.kakaoteck.golagola.security.handler.signout.CustomSignOutProcessHandler;
import com.kakaoteck.golagola.security.jwt.JWTFilter;
import com.kakaoteck.golagola.security.jwt.JWTUtil;
Expand Down Expand Up @@ -37,6 +38,7 @@ public class SecurityConfig {
private final CustomSuccessHandler customSuccessHandler;
private final JWTUtil jwtUtil;
private final CustomSignOutProcessHandler customSignOutProcessHandler;
private final UserRepository userRepository; // UserRepository 추가

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
Expand Down Expand Up @@ -78,8 +80,8 @@ public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
);

// JWT 필터 설정
http.addFilterBefore(new JWTFilter(jwtUtil), LogoutFilter.class); // 로그아웃 필터전에 jwt필터실행
http.addFilterBefore(new JWTFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(new JWTFilter(jwtUtil, userRepository), LogoutFilter.class); // 로그아웃 필터전에 jwt필터실행
http.addFilterBefore(new JWTFilter(jwtUtil, userRepository), UsernamePasswordAuthenticationFilter.class);
// http.addFilterAfter(new JWTFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class);

// 경로별 인가 작업
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
@Configuration
public class SwaggerConfig {

// url: http://localhost:8080/swagger-ui/index.html#/
// url: http://localhost:8080/swagger-ui/index.html#/
@Bean
public OpenAPI getOpenApi() {
Server server = new Server().url("/");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,18 @@

import com.kakaoteck.golagola.domain.auth.dto.AuthRequest;
import com.kakaoteck.golagola.domain.auth.dto.CustomOAuth2User;
import com.kakaoteck.golagola.domain.auth.dto.UserDTO;
import com.kakaoteck.golagola.domain.auth.entity.UserEntity;
import com.kakaoteck.golagola.domain.auth.service.AuthService1;
import com.kakaoteck.golagola.domain.buyer.entity.Buyer;
import com.kakaoteck.golagola.domain.seller.entity.Seller;
import com.kakaoteck.golagola.global.common.ApiResponse;
import com.kakaoteck.golagola.global.common.enums.Role;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
Expand All @@ -20,16 +28,82 @@ public class AuthController {

private final AuthService1 authService;

@Operation(summary = "회원가입 추가정보 진행", description = "(nickname, gender) 저장")
// 해당하는 유저에다가 추가적인 정보 저장하기

// @Operation(summary = "회원가입 추가정보 진행", description = "(nickname, gender) 저장")
// @PostMapping("/join")
// public ApiResponse<String> join(@RequestBody AuthRequest authRequest, @AuthenticationPrincipal CustomOAuth2User customUser) {
// String username = customUser.getUsername();
//
// // 1. UserService를 통해 (nickname, gender) 저장
// authService.saveUserDetails(username, authRequest);
//
// // 2. 기존 UserDTO를 업데이트
// UserDTO updatedUserDTO = customUser.getUserDTO();
// updatedUserDTO.setNickname(authRequest.nickName());
// updatedUserDTO.setGender(authRequest.gender());
//
//
// // 3. CustomOAuth2User 객체 업데이트 (UserEntity 유지)
// UserEntity userEntity = customUser.getUserEntity(); // 기존 UserEntity 유지
// CustomOAuth2User updatedCustomOAuth2User = new CustomOAuth2User(updatedUserDTO, userEntity);
//
// Authentication newAuth = new UsernamePasswordAuthenticationToken(updatedCustomOAuth2User, null, updatedCustomOAuth2User.getAuthorities());
//
// // 5. SecurityContextHolder에 새로운 Authentication 객체로 업데이트
// SecurityContextHolder.getContext().setAuthentication(newAuth);
//
// return ApiResponse.onSuccess("회원가입 성공");
// }

@Operation(summary = "회원가입 추가정보 진행", description = "(nickname, gender, role) 저장")
@PostMapping("/join")
public ApiResponse<String> join(@RequestBody AuthRequest authRequest) {
// 1. jwt 세션 접근
CustomOAuth2User customUser = (CustomOAuth2User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
public ApiResponse<String> join(@RequestBody AuthRequest authRequest, @AuthenticationPrincipal CustomOAuth2User customUser) {
String username = customUser.getUsername();

// 2. UserService를 통해 (nickname, gender) 저장
authService.saveUserDetails(username, authRequest);
// 1. UserEntity 가져오기
UserEntity userEntity = customUser.getUserEntity();

// 2. 유저 정보 업데이트 (닉네임, 성별, 전화번호 등)
userEntity.setNickname(authRequest.nickName());
userEntity.setGender(authRequest.gender());
userEntity.setPhoneNum(authRequest.phoneNumber());
userEntity.setRole(authRequest.role());

// 5. SecurityContextHolder에 새로운 Authentication 객체로 업데이트
UserDTO updatedUserDTO = customUser.getUserDTO();
updatedUserDTO.setNickname(authRequest.nickName());
updatedUserDTO.setGender(authRequest.gender());

// 3. Role에 따른 Buyer 또는 Seller 객체 생성
if (Role.BUYER == authRequest.role()) {

Buyer buyer = Buyer.builder()
.user(userEntity)
.address(authRequest.address())
.build();
userEntity.setBuyer(buyer); // UserEntity에 Buyer 설정
// } else if ("SELLER".equalsIgnoreCase(authRequest.role())) {
// Seller seller = Seller.builder()
// .user(userEntity)
// .businessName(authRequest.address()) // Seller의 추가 정보
// .role(Role.SELLER)
// .build();
// userEntity.setSeller(seller); // UserEntity에 Seller 설정
// Authentication newAuth = new UsernamePasswordAuthenticationToken(seller, null, customUser.getAuthorities());
// SecurityContextHolder.getContext().setAuthentication(newAuth);
} else {
return ApiResponse.onFailure("Invalid role");
}

// 4. 업데이트된 UserEntity 저장 (Cascade 옵션으로 인해 Buyer/Seller도 저장됨)
authService.saveUser(userEntity);

// CustomOAuth2User updatedCustomOAuth2User = new CustomOAuth2User(updatedUserDTO, userEntity);
// Authentication newAuth = new UsernamePasswordAuthenticationToken(updatedCustomOAuth2User, null, updatedCustomOAuth2User.getAuthorities());
// SecurityContextHolder.getContext().setAuthentication(newAuth);

return ApiResponse.onSuccess("회원가입 성공");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

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

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 org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.List;
import java.util.Map;

public class CustomOAuth2User implements UserDetails, OAuth2User{

private final UserDTO userDTO;
private UserEntity userEntity; // UserEntity

// UserDTO만을 받는 생성자 추가 (UserEntity가 필요하지 않은 경우)
public CustomOAuth2User(UserDTO userDTO) {
this.userDTO = userDTO;
}

// UserDTO와 UserEntity를 함께 받는 생성자
public CustomOAuth2User(UserDTO userDTO, UserEntity userEntity) {
this.userDTO = userDTO;
this.userEntity = userEntity;
}

// UserDTO 객체를 반환하는 getter 메서드 추가
public UserDTO getUserDTO() {
return this.userDTO;
}

// UserEntity를 반환하는 getter 메서드 추가
public UserEntity getUserEntity() {
return this.userEntity;
}

@Override
public String getPassword() {
return "";
Expand Down Expand Up @@ -65,10 +88,23 @@ public String getAuthority() {
});
return collection;
}
// @Override
// public Collection<? extends GrantedAuthority> getAuthorities() {
// // Role에 따라 권한을 설정하기 위해 getAuthoritiesForRole 메서드를 호출
// return getAuthoritiesForRole(userEntity.getRole());
// }

public Collection<? extends GrantedAuthority> getAuthoritiesForRole(Role role) {
if (role == Role.BUYER) {
return List.of(new SimpleGrantedAuthority("ROLE_BUYER"));
} else if (role == Role.SELLER) {
return List.of(new SimpleGrantedAuthority("ROLE_SELLER"));
}
return List.of(new SimpleGrantedAuthority("ROLE_USER")); // 기본 권한
}

@Override
public String getName() {

return userDTO.getName();
}

Expand All @@ -80,4 +116,12 @@ public Long getId() { // id 값을 반환하는 메서드 추가
return userDTO.getId();
}

public String getNickname(){
return userDTO.getNickname();
}

public Gender getGender(){
return userDTO.getGender();
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.kakaoteck.golagola.domain.auth.dto;

import com.kakaoteck.golagola.domain.buyer.entity.Buyer;
import com.kakaoteck.golagola.domain.seller.entity.Seller;
import com.kakaoteck.golagola.global.common.enums.Gender;
import lombok.Getter;
import lombok.Setter;

Expand All @@ -12,6 +15,11 @@ public class UserDTO {
private String name;
private String username;
private String email; // 엔티티의 email 추가
private String nickname;
private String image;
private Gender gender;
private Buyer buyer;
private Seller seller;
// private String refreshToken; // 엔티티의 refreshToken 추가
// private boolean loginStatus; // 엔티티의 loginStatus 추가
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ public class UserEntity implements UserDetails {
@Column(nullable = false)
private Gender gender = Gender.valueOf("MALE");

@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Role role = Role.valueOf("BUYER");

// 추가
private String refreshToken; // JWT 리프레시 토큰 발급
private boolean loginStatus; // 로그인 상태처리
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.kakaoteck.golagola.domain.auth.Repository.UserRepository;
import com.kakaoteck.golagola.domain.auth.dto.AuthRequest;
import com.kakaoteck.golagola.domain.auth.entity.UserEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -24,6 +25,10 @@ public void saveUserDetails(String username, AuthRequest authRequest) {
});
}

public void saveUser(UserEntity userEntity) {
userRepository.save(userEntity); // UserEntity를 저장하면 Buyer/Seller도 함께 저장됨
}



}
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package com.kakaoteck.golagola.domain.buyer.controller;

import com.kakaoteck.golagola.domain.auth.dto.CustomOAuth2User;
import com.kakaoteck.golagola.domain.auth.dto.UserDTO;
import com.kakaoteck.golagola.domain.auth.entity.UserEntity;
import com.kakaoteck.golagola.domain.buyer.dto.BuyerRequest;
import com.kakaoteck.golagola.domain.buyer.dto.BuyerResponse;
import com.kakaoteck.golagola.domain.buyer.entity.Buyer;
import com.kakaoteck.golagola.domain.buyer.service.BuyerService;
import com.kakaoteck.golagola.global.common.ApiResponse;
import com.kakaoteck.golagola.global.common.enums.Gender;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
Expand All @@ -23,31 +27,26 @@ public class BuyerController {

// @Operation(summary = "구매자 마이페이지 조회", description = "구매자의 정보를 조회합니다.")
// @GetMapping("/mypage")
// public ApiResponse<BuyerResponse> getMyPage() {
// // 1. jwt 세션 접근
// CustomOAuth2User customUser = (CustomOAuth2User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// String username = customUser.getUsername();
// public ApiResponse<BuyerResponse> getMyPage(@AuthenticationPrincipal CustomOAuth2User customUser) {
//
// return ApiResponse.onSuccess(BuyerService.getMyPage(username));
// UserEntity userEntity = customUser.getUserEntity();
// BuyerResponse buyerResponse = BuyerService.getMyPage(userEntity); // Buyer 객체를 BuyerService로 넘겨서 BuyerResponse 생성
// return ApiResponse.onSuccess(buyerResponse);
// }

@Operation(summary = "구매자 마이페이지 조회", description = "구매자의 정보를 조회합니다.")
@GetMapping("/mypage")
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";
public ApiResponse<BuyerResponse> getMyPage(@AuthenticationPrincipal Buyer buyer) {

// UserEntity userEntity = customUser.getUserEntity();
// BuyerResponse buyerResponse = BuyerService.getMyPage(userEntity); // Buyer 객체를 BuyerService로 넘겨서 BuyerResponse 생성
BuyerResponse buyerResponse = BuyerService.getMyPage(buyer);
return ApiResponse.onSuccess(buyerResponse);
}

@Operation(summary = "구매자 마이페이지 수정", description = "구매자의 정보를 수정합니다.")
@PutMapping("/mypage")
public ApiResponse<BuyerResponse> updateProfile(
@AuthenticationPrincipal Buyer buyer,
@RequestBody BuyerRequest.MyPagePutDto request
) {
public ApiResponse<BuyerResponse> updateProfile(@AuthenticationPrincipal Buyer buyer, @RequestBody BuyerRequest.MyPagePutDto request) {
return ApiResponse.onSuccess(buyerService.updateMyPage(buyer, request));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.kakaoteck.golagola.domain.buyer.dto;

import com.kakaoteck.golagola.global.common.enums.Gender;
import com.kakaoteck.golagola.global.common.enums.Role;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class BuyerDTO {
private Long buyerId; // Buyer의 ID
private String nickname; // UserEntity에서 가져온 필드
private String realName; // UserEntity에서 가져온 필드
private String email; // UserEntity에서 가져온 필드
private String phoneNum; // UserEntity에서 가져온 필드
private Gender gender; // UserEntity에서 가져온 필드
private Role role; // Buyer의 역할 (BUYER)
private String address; // Buyer의 주소
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ public record BuyerRequest(
String email,
String address,
String phoneNum,
Role role,
LocalDate registerDate) {
Role role)
{

@Builder
public record MyPagePutDto(
Expand Down
Loading

0 comments on commit d6cdc81

Please sign in to comment.