diff --git a/src/main/java/space/space_spring/argument_resolver/JwtPreAuth.java b/src/main/java/space/space_spring/argument_resolver/jwtLogin/JwtLoginAuth.java similarity index 72% rename from src/main/java/space/space_spring/argument_resolver/JwtPreAuth.java rename to src/main/java/space/space_spring/argument_resolver/jwtLogin/JwtLoginAuth.java index bfd1b19e..cd8d2e4b 100644 --- a/src/main/java/space/space_spring/argument_resolver/JwtPreAuth.java +++ b/src/main/java/space/space_spring/argument_resolver/jwtLogin/JwtLoginAuth.java @@ -1,4 +1,4 @@ -package space.space_spring.argument_resolver; +package space.space_spring.argument_resolver.jwtLogin; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -7,5 +7,5 @@ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) -public @interface JwtPreAuth { +public @interface JwtLoginAuth { } diff --git a/src/main/java/space/space_spring/argument_resolver/JwtAuthHandlerArgumentResolver.java b/src/main/java/space/space_spring/argument_resolver/jwtLogin/JwtLoginAuthHandlerArgumentResolver.java similarity index 82% rename from src/main/java/space/space_spring/argument_resolver/JwtAuthHandlerArgumentResolver.java rename to src/main/java/space/space_spring/argument_resolver/jwtLogin/JwtLoginAuthHandlerArgumentResolver.java index fb6341cb..aff96769 100644 --- a/src/main/java/space/space_spring/argument_resolver/JwtAuthHandlerArgumentResolver.java +++ b/src/main/java/space/space_spring/argument_resolver/jwtLogin/JwtLoginAuthHandlerArgumentResolver.java @@ -1,4 +1,4 @@ -package space.space_spring.argument_resolver; +package space.space_spring.argument_resolver.jwtLogin; import jakarta.servlet.http.HttpServletRequest; import org.springframework.core.MethodParameter; @@ -9,13 +9,12 @@ import org.springframework.web.method.support.ModelAndViewContainer; @Component -public class JwtAuthHandlerArgumentResolver implements HandlerMethodArgumentResolver { - +public class JwtLoginAuthHandlerArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { // 일단 parameter의 return value type 을 검사하지는 X - return parameter.hasParameterAnnotation(JwtPreAuth.class); + return parameter.hasParameterAnnotation(JwtLoginAuth.class); } @Override diff --git a/src/main/java/space/space_spring/argument_resolver/jwtUserSpace/JwtUserSpaceAuth.java b/src/main/java/space/space_spring/argument_resolver/jwtUserSpace/JwtUserSpaceAuth.java new file mode 100644 index 00000000..074e0a7b --- /dev/null +++ b/src/main/java/space/space_spring/argument_resolver/jwtUserSpace/JwtUserSpaceAuth.java @@ -0,0 +1,11 @@ +package space.space_spring.argument_resolver.jwtUserSpace; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +public @interface JwtUserSpaceAuth { +} diff --git a/src/main/java/space/space_spring/argument_resolver/jwtUserSpace/JwtUserSpaceAuthHandlerArgumentResolver.java b/src/main/java/space/space_spring/argument_resolver/jwtUserSpace/JwtUserSpaceAuthHandlerArgumentResolver.java new file mode 100644 index 00000000..2450ecbd --- /dev/null +++ b/src/main/java/space/space_spring/argument_resolver/jwtUserSpace/JwtUserSpaceAuthHandlerArgumentResolver.java @@ -0,0 +1,25 @@ +package space.space_spring.argument_resolver.jwtUserSpace; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.core.MethodParameter; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; + +@Component +public class JwtUserSpaceAuthHandlerArgumentResolver implements HandlerMethodArgumentResolver { + + @Override + public boolean supportsParameter(MethodParameter parameter) { + // 일단 parameter의 return value type 을 검사하지는 X + return parameter.hasParameterAnnotation(JwtUserSpaceAuth.class); + } + + @Override + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { + HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest(); + return request.getAttribute("jwtPayloadDto"); // jwt를 복호화해서 얻은 userId get + } +} diff --git a/src/main/java/space/space_spring/config/WebConfig.java b/src/main/java/space/space_spring/config/WebConfig.java index 03570905..184974bc 100644 --- a/src/main/java/space/space_spring/config/WebConfig.java +++ b/src/main/java/space/space_spring/config/WebConfig.java @@ -5,9 +5,10 @@ import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import space.space_spring.argument_resolver.JwtAuthHandlerArgumentResolver; -import space.space_spring.interceptor.JwtAuthInterceptor; -import space.space_spring.jwt.JwtProvider; +import space.space_spring.argument_resolver.jwtLogin.JwtLoginAuthHandlerArgumentResolver; +import space.space_spring.argument_resolver.jwtUserSpace.JwtUserSpaceAuthHandlerArgumentResolver; +import space.space_spring.interceptor.jwtLogin.JwtLoginAuthInterceptor; +import space.space_spring.interceptor.jwtUserSpace.JwtUserSpaceAuthInterceptor; import java.util.List; @@ -15,18 +16,26 @@ @RequiredArgsConstructor public class WebConfig implements WebMvcConfigurer { - private final JwtAuthInterceptor jwtAuthInterceptor; - private final JwtAuthHandlerArgumentResolver authHandlerArgumentResolver; + private final JwtLoginAuthInterceptor jwtLoginAuthInterceptor; + private final JwtUserSpaceAuthInterceptor jwtUserSpaceAuthInterceptor; + + private final JwtLoginAuthHandlerArgumentResolver jwtLoginAuthHandlerArgumentResolver; + private final JwtUserSpaceAuthHandlerArgumentResolver jwtUserSpaceAuthHandlerArgumentResolver; @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(jwtAuthInterceptor) + registry.addInterceptor(jwtLoginAuthInterceptor) .order(1) - .addPathPatterns("/space/**", "/test/**"); // interceptor 적용되야하는 url enum으로 만들어서 여기에 달면 될듯 + .addPathPatterns("/space/**", "/test/**"); + + registry.addInterceptor(jwtUserSpaceAuthInterceptor) + .order(2) + .addPathPatterns("/test111/**"); // interceptor 적용되야하는 url enum으로 만들어서 여기에 달면 될듯 } @Override public void addArgumentResolvers(List argumentResolvers) { - argumentResolvers.add(authHandlerArgumentResolver); + argumentResolvers.add(jwtLoginAuthHandlerArgumentResolver); + argumentResolvers.add(jwtUserSpaceAuthHandlerArgumentResolver); } } diff --git a/src/main/java/space/space_spring/controller/SpaceController.java b/src/main/java/space/space_spring/controller/SpaceController.java new file mode 100644 index 00000000..b1d1aa16 --- /dev/null +++ b/src/main/java/space/space_spring/controller/SpaceController.java @@ -0,0 +1,45 @@ +package space.space_spring.controller; + +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.BindingResult; +import org.springframework.validation.annotation.Validated; +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; +import space.space_spring.argument_resolver.jwtLogin.JwtLoginAuth; +import space.space_spring.argument_resolver.jwtUserSpace.JwtUserSpaceAuth; +import space.space_spring.dto.jwt.JwtPayloadDto; +import space.space_spring.dto.space.PostSpaceCreateRequest; +import space.space_spring.dto.space.PostSpaceCreateResponse; + +import space.space_spring.dto.space.SpaceCreateDto; +import space.space_spring.exception.SpaceException; +import space.space_spring.response.BaseResponse; +import space.space_spring.service.SpaceService; + +import static space.space_spring.response.status.BaseExceptionResponseStatus.INVALID_SPACE_CREATE; +import static space.space_spring.util.BindingResultUtils.getErrorMessage; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/space") +public class SpaceController { + + private final SpaceService spaceService; + + @PostMapping("/create") + public BaseResponse createSpace(@JwtLoginAuth Long userId, @Validated @RequestBody PostSpaceCreateRequest postSpaceCreateRequest, BindingResult bindingResult, HttpServletResponse response) { + if (bindingResult.hasErrors()) { + throw new SpaceException(INVALID_SPACE_CREATE, getErrorMessage(bindingResult)); + } + + SpaceCreateDto spaceCreateDto = spaceService.createSpace(userId, postSpaceCreateRequest); + String jwtUserSpace = spaceCreateDto.getJwtUserSpace(); + response.setHeader("Authorization", "Bearer " + jwtUserSpace); + + return new BaseResponse<>(new PostSpaceCreateResponse(spaceCreateDto.getSpaceId())); + } + +} diff --git a/src/main/java/space/space_spring/controller/TestController.java b/src/main/java/space/space_spring/controller/TestController.java index b1ca1bdb..ac6761a7 100644 --- a/src/main/java/space/space_spring/controller/TestController.java +++ b/src/main/java/space/space_spring/controller/TestController.java @@ -3,7 +3,9 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import space.space_spring.argument_resolver.JwtPreAuth; +import space.space_spring.argument_resolver.jwtLogin.JwtLoginAuth; +import space.space_spring.argument_resolver.jwtUserSpace.JwtUserSpaceAuth; +import space.space_spring.dto.jwt.JwtPayloadDto; import space.space_spring.response.BaseResponse; @RestController @@ -16,8 +18,14 @@ public String test(){ } @GetMapping("/test/jwt") - public BaseResponse jwtTest(@JwtPreAuth Long userId) { + public BaseResponse jwtLoginTest(@JwtLoginAuth Long userId) { log.info("userId = {}", userId); - return new BaseResponse<>("jwt test 성공"); + return new BaseResponse<>("jwt login test 성공"); + } + + @GetMapping("/test111") + public BaseResponse jwtUserSpaceTest(@JwtUserSpaceAuth JwtPayloadDto jwtPayloadDto) { + log.info("jwtPayloadDto = {}", jwtPayloadDto); + return new BaseResponse<>("jwt user space test 성공"); } } diff --git a/src/main/java/space/space_spring/controller/UserController.java b/src/main/java/space/space_spring/controller/UserController.java index 77ee6464..e7ec94ad 100644 --- a/src/main/java/space/space_spring/controller/UserController.java +++ b/src/main/java/space/space_spring/controller/UserController.java @@ -9,15 +9,15 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import space.space_spring.dto.PostUserLoginRequest; -import space.space_spring.dto.PostUserLoginResponse; -import space.space_spring.dto.PostUserSignupRequest; -import space.space_spring.dto.PostUserSignupResponse; +import space.space_spring.dto.user.PostUserLoginRequest; +import space.space_spring.dto.user.PostUserLoginResponse; +import space.space_spring.dto.user.PostUserSignupRequest; +import space.space_spring.dto.user.PostUserSignupResponse; import space.space_spring.exception.UserException; import space.space_spring.response.BaseResponse; import space.space_spring.service.UserService; -import static space.space_spring.response.status.BaseExceptionResponseStatus.INVALID_USER_VALUE; +import static space.space_spring.response.status.BaseExceptionResponseStatus.*; import static space.space_spring.util.BindingResultUtils.getErrorMessage; @Slf4j @@ -34,7 +34,7 @@ public class UserController { @PostMapping("/signup") public BaseResponse signup(@Validated @RequestBody PostUserSignupRequest postUserSignupRequest, BindingResult bindingResult) { if (bindingResult.hasErrors()) { - throw new UserException(INVALID_USER_VALUE, getErrorMessage(bindingResult)); + throw new UserException(INVALID_USER_SIGNUP, getErrorMessage(bindingResult)); } return new BaseResponse<>(userService.signup(postUserSignupRequest)); } @@ -45,11 +45,11 @@ public BaseResponse signup(@Validated @RequestBody PostU @PostMapping("/login") public BaseResponse login(@Validated @RequestBody PostUserLoginRequest postUserLoginRequest, BindingResult bindingResult, HttpServletResponse response) { if (bindingResult.hasErrors()) { - throw new UserException(INVALID_USER_VALUE, getErrorMessage(bindingResult)); + throw new UserException(INVALID_USER_LOGIN, getErrorMessage(bindingResult)); } - String jwt = userService.login(postUserLoginRequest); - response.setHeader("Authorization", "Bearer " + jwt); + String jwtLogin = userService.login(postUserLoginRequest); + response.setHeader("Authorization", "Bearer " + jwtLogin); return new BaseResponse<>(new PostUserLoginResponse("로그인 성공")); } diff --git a/src/main/java/space/space_spring/dao/SpaceDao.java b/src/main/java/space/space_spring/dao/SpaceDao.java new file mode 100644 index 00000000..e2cf42fd --- /dev/null +++ b/src/main/java/space/space_spring/dao/SpaceDao.java @@ -0,0 +1,34 @@ +package space.space_spring.dao; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import org.springframework.stereotype.Repository; +import space.space_spring.entity.Space; +import space.space_spring.entity.User; +import space.space_spring.entity.UserSpace; +import space.space_spring.dto.space.PostSpaceCreateRequest; + +import static space.space_spring.entity.enumStatus.UserSpaceAuth.MANAGER; + +@Repository +public class SpaceDao { + + @PersistenceContext + private EntityManager em; + + public Space saveSpace(PostSpaceCreateRequest postSpaceCreateRequest) { + Space space = new Space(); + space.saveSpace(postSpaceCreateRequest.getSpaceName(), postSpaceCreateRequest.getSpaceProfileImg()); + + em.persist(space); + return space; + } + + public UserSpace createUserSpace(User manager, Space saveSpace) { + UserSpace userSpace = new UserSpace(); + userSpace.createUserSpace(manager, saveSpace, MANAGER); + + em.persist(userSpace); + return userSpace; + } +} diff --git a/src/main/java/space/space_spring/dao/UserDao.java b/src/main/java/space/space_spring/dao/UserDao.java index 7c5a3e11..70caafc9 100644 --- a/src/main/java/space/space_spring/dao/UserDao.java +++ b/src/main/java/space/space_spring/dao/UserDao.java @@ -5,8 +5,8 @@ import jakarta.persistence.PersistenceContext; import jakarta.persistence.TypedQuery; import org.springframework.stereotype.Repository; -import space.space_spring.domain.User; -import space.space_spring.dto.PostUserSignupRequest; +import space.space_spring.entity.User; +import space.space_spring.dto.user.PostUserSignupRequest; @Repository public class UserDao { @@ -14,12 +14,12 @@ public class UserDao { @PersistenceContext private EntityManager em; - public Long saveUser(PostUserSignupRequest postUserSignupRequest) { + public User saveUser(PostUserSignupRequest postUserSignupRequest) { User user = new User(); user.saveUser(postUserSignupRequest.getEmail(), postUserSignupRequest.getPassword(), postUserSignupRequest.getUserName()); em.persist(user); - return user.getUserId(); + return user; } public User findUserByEmail(String email) { @@ -43,4 +43,10 @@ public User getUserByEmail(String email) { return null; } } + + public User findUserByUserId(Long userId) { + TypedQuery query = em.createQuery("SELECT u FROM User u WHERE u.userId = :userId", User.class); + query.setParameter("userId", userId); + return query.getSingleResult(); + } } diff --git a/src/main/java/space/space_spring/dto/jwt/JwtPayloadDto.java b/src/main/java/space/space_spring/dto/jwt/JwtPayloadDto.java new file mode 100644 index 00000000..f697f852 --- /dev/null +++ b/src/main/java/space/space_spring/dto/jwt/JwtPayloadDto.java @@ -0,0 +1,30 @@ +package space.space_spring.dto.jwt; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.util.ArrayList; +import java.util.List; + +@Getter +@NoArgsConstructor +@ToString +public class JwtPayloadDto { + + private Long userId; + + private List userSpaceList = new ArrayList<>(); + + public void saveUserIdToJwt(Long userId) { + this.userId = userId; + } + + public void saveUserSpaceList(List userSpaceList) { + this.userSpaceList = userSpaceList; + } + + public void addJwtUserSpaceAuth(JwtUserSpaceAuthDto jwtUserSpaceAuthDto) { + this.userSpaceList.add(jwtUserSpaceAuthDto); + } +} diff --git a/src/main/java/space/space_spring/dto/jwt/JwtUserSpaceAuthDto.java b/src/main/java/space/space_spring/dto/jwt/JwtUserSpaceAuthDto.java new file mode 100644 index 00000000..ab6c4f56 --- /dev/null +++ b/src/main/java/space/space_spring/dto/jwt/JwtUserSpaceAuthDto.java @@ -0,0 +1,18 @@ +package space.space_spring.dto.jwt; + +import lombok.Getter; +import lombok.ToString; + +import java.util.HashMap; +import java.util.Map; + +@Getter +@ToString +public class JwtUserSpaceAuthDto { + + private Map userSpaceAuthMap = new HashMap<>(); + + public void saveUserSpaceAuth(Long spaceId, String userSpaceAuth) { + userSpaceAuthMap.put(spaceId, userSpaceAuth); + } +} diff --git a/src/main/java/space/space_spring/dto/space/PostSpaceCreateRequest.java b/src/main/java/space/space_spring/dto/space/PostSpaceCreateRequest.java new file mode 100644 index 00000000..e92eafa7 --- /dev/null +++ b/src/main/java/space/space_spring/dto/space/PostSpaceCreateRequest.java @@ -0,0 +1,20 @@ +package space.space_spring.dto.space; + +import jakarta.validation.constraints.NotBlank; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.validator.constraints.Length; + +@Getter +@Setter +@NoArgsConstructor +public class PostSpaceCreateRequest { + + @Length(min = 1, max = 10, message = "이름은 10자이내의 문자열이어야 합니다.") + @NotBlank(message = "스페이스 이름은 공백일 수 없습니다.") + private String spaceName; + + @NotBlank(message = "스페이스 프로필 이미지는 공백일 수 없습니다.") + private String spaceProfileImg; // 스페이스 프로필 이미지 (썸네일) +} diff --git a/src/main/java/space/space_spring/dto/space/PostSpaceCreateResponse.java b/src/main/java/space/space_spring/dto/space/PostSpaceCreateResponse.java new file mode 100644 index 00000000..26479f54 --- /dev/null +++ b/src/main/java/space/space_spring/dto/space/PostSpaceCreateResponse.java @@ -0,0 +1,11 @@ +package space.space_spring.dto.space; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class PostSpaceCreateResponse { + + private Long spaceId; +} diff --git a/src/main/java/space/space_spring/dto/space/SpaceCreateDto.java b/src/main/java/space/space_spring/dto/space/SpaceCreateDto.java new file mode 100644 index 00000000..c371de16 --- /dev/null +++ b/src/main/java/space/space_spring/dto/space/SpaceCreateDto.java @@ -0,0 +1,12 @@ +package space.space_spring.dto.space; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class SpaceCreateDto { + + private Long spaceId; + private String jwtUserSpace; +} diff --git a/src/main/java/space/space_spring/dto/PostUserLoginRequest.java b/src/main/java/space/space_spring/dto/user/PostUserLoginRequest.java similarity index 85% rename from src/main/java/space/space_spring/dto/PostUserLoginRequest.java rename to src/main/java/space/space_spring/dto/user/PostUserLoginRequest.java index 5393b72f..69f8768f 100644 --- a/src/main/java/space/space_spring/dto/PostUserLoginRequest.java +++ b/src/main/java/space/space_spring/dto/user/PostUserLoginRequest.java @@ -1,5 +1,6 @@ -package space.space_spring.dto; +package space.space_spring.dto.user; +import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import lombok.Getter; import lombok.NoArgsConstructor; @@ -11,11 +12,13 @@ public class PostUserLoginRequest { @Pattern(regexp = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,6}$", message = "이메일 형식에 맞지 않습니다.") // 이메일 정규표현식 확인 필요함 + @NotBlank private String email; @Pattern( regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,16}$", message = "8~16글자의 영문 대/소문자, 숫자, 특수문자가 포함되어야 합니다." ) + @NotBlank private String password; } diff --git a/src/main/java/space/space_spring/dto/PostUserLoginResponse.java b/src/main/java/space/space_spring/dto/user/PostUserLoginResponse.java similarity index 80% rename from src/main/java/space/space_spring/dto/PostUserLoginResponse.java rename to src/main/java/space/space_spring/dto/user/PostUserLoginResponse.java index 14aa5a5f..29b631c5 100644 --- a/src/main/java/space/space_spring/dto/PostUserLoginResponse.java +++ b/src/main/java/space/space_spring/dto/user/PostUserLoginResponse.java @@ -1,4 +1,4 @@ -package space.space_spring.dto; +package space.space_spring.dto.user; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/space/space_spring/dto/PostUserSignupRequest.java b/src/main/java/space/space_spring/dto/user/PostUserSignupRequest.java similarity index 87% rename from src/main/java/space/space_spring/dto/PostUserSignupRequest.java rename to src/main/java/space/space_spring/dto/user/PostUserSignupRequest.java index 0172461c..c483849d 100644 --- a/src/main/java/space/space_spring/dto/PostUserSignupRequest.java +++ b/src/main/java/space/space_spring/dto/user/PostUserSignupRequest.java @@ -1,5 +1,6 @@ -package space.space_spring.dto; +package space.space_spring.dto.user; +import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import lombok.AllArgsConstructor; import lombok.Getter; @@ -14,14 +15,17 @@ public class PostUserSignupRequest { @Pattern(regexp = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,6}$", message = "이메일 형식에 맞지 않습니다.") // 이메일 정규표현식 확인 필요함 + @NotBlank private String email; @Pattern( regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,16}$", message = "8~16글자의 영문 대/소문자, 숫자, 특수문자가 포함되어야 합니다." ) + @NotBlank private String password; @Length(min = 1, max = 10, message = "이름은 10자이내의 문자열이어야 합니다.") + @NotBlank private String userName; } diff --git a/src/main/java/space/space_spring/dto/PostUserSignupResponse.java b/src/main/java/space/space_spring/dto/user/PostUserSignupResponse.java similarity index 85% rename from src/main/java/space/space_spring/dto/PostUserSignupResponse.java rename to src/main/java/space/space_spring/dto/user/PostUserSignupResponse.java index 4dd0056b..3fb00679 100644 --- a/src/main/java/space/space_spring/dto/PostUserSignupResponse.java +++ b/src/main/java/space/space_spring/dto/user/PostUserSignupResponse.java @@ -1,4 +1,4 @@ -package space.space_spring.dto; +package space.space_spring.dto.user; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/space/space_spring/domain/BaseEntity.java b/src/main/java/space/space_spring/entity/BaseEntity.java similarity index 95% rename from src/main/java/space/space_spring/domain/BaseEntity.java rename to src/main/java/space/space_spring/entity/BaseEntity.java index ff7f133c..4b035dd0 100644 --- a/src/main/java/space/space_spring/domain/BaseEntity.java +++ b/src/main/java/space/space_spring/entity/BaseEntity.java @@ -1,4 +1,4 @@ -package space.space_spring.domain; +package space.space_spring.entity; import jakarta.persistence.*; diff --git a/src/main/java/space/space_spring/domain/Space.java b/src/main/java/space/space_spring/entity/Space.java similarity index 60% rename from src/main/java/space/space_spring/domain/Space.java rename to src/main/java/space/space_spring/entity/Space.java index 0a5c5ea0..a07a3b6c 100644 --- a/src/main/java/space/space_spring/domain/Space.java +++ b/src/main/java/space/space_spring/entity/Space.java @@ -1,6 +1,5 @@ -package space.space_spring.domain; +package space.space_spring.entity; -import jakarta.annotation.Nullable; import jakarta.persistence.*; import lombok.Getter; @@ -17,6 +16,12 @@ public class Space extends BaseEntity { private String spaceName; @Column(name = "space_profile_img") - @Nullable private String spaceProfileImg; + + public void saveSpace(String spaceName, String spaceProfileImg) { + this.spaceName = spaceName; + this.spaceProfileImg = spaceProfileImg; + initializeBaseEntityFields(); + } + } diff --git a/src/main/java/space/space_spring/domain/User.java b/src/main/java/space/space_spring/entity/User.java similarity index 81% rename from src/main/java/space/space_spring/domain/User.java rename to src/main/java/space/space_spring/entity/User.java index b15bc936..a13a9430 100644 --- a/src/main/java/space/space_spring/domain/User.java +++ b/src/main/java/space/space_spring/entity/User.java @@ -1,11 +1,8 @@ -package space.space_spring.domain; +package space.space_spring.entity; import jakarta.annotation.Nullable; import jakarta.persistence.*; -import jakarta.validation.constraints.Email; -import jakarta.validation.constraints.Pattern; import lombok.Getter; -import org.hibernate.validator.constraints.Length; @Entity @Table(name = "Users") diff --git a/src/main/java/space/space_spring/domain/UserSpace.java b/src/main/java/space/space_spring/entity/UserSpace.java similarity index 60% rename from src/main/java/space/space_spring/domain/UserSpace.java rename to src/main/java/space/space_spring/entity/UserSpace.java index 5d44ee9b..35d668b3 100644 --- a/src/main/java/space/space_spring/domain/UserSpace.java +++ b/src/main/java/space/space_spring/entity/UserSpace.java @@ -1,8 +1,9 @@ -package space.space_spring.domain; +package space.space_spring.entity; import jakarta.annotation.Nullable; import jakarta.persistence.*; import lombok.Getter; +import space.space_spring.entity.enumStatus.UserSpaceAuth; @Entity @Getter @@ -32,11 +33,20 @@ public class UserSpace extends BaseEntity { @Nullable private String userProfileMsg; + // 스페이스의 관리자 vs 일반 멤버 @Column(name = "user_auth") - private String userAuth; + private String userSpaceAuth; + // 스페이스 선택화면에서의 배치 순서 -> 일단 개발 후순위 (계속 0으로 저장) @Column(name = "space_order") private int spaceOrder; + public void createUserSpace(User user, Space space, UserSpaceAuth userSpaceAuth) { + this.user = user; + this.space = space; + this.userName = user.getUserName(); + this.userSpaceAuth = userSpaceAuth.getAuth(); + } + } diff --git a/src/main/java/space/space_spring/entity/enumStatus/UserSpaceAuth.java b/src/main/java/space/space_spring/entity/enumStatus/UserSpaceAuth.java new file mode 100644 index 00000000..7024b35d --- /dev/null +++ b/src/main/java/space/space_spring/entity/enumStatus/UserSpaceAuth.java @@ -0,0 +1,15 @@ +package space.space_spring.entity.enumStatus; + +import lombok.Getter; + +@Getter +public enum UserSpaceAuth { + MANAGER("manager"), + NORMAL("normal"); + + private String auth; + + UserSpaceAuth(String auth) { + this.auth = auth; + } +} diff --git a/src/main/java/space/space_spring/exception/SpaceException.java b/src/main/java/space/space_spring/exception/SpaceException.java new file mode 100644 index 00000000..d8369c8f --- /dev/null +++ b/src/main/java/space/space_spring/exception/SpaceException.java @@ -0,0 +1,21 @@ +package space.space_spring.exception; + +import lombok.Getter; +import space.space_spring.response.status.ResponseStatus; + +@Getter +public class SpaceException extends RuntimeException { + + private final ResponseStatus exceptionStatus; + + public SpaceException(ResponseStatus exceptionStatus) { + super(exceptionStatus.getMessage()); + this.exceptionStatus = exceptionStatus; + } + + public SpaceException(ResponseStatus exceptionStatus, String message) { + super(message); + this.exceptionStatus = exceptionStatus; + } + +} diff --git a/src/main/java/space/space_spring/interceptor/JwtAuthInterceptor.java b/src/main/java/space/space_spring/interceptor/jwtLogin/JwtLoginAuthInterceptor.java similarity index 80% rename from src/main/java/space/space_spring/interceptor/JwtAuthInterceptor.java rename to src/main/java/space/space_spring/interceptor/jwtLogin/JwtLoginAuthInterceptor.java index f8728ea3..d196a683 100644 --- a/src/main/java/space/space_spring/interceptor/JwtAuthInterceptor.java +++ b/src/main/java/space/space_spring/interceptor/jwtLogin/JwtLoginAuthInterceptor.java @@ -1,4 +1,4 @@ -package space.space_spring.interceptor; +package space.space_spring.interceptor.jwtLogin; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -6,20 +6,20 @@ import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; -import space.space_spring.jwt.JwtProvider; -import space.space_spring.exception.jwt.unauthorized.JwtExpiredTokenException; import space.space_spring.exception.jwt.bad_request.JwtNoTokenException; import space.space_spring.exception.jwt.bad_request.JwtUnsupportedTokenException; +import space.space_spring.exception.jwt.unauthorized.JwtExpiredTokenException; +import space.space_spring.jwt.JwtLoginProvider; import static space.space_spring.response.status.BaseExceptionResponseStatus.*; @Component @RequiredArgsConstructor -public class JwtAuthInterceptor implements HandlerInterceptor { +public class JwtLoginAuthInterceptor implements HandlerInterceptor{ private static final String JWT_TOKEN_PREFIX = "Bearer "; - private final JwtProvider jwtProvider; + private final JwtLoginProvider jwtLoginProvider; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { @@ -27,14 +27,14 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons validateAccessToken(accessToken); // jwt에서 userId get - Long userId = jwtProvider.getUserIdFromToken(accessToken); - request.setAttribute("userId", userId); + Long userIdFromToken = jwtLoginProvider.getUserIdFromToken(accessToken); + request.setAttribute("userId", userIdFromToken); return true; } private void validateAccessToken(String accessToken) { - if (jwtProvider.isExpiredToken(accessToken)) { + if (jwtLoginProvider.isExpiredToken(accessToken)) { throw new JwtExpiredTokenException(EXPIRED_TOKEN); } @@ -56,4 +56,4 @@ private void validateToken(String token) { } -} +} \ No newline at end of file diff --git a/src/main/java/space/space_spring/interceptor/jwtUserSpace/JwtUserSpaceAuthInterceptor.java b/src/main/java/space/space_spring/interceptor/jwtUserSpace/JwtUserSpaceAuthInterceptor.java new file mode 100644 index 00000000..080d275e --- /dev/null +++ b/src/main/java/space/space_spring/interceptor/jwtUserSpace/JwtUserSpaceAuthInterceptor.java @@ -0,0 +1,60 @@ +package space.space_spring.interceptor.jwtUserSpace; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import space.space_spring.dto.jwt.JwtPayloadDto; +import space.space_spring.jwt.JwtUserSpaceProvider; +import space.space_spring.exception.jwt.unauthorized.JwtExpiredTokenException; +import space.space_spring.exception.jwt.bad_request.JwtNoTokenException; +import space.space_spring.exception.jwt.bad_request.JwtUnsupportedTokenException; + +import static space.space_spring.response.status.BaseExceptionResponseStatus.*; + +@Component +@RequiredArgsConstructor +public class JwtUserSpaceAuthInterceptor implements HandlerInterceptor { + + private static final String JWT_TOKEN_PREFIX = "Bearer "; + + private final JwtUserSpaceProvider jwtUserSpaceProvider; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String accessToken = resolveAccessToken(request); + validateAccessToken(accessToken); + + // jwt에서 JwtPayloadDto get + JwtPayloadDto jwtPayloadDto = jwtUserSpaceProvider.getJwtPayloadDtoFromToken(accessToken); + request.setAttribute("jwtPayloadDto", jwtPayloadDto); + + return true; + } + + private void validateAccessToken(String accessToken) { + if (jwtUserSpaceProvider.isExpiredToken(accessToken)) { + throw new JwtExpiredTokenException(EXPIRED_TOKEN); + } + + } + + private String resolveAccessToken(HttpServletRequest request) { + String token = request.getHeader(HttpHeaders.AUTHORIZATION); + validateToken(token); + return token.substring(JWT_TOKEN_PREFIX.length()); + } + + private void validateToken(String token) { + if (token == null) { + throw new JwtNoTokenException(TOKEN_NOT_FOUND); + } + if (!token.startsWith(JWT_TOKEN_PREFIX)) { + throw new JwtUnsupportedTokenException(UNSUPPORTED_TOKEN_TYPE); + } + } + + +} diff --git a/src/main/java/space/space_spring/jwt/JwtProvider.java b/src/main/java/space/space_spring/jwt/JwtLoginProvider.java similarity index 75% rename from src/main/java/space/space_spring/jwt/JwtProvider.java rename to src/main/java/space/space_spring/jwt/JwtLoginProvider.java index 429a9752..b5aa0ef0 100644 --- a/src/main/java/space/space_spring/jwt/JwtProvider.java +++ b/src/main/java/space/space_spring/jwt/JwtLoginProvider.java @@ -4,43 +4,46 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import space.space_spring.domain.User; +import space.space_spring.entity.User; +import space.space_spring.exception.jwt.bad_request.JwtUnsupportedTokenException; import space.space_spring.exception.jwt.unauthorized.JwtInvalidTokenException; import space.space_spring.exception.jwt.unauthorized.JwtMalformedTokenException; -import space.space_spring.exception.jwt.bad_request.JwtUnsupportedTokenException; import java.util.Date; import static space.space_spring.response.status.BaseExceptionResponseStatus.*; -@Component @Slf4j -public class JwtProvider { - - @Value("${secret.jwt-secret-key}") - private String JWT_SECRET_KEY; +@Component +public class JwtLoginProvider { + @Value("${secret.jwt-login-secret-key}") + private String JWT_LOGIN_SECRET_KEY; @Value("${secret.jwt-expired-in}") private Long JWT_EXPIRED_IN; + public String generateToken(User user) { - Claims claims = Jwts.claims().setSubject(user.getEmail()); +// Claims claims = Jwts.claims().setSubject(jwtPayloadDto.getUserId().toString()); + Date now = new Date(); Date expiration = new Date(now.getTime() + JWT_EXPIRED_IN); + Long userId = user.getUserId(); + return Jwts.builder() - .setClaims(claims) +// .setClaims(claims) .setIssuedAt(now) .setExpiration(expiration) - .claim("userId", user.getUserId()) - .signWith(SignatureAlgorithm.HS256, JWT_SECRET_KEY) + .claim("userId", userId) + .signWith(SignatureAlgorithm.HS256, JWT_LOGIN_SECRET_KEY) .compact(); } public boolean isExpiredToken(String accessToken) { try { Jws claims = Jwts.parserBuilder() - .setSigningKey(JWT_SECRET_KEY).build() + .setSigningKey(JWT_LOGIN_SECRET_KEY).build() .parseClaimsJws(accessToken); return claims.getBody().getExpiration().before(new Date()); @@ -62,11 +65,11 @@ public boolean isExpiredToken(String accessToken) { public Long getUserIdFromToken(String accessToken) { try { Jws claims = Jwts.parserBuilder() - .setSigningKey(JWT_SECRET_KEY).build() + .setSigningKey(JWT_LOGIN_SECRET_KEY).build() .parseClaimsJws(accessToken); return claims.getBody().get("userId", Long.class); } catch (JwtException e) { - log.error("[JwtTokenProvider.getUserIdFromToken]", e); + log.error("[JwtTokenProvider.getJwtPayloadDtoFromToken]", e); throw e; } } diff --git a/src/main/java/space/space_spring/jwt/JwtUserSpaceProvider.java b/src/main/java/space/space_spring/jwt/JwtUserSpaceProvider.java new file mode 100644 index 00000000..e078c9d0 --- /dev/null +++ b/src/main/java/space/space_spring/jwt/JwtUserSpaceProvider.java @@ -0,0 +1,106 @@ +package space.space_spring.jwt; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.jsonwebtoken.*; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import space.space_spring.dto.jwt.JwtPayloadDto; +import space.space_spring.dto.jwt.JwtUserSpaceAuthDto; +import space.space_spring.exception.jwt.unauthorized.JwtInvalidTokenException; +import space.space_spring.exception.jwt.unauthorized.JwtMalformedTokenException; +import space.space_spring.exception.jwt.bad_request.JwtUnsupportedTokenException; + +import java.util.Date; +import java.util.List; + +import static space.space_spring.response.status.BaseExceptionResponseStatus.*; + +@Component +@Slf4j +public class JwtUserSpaceProvider { + + @Value("${secret.jwt-user-space-secret-key}") + private String JWT_USER_SPACE_SECRET_KEY; + + @Value("${secret.jwt-expired-in}") + private Long JWT_EXPIRED_IN; + + private final ObjectMapper objectMapper = new ObjectMapper(); + + public String generateToken(JwtPayloadDto jwtPayloadDto) { +// Claims claims = Jwts.claims().setSubject(jwtPayloadDto.getUserId().toString()); + + Date now = new Date(); + Date expiration = new Date(now.getTime() + JWT_EXPIRED_IN); + + Long userId = jwtPayloadDto.getUserId(); + List userSpaceList = jwtPayloadDto.getUserSpaceList(); + String userSpaceListToJson = null; + try { + userSpaceListToJson = objectMapper.writeValueAsString(userSpaceList); + } catch (JsonProcessingException e) { + log.error("Failed to convert userSpaceList to json", e); + } + + return Jwts.builder() +// .setClaims(claims) + .setIssuedAt(now) + .setExpiration(expiration) + .claim("userId", userId) + .claim("userSpaceList", userSpaceListToJson) + .signWith(SignatureAlgorithm.HS256, JWT_USER_SPACE_SECRET_KEY) + .compact(); + + } + + public boolean isExpiredToken(String accessToken) { + try { + Jws claims = Jwts.parserBuilder() + .setSigningKey(JWT_USER_SPACE_SECRET_KEY).build() + .parseClaimsJws(accessToken); + return claims.getBody().getExpiration().before(new Date()); + + } catch (ExpiredJwtException e) { + return true; + + } catch (UnsupportedJwtException e) { + throw new JwtUnsupportedTokenException(UNSUPPORTED_TOKEN_TYPE); + } catch (MalformedJwtException e) { + throw new JwtMalformedTokenException(MALFORMED_TOKEN); + } catch (IllegalArgumentException e) { + throw new JwtInvalidTokenException(INVALID_TOKEN); + } catch (JwtException e) { + log.error("[JwtTokenProvider.validateAccessToken]", e); + throw e; + } + } + + public JwtPayloadDto getJwtPayloadDtoFromToken(String accessToken) { + try { + Jws claims = Jwts.parserBuilder() + .setSigningKey(JWT_USER_SPACE_SECRET_KEY).build() + .parseClaimsJws(accessToken); + + Long userId = claims.getBody().get("userId", Long.class); + String userSpaceListToJson = claims.getBody().get("userSpaceList", String.class); + List userSpaceList = null; + try { + userSpaceList = objectMapper.readValue(userSpaceListToJson, + objectMapper.getTypeFactory().constructCollectionType(List.class, JwtUserSpaceAuthDto.class)); + } catch (JsonProcessingException e) { + log.error("Failed to convert json to userSpaceList", e); + } + + JwtPayloadDto jwtPayloadDto = new JwtPayloadDto(); + jwtPayloadDto.saveUserIdToJwt(userId); + jwtPayloadDto.saveUserSpaceList(userSpaceList); + + return jwtPayloadDto; + } catch (JwtException e) { + log.error("[JwtTokenProvider.getJwtPayloadDtoFromToken]", e); + throw e; + } + } +} diff --git a/src/main/java/space/space_spring/response/status/BaseExceptionResponseStatus.java b/src/main/java/space/space_spring/response/status/BaseExceptionResponseStatus.java index 1a5c7410..f92ef72b 100644 --- a/src/main/java/space/space_spring/response/status/BaseExceptionResponseStatus.java +++ b/src/main/java/space/space_spring/response/status/BaseExceptionResponseStatus.java @@ -40,13 +40,37 @@ public enum BaseExceptionResponseStatus implements ResponseStatus { /** * 5000: User 오류 */ - INVALID_USER_VALUE(5000, HttpStatus.BAD_REQUEST.value(), "회원가입 요청에서 잘못된 값이 존재합니다."), + INVALID_USER_SIGNUP(5000, HttpStatus.BAD_REQUEST.value(), "회원가입 요청에서 잘못된 값이 존재합니다."), DUPLICATE_EMAIL(5001, HttpStatus.BAD_REQUEST.value(), "이미 존재하는 이메일입니다."), DUPLICATE_NICKNAME(5002, HttpStatus.BAD_REQUEST.value(), "이미 존재하는 닉네임입니다."), USER_NOT_FOUND(4003, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 회원입니다."), PASSWORD_NO_MATCH(4004, HttpStatus.BAD_REQUEST.value(), "비밀번호가 일치하지 않습니다."), INVALID_USER_STATUS(4005, HttpStatus.BAD_REQUEST.value(), "잘못된 회원 status 값입니다."), - EMAIL_NOT_FOUND(4006, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 이메일입니다."); + EMAIL_NOT_FOUND(4006, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 이메일입니다."), + INVALID_USER_LOGIN(4007, HttpStatus.BAD_REQUEST.value(), "로그인 요청에서 잘못된 값이 존재합니다."), + + /** + * 6000: Space 오류 + */ + INVALID_SPACE_CREATE(6000, HttpStatus.BAD_REQUEST.value(), "스페이스 생성 요청에서 잘못된 값이 존재합니다."), + safd(6001, HttpStatus.BAD_REQUEST.value(), "이미 존재하는 이메일입니다."), + adff(6002, HttpStatus.BAD_REQUEST.value(), "이미 존재하는 닉네임입니다."), + baab(6003, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 회원입니다."), + nff(6004, HttpStatus.BAD_REQUEST.value(), "비밀번호가 일치하지 않습니다."), + gnf(6005, HttpStatus.BAD_REQUEST.value(), "잘못된 회원 status 값입니다."), + fb(6006, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 이메일입니다."), + + + /** + * 7000: 오류 + */ + A(7000, HttpStatus.BAD_REQUEST.value(), "회원가입 요청에서 잘못된 값이 존재합니다."), + B(7001, HttpStatus.BAD_REQUEST.value(), "이미 존재하는 이메일입니다."), + C(7002, HttpStatus.BAD_REQUEST.value(), "이미 존재하는 닉네임입니다."), + D(7003, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 회원입니다."), + E(7004, HttpStatus.BAD_REQUEST.value(), "비밀번호가 일치하지 않습니다."), + F(7005, HttpStatus.BAD_REQUEST.value(), "잘못된 회원 status 값입니다."), + G(7006, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 이메일입니다."); private final int code; private final int status; diff --git a/src/main/java/space/space_spring/service/SpaceService.java b/src/main/java/space/space_spring/service/SpaceService.java new file mode 100644 index 00000000..00ae53bf --- /dev/null +++ b/src/main/java/space/space_spring/service/SpaceService.java @@ -0,0 +1,47 @@ +package space.space_spring.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import space.space_spring.dao.SpaceDao; +import space.space_spring.dao.UserDao; +import space.space_spring.dto.jwt.JwtPayloadDto; +import space.space_spring.dto.jwt.JwtUserSpaceAuthDto; +import space.space_spring.dto.space.SpaceCreateDto; +import space.space_spring.entity.Space; +import space.space_spring.entity.User; +import space.space_spring.dto.space.PostSpaceCreateRequest; +import space.space_spring.dto.space.PostSpaceCreateResponse; +import space.space_spring.entity.UserSpace; +import space.space_spring.jwt.JwtUserSpaceProvider; + +@Service +@RequiredArgsConstructor +public class SpaceService { + + private final SpaceDao spaceDao; + private final UserDao userDao; + private final JwtUserSpaceProvider jwtUserSpaceProvider; + + @Transactional + public SpaceCreateDto createSpace(Long userId, PostSpaceCreateRequest postSpaceCreateRequest) { + + // TODO 1. 스페이스 생성 정보 db insert + Space saveSpace = spaceDao.saveSpace(postSpaceCreateRequest); + + // TODO 2. 유저_스페이스 매핑 정보 db insert + User manager = userDao.findUserByUserId(userId); + UserSpace userSpace = spaceDao.createUserSpace(manager, saveSpace); + + // TODO 3. jwt에 space 정보 추가 + JwtUserSpaceAuthDto jwtUserSpaceAuthDto = new JwtUserSpaceAuthDto(); + jwtUserSpaceAuthDto.saveUserSpaceAuth(userSpace.getSpace().getSpaceId(), userSpace.getUserSpaceAuth()); + + JwtPayloadDto jwtPayloadDto = new JwtPayloadDto(); + jwtPayloadDto.addJwtUserSpaceAuth(jwtUserSpaceAuthDto); + + String jwtUserSpace = jwtUserSpaceProvider.generateToken(jwtPayloadDto); + + return new SpaceCreateDto(saveSpace.getSpaceId(), jwtUserSpace); + } +} diff --git a/src/main/java/space/space_spring/service/UserService.java b/src/main/java/space/space_spring/service/UserService.java index 05863d63..52256e78 100644 --- a/src/main/java/space/space_spring/service/UserService.java +++ b/src/main/java/space/space_spring/service/UserService.java @@ -3,12 +3,14 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import space.space_spring.jwt.JwtProvider; +import space.space_spring.dto.jwt.JwtPayloadDto; +import space.space_spring.jwt.JwtLoginProvider; +import space.space_spring.jwt.JwtUserSpaceProvider; import space.space_spring.dao.UserDao; -import space.space_spring.domain.User; -import space.space_spring.dto.PostUserLoginRequest; -import space.space_spring.dto.PostUserSignupRequest; -import space.space_spring.dto.PostUserSignupResponse; +import space.space_spring.entity.User; +import space.space_spring.dto.user.PostUserLoginRequest; +import space.space_spring.dto.user.PostUserSignupRequest; +import space.space_spring.dto.user.PostUserSignupResponse; import space.space_spring.exception.UserException; import static space.space_spring.response.status.BaseExceptionResponseStatus.*; @@ -18,7 +20,7 @@ public class UserService { private final UserDao userDao; - private final JwtProvider jwtProvider; + private final JwtLoginProvider jwtLoginProvider; @Transactional public PostUserSignupResponse signup(PostUserSignupRequest postUserSignupRequest) { @@ -29,12 +31,12 @@ public PostUserSignupResponse signup(PostUserSignupRequest postUserSignupRequest // TODO 2. 회원정보 db insert - Long savedUserId = userDao.saveUser(postUserSignupRequest); + User saveUser = userDao.saveUser(postUserSignupRequest); // TODO 3. JWT 토큰 초기화 (회원가입시에는 토큰 발급 X) String jwt = null; - return new PostUserSignupResponse(savedUserId, jwt); + return new PostUserSignupResponse(saveUser.getUserId(), jwt); } private void validateEmail(String email) { @@ -52,12 +54,12 @@ public String login(PostUserLoginRequest postUserLoginRequest) { validatePassword(userByEmail, postUserLoginRequest.getPassword()); // TODO 3. JWT 발급 - String jwt = jwtProvider.generateToken(userByEmail); + String jwtLogin = jwtLoginProvider.generateToken(userByEmail); // TODO 4. JWT db에 insert -> db에 저장해야할까?? - userByEmail.saveJWTtoLoginUser(jwt); + userByEmail.saveJWTtoLoginUser(jwtLogin); - return jwt; + return jwtLogin; } private User findUserByEmail(String email) { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 4c55f267..c7b96c06 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -11,14 +11,15 @@ spring: jpa: hibernate: - ddl-auto: update # create : 존재하는 table을 전부 drop했다가 다시 생성 -> 테스트용 + ddl-auto: create # create : 존재하는 table을 전부 drop했다가 다시 생성 -> 테스트용 properties: hibernate: format_sql: true show_sql: true secret: - jwt-secret-key: ${JWT_SECRET_KEY} + jwt-login-secret-key: ${JWT_LOGIN_SECRET_KEY} + jwt-user-space-secret-key: ${JWT_USER_SPACE_SECRET_KEY} jwt-expired-in: ${JWT_EXPIRED_IN} logging: diff --git a/src/test/java/space/space_spring/service/UserServiceTest.java b/src/test/java/space/space_spring/service/UserServiceTest.java index c4d8df07..d0a19710 100644 --- a/src/test/java/space/space_spring/service/UserServiceTest.java +++ b/src/test/java/space/space_spring/service/UserServiceTest.java @@ -1,16 +1,6 @@ package space.space_spring.service; -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.Rollback; -import org.springframework.transaction.annotation.Transactional; -import space.space_spring.dao.UserDao; -import space.space_spring.domain.User; -import space.space_spring.dto.PostUserSignupRequest; -import space.space_spring.dto.PostUserSignupResponse; @SpringBootTest class UserServiceTest {