diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/Role.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/Role.java new file mode 100644 index 00000000..21caaedc --- /dev/null +++ b/src/main/java/org/prgrms/nabimarketbe/domain/user/Role.java @@ -0,0 +1,14 @@ +package org.prgrms.nabimarketbe.domain.user; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public enum Role { + GUEST("ROLE_GUEST"), + + USER("ROLE_USER"); + + private final String key; +} diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/api/UserController.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/api/UserController.java index ecc6509d..9eeabf2b 100644 --- a/src/main/java/org/prgrms/nabimarketbe/domain/user/api/UserController.java +++ b/src/main/java/org/prgrms/nabimarketbe/domain/user/api/UserController.java @@ -2,8 +2,8 @@ import lombok.RequiredArgsConstructor; -import org.prgrms.nabimarketbe.domain.user.dto.UserRequestDto; -import org.prgrms.nabimarketbe.domain.user.dto.UserResponseDto; +import org.prgrms.nabimarketbe.domain.user.dto.request.UserRequestDTO; +import org.prgrms.nabimarketbe.domain.user.dto.response.UserResponseDTO; import org.prgrms.nabimarketbe.domain.user.service.UserService; import org.prgrms.nabimarketbe.global.util.model.CommonResult; import org.prgrms.nabimarketbe.global.util.model.ListResult; @@ -14,40 +14,40 @@ @RequiredArgsConstructor @RestController -@RequestMapping("/v1") +@RequestMapping("/api/v1/users") public class UserController { private final UserService userService; private final ResponseFactory responseFactory; - @GetMapping("/user/id/{userId}") - public SingleResult findUserById(@PathVariable Long userId) { + @GetMapping("/{userId}") + public SingleResult findUserById(@PathVariable Long userId) { return responseFactory.getSingleResult(userService.findById(userId)); } - @GetMapping("/user/nickname/{nickname}") - public SingleResult findUserByNickName(@PathVariable String nickname) { - return responseFactory.getSingleResult(userService.findByNickName(nickname)); + @GetMapping("/{nickname}") + public SingleResult findUserByNickName(@PathVariable String nickname) { + return responseFactory.getSingleResult(userService.findByNickname(nickname)); } - @GetMapping("/users") - public ListResult findAllUser() { + @GetMapping + public ListResult findAllUser() { return responseFactory.getListResult(userService.findAllUser()); } - @PutMapping("/user") + @PutMapping public SingleResult update ( @RequestParam Long userId, @RequestParam String nickname ) { - UserRequestDto userRequestDto = UserRequestDto.builder() + UserRequestDTO userRequestDTO = UserRequestDTO.builder() .nickName(nickname) .build(); - return responseFactory.getSingleResult(userService.update(userId, userRequestDto)); + return responseFactory.getSingleResult(userService.update(userId, userRequestDTO)); } - @DeleteMapping("/user/{userId}") + @DeleteMapping("/{userId}") public CommonResult delete(@PathVariable Long userId) { userService.delete(userId); diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/UserResponseDto.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/UserResponseDto.java deleted file mode 100644 index 68ef2000..00000000 --- a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/UserResponseDto.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.prgrms.nabimarketbe.domain.user.dto; - -import lombok.Getter; -import org.prgrms.nabimarketbe.domain.user.entity.User; -import org.springframework.security.core.GrantedAuthority; - -import java.time.LocalDateTime; -import java.util.Collection; -import java.util.List; - -@Getter -public class UserResponseDto { - private final Long userId; - - private final String nickName; - - private List roles; - - private Collection authorities; - - private final LocalDateTime modifiedDate; - - public UserResponseDto(User user) { - this.userId = user.getUserId(); - this.nickName = user.getNickname(); - this.roles = user.getRoles(); - this.authorities = user.getAuthorities(); - this.modifiedDate = user.getModifiedDate(); - } -} diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/UserRequestDto.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/request/UserRequestDTO.java similarity index 59% rename from src/main/java/org/prgrms/nabimarketbe/domain/user/dto/UserRequestDto.java rename to src/main/java/org/prgrms/nabimarketbe/domain/user/dto/request/UserRequestDTO.java index bbd4d12d..764d2f0d 100644 --- a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/UserRequestDto.java +++ b/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/request/UserRequestDTO.java @@ -1,19 +1,14 @@ -package org.prgrms.nabimarketbe.domain.user.dto; +package org.prgrms.nabimarketbe.domain.user.dto.request; -import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; -import lombok.NoArgsConstructor; import org.prgrms.nabimarketbe.domain.user.entity.User; @Getter @Builder -@AllArgsConstructor -@NoArgsConstructor -public class UserRequestDto { - +public class UserRequestDTO { private String email; - private String name; + private String nickName; public User toEntity() { diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/request/UserSignInRequestDTO.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/request/UserSignInRequestDTO.java new file mode 100644 index 00000000..e8c75ed0 --- /dev/null +++ b/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/request/UserSignInRequestDTO.java @@ -0,0 +1,22 @@ +package org.prgrms.nabimarketbe.domain.user.dto.request; + +import lombok.Builder; +import org.prgrms.nabimarketbe.domain.user.Role; +import org.prgrms.nabimarketbe.domain.user.entity.User; + +@Builder +public record UserSignInRequestDTO( + String accountId, + String nickname, + String provider +) { + public User toEntity() { + return User.builder() + .accountId(accountId) + .nickname(nickname) + .provider(provider) + .role(Role.USER) + .build(); + } +} + diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/response/UserResponseDTO.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/response/UserResponseDTO.java new file mode 100644 index 00000000..cb767fe0 --- /dev/null +++ b/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/response/UserResponseDTO.java @@ -0,0 +1,31 @@ +package org.prgrms.nabimarketbe.domain.user.dto.response; + +import lombok.Getter; +import org.prgrms.nabimarketbe.domain.user.Role; +import org.prgrms.nabimarketbe.domain.user.entity.User; + +import java.time.LocalDateTime; + +@Getter +public class UserResponseDTO { + private final Long userId; + + private final String accountId; + + private final String nickName; + + private final Role role; + + private final LocalDateTime createdDate; + + private final LocalDateTime modifiedDate; + + public UserResponseDTO(User user) { + this.userId = user.getUserId(); + this.accountId = user.getAccountId(); + this.nickName = user.getNickname(); + this.role = user.getRole(); + this.createdDate = user.getCreatedDate(); + this.modifiedDate = user.getModifiedDate(); + } +} diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/sign/UserSignupRequestDto.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/sign/UserSignupRequestDto.java deleted file mode 100644 index c5379366..00000000 --- a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/sign/UserSignupRequestDto.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.prgrms.nabimarketbe.domain.user.dto.sign; - -import lombok.Builder; -import org.prgrms.nabimarketbe.domain.user.entity.User; - -import java.util.Collections; - -@Builder -public record UserSignupRequestDto(String nickname, String provider) { - public User toEntity() { - return User.builder() - .nickname(nickname) - .provider(provider) - .roles(Collections.singletonList("ROLE_USER")) - .build(); - } -} - diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/sign/UserSocialLoginRequestDto.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/sign/UserSocialLoginRequestDto.java deleted file mode 100644 index 3ffdf56a..00000000 --- a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/sign/UserSocialLoginRequestDto.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.prgrms.nabimarketbe.domain.user.dto.sign; - -import lombok.*; - -@Builder -public record UserSocialLoginRequestDto(String accessToken) { -} diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/sign/UserSocialSignupRequestDto.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/sign/UserSocialSignupRequestDto.java deleted file mode 100644 index 630e2c14..00000000 --- a/src/main/java/org/prgrms/nabimarketbe/domain/user/dto/sign/UserSocialSignupRequestDto.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.prgrms.nabimarketbe.domain.user.dto.sign; - -import lombok.*; - -@Builder -public record UserSocialSignupRequestDto(String accessToken) { -} - diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/entity/User.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/entity/User.java index 22fb817d..abeb75e3 100644 --- a/src/main/java/org/prgrms/nabimarketbe/domain/user/entity/User.java +++ b/src/main/java/org/prgrms/nabimarketbe/domain/user/entity/User.java @@ -5,16 +5,16 @@ import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; + import org.prgrms.nabimarketbe.global.BaseEntity; +import org.prgrms.nabimarketbe.domain.user.Role; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; +import java.util.Collections; @Builder @Entity @@ -27,6 +27,9 @@ public class User extends BaseEntity implements UserDetails { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long userId; + @Column(nullable = false, unique = true, length = 30) + private String accountId; + @Column(name = "nick_name", nullable = false, length = 20) private String nickname; @@ -34,23 +37,30 @@ public class User extends BaseEntity implements UserDetails { private String email; @Column(name = "user_image_url") - private String image_url; + private String imageUrl; @Column(length = 100) private String provider; - @ElementCollection(fetch = FetchType.EAGER) - @Builder.Default - private List roles = new ArrayList<>(); + @Enumerated(EnumType.STRING) + @Column(name = "user_role") + private Role role; + + private User( + String accountId, + String nickname, + String profileImageUrl, + Role role + ) { + } public void updateNickname(String nickname) { this.nickname = nickname; } + @Override public Collection getAuthorities() { - return this.roles - .stream().map(SimpleGrantedAuthority::new) - .collect(Collectors.toList()); + return Collections.singletonList(new SimpleGrantedAuthority(this.role.toString())); } @Override @@ -58,32 +68,32 @@ public String getPassword() { return null; } - @Override @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Override public String getUsername() { return String.valueOf(this.userId); } - @Override @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Override public boolean isAccountNonExpired() { return true; } - @Override @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Override public boolean isAccountNonLocked() { return true; } - @Override @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Override public boolean isCredentialsNonExpired() { return true; } - @Override @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @Override public boolean isEnabled() { return true; } diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/repository/UserJpaRepo.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/repository/UserRepository.java similarity index 64% rename from src/main/java/org/prgrms/nabimarketbe/domain/user/repository/UserJpaRepo.java rename to src/main/java/org/prgrms/nabimarketbe/domain/user/repository/UserRepository.java index 5db57dd2..1ee1b5c2 100644 --- a/src/main/java/org/prgrms/nabimarketbe/domain/user/repository/UserJpaRepo.java +++ b/src/main/java/org/prgrms/nabimarketbe/domain/user/repository/UserRepository.java @@ -7,8 +7,12 @@ import java.util.Optional; @Repository -public interface UserJpaRepo extends JpaRepository { +public interface UserRepository extends JpaRepository { Optional findByNickname(String name); + Optional findByEmail(String email); - Optional findByNicknameAndProvider(String name, String provider); + + Optional findByAccountIdAndProvider(String accountId, String provider); + + Optional findByAccountId(String oauthId); } diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/service/SignService.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/service/SignService.java index 4f2cc528..95099239 100644 --- a/src/main/java/org/prgrms/nabimarketbe/domain/user/service/SignService.java +++ b/src/main/java/org/prgrms/nabimarketbe/domain/user/service/SignService.java @@ -2,19 +2,15 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.prgrms.nabimarketbe.global.security.jwt.dto.TokenRequestDto; + import org.prgrms.nabimarketbe.oauth2.kakao.dto.KakaoProfile; -import org.prgrms.nabimarketbe.oauth2.kakao.service.OAuth2Service; -import org.prgrms.nabimarketbe.domain.user.dto.sign.UserSignupRequestDto; +import org.prgrms.nabimarketbe.domain.user.dto.request.UserSignInRequestDTO; import org.prgrms.nabimarketbe.global.security.jwt.provider.JwtProvider; -import org.prgrms.nabimarketbe.global.security.entity.RefreshToken; -import org.prgrms.nabimarketbe.oauth2.kakao.repository.RefreshTokenJpaRepo; -import org.prgrms.nabimarketbe.global.security.jwt.dto.TokenDto; import org.prgrms.nabimarketbe.domain.user.entity.User; -import org.prgrms.nabimarketbe.domain.user.repository.UserJpaRepo; +import org.prgrms.nabimarketbe.domain.user.repository.UserRepository; import org.prgrms.nabimarketbe.global.util.ResponseFactory; import org.prgrms.nabimarketbe.global.util.model.CommonResult; -import org.springframework.security.core.Authentication; + import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -24,23 +20,16 @@ @Service @RequiredArgsConstructor public class SignService { - private final UserJpaRepo userJpaRepo; - - private final OAuth2Service OAuth2Service; + private final UserRepository userRepository; private final ResponseFactory responseFactory; private final JwtProvider jwtProvider; - private final RefreshTokenJpaRepo tokenJpaRepo; - @Transactional - public CommonResult signupBySocial(String accessToken) { - KakaoProfile kakaoProfile = OAuth2Service.getKakaoProfile(accessToken); - - if (kakaoProfile == null) throw new RuntimeException("카카오에 해당 회원이 없습니다."); - - CommonResult result = socialSignup(UserSignupRequestDto.builder() + public CommonResult signInBySocial(KakaoProfile kakaoProfile) { + CommonResult result = signIn(UserSignInRequestDTO.builder() + .accountId(kakaoProfile.getId()) .nickname(kakaoProfile.getProperties().getNickname()) .provider("kakao") .build()); @@ -48,48 +37,19 @@ public CommonResult signupBySocial(String accessToken) { return responseFactory.getSingleResult(result); } @Transactional - public CommonResult socialSignup(UserSignupRequestDto userSignupRequestDto) { - Optional user = userJpaRepo.findByNicknameAndProvider( - userSignupRequestDto.nickname(), - userSignupRequestDto.provider() + public CommonResult signIn(UserSignInRequestDTO userSignInRequestDTO) { + Optional user = userRepository.findByAccountIdAndProvider( + userSignInRequestDTO.accountId(), + userSignInRequestDTO.provider() ); if (user.isPresent()) { - return responseFactory.getSingleResult(jwtProvider.createTokenDto(user.get().getUserId(), user.get().getRoles())); + return responseFactory.getSingleResult(jwtProvider.createTokenDTO( + user.get().getUserId(), user.get().getRole()) + ); } - userJpaRepo.save(userSignupRequestDto.toEntity()); - return responseFactory.getSingleResult(jwtProvider.createTokenDto(user.get().getUserId(), user.get().getRoles())); - } - - @Transactional - public TokenDto reissue(TokenRequestDto tokenRequestDto) { - // 만료된 refresh token 에러 - if (!jwtProvider.validationToken(tokenRequestDto.getAccessToken())) { - throw new RuntimeException("RefreshTokenException"); - } - - // AccessToken 에서 Username (pk) 가져오기 - String accessToken = tokenRequestDto.getAccessToken(); - Authentication authentication = jwtProvider.getAuthentication(accessToken); - - // user pk로 유저 검색 / repo 에 저장된 Refresh Token 이 없음 - User user = userJpaRepo.findById(Long.parseLong(authentication.getName())) - .orElseThrow(() ->new RuntimeException("RefreshTokenException")); - - RefreshToken refreshToken = tokenJpaRepo.findByKey(user.getUserId()) - .orElseThrow(() ->new RuntimeException("RefreshTokenException")); - - // 리프레시 토큰 불일치 에러 - if (!refreshToken.getToken().equals(tokenRequestDto.getRefreshToken())) - throw new RuntimeException("RefreshTokenException"); - - // AccessToken, RefreshToken 토큰 재발급, 리프레쉬 토큰 저장 - TokenDto newCreatedToken = jwtProvider.createTokenDto(user.getUserId(), user.getRoles()); - RefreshToken updateRefreshToken = refreshToken.updateToken(newCreatedToken.getRefreshToken()); - - tokenJpaRepo.save(updateRefreshToken); - - return newCreatedToken; + User savedUser = userRepository.save(userSignInRequestDTO.toEntity()); + return responseFactory.getSingleResult(jwtProvider.createTokenDTO(savedUser.getUserId(), savedUser.getRole())); } } diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/user/service/UserService.java b/src/main/java/org/prgrms/nabimarketbe/domain/user/service/UserService.java index bdac9995..9221007b 100644 --- a/src/main/java/org/prgrms/nabimarketbe/domain/user/service/UserService.java +++ b/src/main/java/org/prgrms/nabimarketbe/domain/user/service/UserService.java @@ -2,10 +2,12 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.prgrms.nabimarketbe.domain.user.dto.UserRequestDto; -import org.prgrms.nabimarketbe.domain.user.dto.UserResponseDto; + +import org.prgrms.nabimarketbe.domain.user.dto.request.UserRequestDTO; +import org.prgrms.nabimarketbe.domain.user.dto.response.UserResponseDTO; import org.prgrms.nabimarketbe.domain.user.entity.User; -import org.prgrms.nabimarketbe.domain.user.repository.UserJpaRepo; +import org.prgrms.nabimarketbe.domain.user.repository.UserRepository; + import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -16,43 +18,51 @@ @Service @AllArgsConstructor public class UserService { - private UserJpaRepo userJpaRepo; + private UserRepository userRepository; + + @Transactional(readOnly = true) + public UserResponseDTO findById(Long id) { + User user = userRepository.findById(id) + .orElseThrow(() -> new RuntimeException("해당 회원이 없습니다.")); + + return new UserResponseDTO(user); + } @Transactional(readOnly = true) - public UserResponseDto findById(Long id) { - User user = userJpaRepo.findById(id) + public UserResponseDTO findByAccountId(String accountId) { + User user = userRepository.findByAccountId(accountId) .orElseThrow(() -> new RuntimeException("해당 회원이 없습니다.")); - return new UserResponseDto(user); + return new UserResponseDTO(user); } @Transactional(readOnly = true) - public UserResponseDto findByNickName(String nickname) { - User user = userJpaRepo.findByNickname(nickname) + public UserResponseDTO findByNickname(String nickname) { + User user = userRepository.findByNickname(nickname) .orElseThrow(() -> new RuntimeException("해당 회원이 없습니다.")); - return new UserResponseDto(user); + return new UserResponseDTO(user); } @Transactional(readOnly = true) - public List findAllUser() { - return userJpaRepo.findAll() + public List findAllUser() { + return userRepository.findAll() .stream() - .map(UserResponseDto::new) + .map(UserResponseDTO::new) .collect(Collectors.toList()); } @Transactional - public Long update(Long id, UserRequestDto userRequestDto) { - User modifiedUser = userJpaRepo + public Long update(Long id, UserRequestDTO userRequestDTO) { + User modifiedUser = userRepository .findById(id).orElseThrow(() -> new RuntimeException("해당 회원이 없습니다.")); - modifiedUser.updateNickname(userRequestDto.getNickName()); + modifiedUser.updateNickname(userRequestDTO.getNickName()); return id; } @Transactional public void delete(Long id) { - userJpaRepo.deleteById(id); + userRepository.deleteById(id); } } diff --git a/src/main/java/org/prgrms/nabimarketbe/global/config/SecurityConfiguration.java b/src/main/java/org/prgrms/nabimarketbe/global/config/SecurityConfiguration.java index 6c490bb8..3e1bb131 100644 --- a/src/main/java/org/prgrms/nabimarketbe/global/config/SecurityConfiguration.java +++ b/src/main/java/org/prgrms/nabimarketbe/global/config/SecurityConfiguration.java @@ -1,10 +1,12 @@ package org.prgrms.nabimarketbe.global.config; import lombok.RequiredArgsConstructor; + import org.prgrms.nabimarketbe.global.security.handler.CustomAccessDeniedHandler; import org.prgrms.nabimarketbe.global.security.handler.CustomAuthenticationEntryPoint; -import org.prgrms.nabimarketbe.global.security.jwt.provider.JwtProvider; import org.prgrms.nabimarketbe.global.security.jwt.filter.JwtAuthenticationFilter; +import org.prgrms.nabimarketbe.global.security.jwt.provider.JwtProvider; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; @@ -12,8 +14,8 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @RequiredArgsConstructor @Configuration @@ -24,6 +26,7 @@ public class SecurityConfiguration { private final CustomAccessDeniedHandler customAccessDeniedHandler; + @Bean public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http @@ -34,7 +37,7 @@ public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws .authorizeRequests(authorizeRequests -> authorizeRequests .antMatchers(HttpMethod.POST, "/v1/signup", "/v1/login", "/v1/reissue", "/v1/social/**").permitAll() - .antMatchers(HttpMethod.GET, "/oauth/kakao/**").permitAll() + .antMatchers(HttpMethod.GET, "/api/v1/users/oauth2/authorize/kakao/**").permitAll() .antMatchers(HttpMethod.GET, "/exception/**").permitAll() .anyRequest ().hasRole("USER")) .exceptionHandling(exceptionHandling -> exceptionHandling @@ -45,6 +48,7 @@ public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws return http.build(); } + @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().antMatchers("/v2/api-docs", "/webjars/**", "/swagger/**", "/h2-console/**"); diff --git a/src/main/java/org/prgrms/nabimarketbe/global/security/entity/RefreshToken.java b/src/main/java/org/prgrms/nabimarketbe/global/security/entity/RefreshToken.java index 1e29a50f..ee8fab32 100644 --- a/src/main/java/org/prgrms/nabimarketbe/global/security/entity/RefreshToken.java +++ b/src/main/java/org/prgrms/nabimarketbe/global/security/entity/RefreshToken.java @@ -13,9 +13,9 @@ public class RefreshToken extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - private String id; + private Long id; - @Column(nullable = false) + @Column(name = "key_id", nullable = false) private Long key; @Column(nullable = false) diff --git a/src/main/java/org/prgrms/nabimarketbe/domain/security/jwt/dto/TokenResponseDto.java b/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/dto/TokenDTO.java similarity index 71% rename from src/main/java/org/prgrms/nabimarketbe/domain/security/jwt/dto/TokenResponseDto.java rename to src/main/java/org/prgrms/nabimarketbe/global/security/jwt/dto/TokenDTO.java index 743c69af..8f05ccb7 100644 --- a/src/main/java/org/prgrms/nabimarketbe/domain/security/jwt/dto/TokenResponseDto.java +++ b/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/dto/TokenDTO.java @@ -1,4 +1,4 @@ -package org.prgrms.nabimarketbe.domain.security.jwt.dto; +package org.prgrms.nabimarketbe.global.security.jwt.dto; import lombok.*; @@ -7,7 +7,7 @@ @Builder @NoArgsConstructor @AllArgsConstructor -public class TokenResponseDto { +public class TokenDTO { private String grantType; private String accessToken; diff --git a/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/dto/TokenRequestDto.java b/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/dto/TokenRequestDto.java deleted file mode 100644 index a7ecbe41..00000000 --- a/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/dto/TokenRequestDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.prgrms.nabimarketbe.global.security.jwt.dto; - -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -@Getter -@Setter -@NoArgsConstructor -public class TokenRequestDto { - String accessToken; - String refreshToken; - - @Builder - public TokenRequestDto(String accessToken, String refreshToken) { - this.accessToken = accessToken; - this.refreshToken = refreshToken; - } -} diff --git a/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/provider/JwtProvider.java b/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/provider/JwtProvider.java index 99a18ea3..02167965 100644 --- a/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/provider/JwtProvider.java +++ b/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/provider/JwtProvider.java @@ -4,7 +4,10 @@ import io.jsonwebtoken.impl.Base64UrlCodec; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.prgrms.nabimarketbe.global.security.jwt.dto.TokenDto; +import org.prgrms.nabimarketbe.global.security.entity.RefreshToken; +import org.prgrms.nabimarketbe.global.security.jwt.dto.TokenDTO; +import org.prgrms.nabimarketbe.domain.user.Role; +import org.prgrms.nabimarketbe.global.security.jwt.repository.RefreshTokenRepository; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -16,7 +19,6 @@ import javax.servlet.http.HttpServletRequest; import java.nio.charset.StandardCharsets; import java.util.Date; -import java.util.List; @Slf4j @RequiredArgsConstructor @@ -24,12 +26,14 @@ public class JwtProvider { @Value("spring.jwt.secret") private String secretKey; - private String ROLES = "roles"; + private String ROLE = "role"; private final Long accessTokenValidMillisecond = 60 * 60 * 1000L; // 1 hour private final Long refreshTokenValidMillisecond = 14 * 24 * 60 * 60 * 1000L; // 14 day private final UserDetailsService userDetailsService; + private final RefreshTokenRepository refreshTokenRepository; + @PostConstruct protected void init() { // 암호화 @@ -37,10 +41,10 @@ protected void init() { } // Jwt 생성 - public TokenDto createTokenDto(Long userPk, List roles) { + public TokenDTO createTokenDTO(Long userPk, Role role) { // Claims 에 user 구분을 위한 User pk 및 authorities 목록 삽입 Claims claims = Jwts.claims().setSubject(String.valueOf(userPk)); - claims.put(ROLES, roles); + claims.put(ROLE, role); // 생성날짜, 만료날짜를 위한 Date Date now = new Date(); @@ -59,7 +63,10 @@ public TokenDto createTokenDto(Long userPk, List roles) { .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); - return TokenDto.builder() + RefreshToken refreshTokenEntity = new RefreshToken(userPk, refreshToken); + refreshTokenRepository.save(refreshTokenEntity); + + return TokenDTO.builder() .grantType("Bearer") .accessToken(accessToken) .refreshToken(refreshToken) @@ -73,7 +80,7 @@ public Authentication getAuthentication(String token) { Claims claims = parseClaims(token); // 권한 정보가 없음 - if (claims.get(ROLES) == null) { + if (claims.get(ROLE) == null) { throw new RuntimeException("AuthenticationEntryPointException"); } diff --git a/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/repository/RefreshTokenJpaRepo.java b/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/repository/RefreshTokenRepository.java similarity index 58% rename from src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/repository/RefreshTokenJpaRepo.java rename to src/main/java/org/prgrms/nabimarketbe/global/security/jwt/repository/RefreshTokenRepository.java index 3654e063..c1a8923d 100644 --- a/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/repository/RefreshTokenJpaRepo.java +++ b/src/main/java/org/prgrms/nabimarketbe/global/security/jwt/repository/RefreshTokenRepository.java @@ -1,9 +1,9 @@ -package org.prgrms.nabimarketbe.oauth2.kakao.repository; +package org.prgrms.nabimarketbe.global.security.jwt.repository; import org.prgrms.nabimarketbe.global.security.entity.RefreshToken; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; -public interface RefreshTokenJpaRepo extends JpaRepository { +public interface RefreshTokenRepository extends JpaRepository { Optional findByKey(Long key); } diff --git a/src/main/java/org/prgrms/nabimarketbe/global/util/ResponseFactory.java b/src/main/java/org/prgrms/nabimarketbe/global/util/ResponseFactory.java index 2c866917..3c338d0c 100644 --- a/src/main/java/org/prgrms/nabimarketbe/global/util/ResponseFactory.java +++ b/src/main/java/org/prgrms/nabimarketbe/global/util/ResponseFactory.java @@ -1,6 +1,7 @@ package org.prgrms.nabimarketbe.global.util; import lombok.extern.slf4j.Slf4j; + import org.prgrms.nabimarketbe.global.util.model.CommonResponse; import org.prgrms.nabimarketbe.global.util.model.CommonResult; import org.prgrms.nabimarketbe.global.util.model.ListResult; diff --git a/src/main/java/org/prgrms/nabimarketbe/oauth2/google/member/dto/OAuth2Attributes.java b/src/main/java/org/prgrms/nabimarketbe/oauth2/google/member/dto/OAuth2Attributes.java index 8b410963..9d3b5178 100644 --- a/src/main/java/org/prgrms/nabimarketbe/oauth2/google/member/dto/OAuth2Attributes.java +++ b/src/main/java/org/prgrms/nabimarketbe/oauth2/google/member/dto/OAuth2Attributes.java @@ -1,52 +1,52 @@ -package org.prgrms.nabimarketbe.oauth2.google.member.dto; - -import java.util.Collections; -import java.util.Map; - -import org.prgrms.nabimarketbe.domain.user.entity.User; -import lombok.Builder; -import lombok.Getter; - -@Getter -public class OAuth2Attributes { - - public Map attributes; - private String nameAttributeKey; - private String name; - private String email; - private String image_url; - - @Builder - public OAuth2Attributes(Map attributes, String nameAttributeKey, String name, String email - ,String image_url){ - this.attributes=attributes; - this.nameAttributeKey=nameAttributeKey; - this.name=name; - this.email=email; - this.image_url = image_url; - } - - public static OAuth2Attributes of(String registrationId, String userNameAttributeName, Map attributes){ - return ofGoogle(userNameAttributeName, attributes); - } - - private static OAuth2Attributes ofGoogle(String userNameAttributeName, Map attributes){ - return OAuth2Attributes.builder() - .name((String) attributes.get("name")) - .email((String)attributes.get("email")) - .nameAttributeKey(userNameAttributeName) - .attributes(attributes) - .image_url((String) attributes.get("picture")) - .build(); - } - - public User toEntity(){ - return User.builder() - .email(email) - .nickname(name) - .image_url(image_url) - .roles(Collections.singletonList("ROLE_USER")) - .build(); - } - -} +//package org.prgrms.nabimarketbe.oauth2.google.member.dto; +// +//import java.util.Collections; +//import java.util.Map; +// +//import org.prgrms.nabimarketbe.domain.user.entity.User; +//import lombok.Builder; +//import lombok.Getter; +// +//@Getter +//public class OAuth2Attributes { +// +// public Map attributes; +// private String nameAttributeKey; +// private String name; +// private String email; +// private String image_url; +// +// @Builder +// public OAuth2Attributes(Map attributes, String nameAttributeKey, String name, String email +// ,String image_url){ +// this.attributes=attributes; +// this.nameAttributeKey=nameAttributeKey; +// this.name=name; +// this.email=email; +// this.image_url = image_url; +// } +// +// public static OAuth2Attributes of(String registrationId, String userNameAttributeName, Map attributes){ +// return ofGoogle(userNameAttributeName, attributes); +// } +// +// private static OAuth2Attributes ofGoogle(String userNameAttributeName, Map attributes){ +// return OAuth2Attributes.builder() +// .name((String) attributes.get("name")) +// .email((String)attributes.get("email")) +// .nameAttributeKey(userNameAttributeName) +// .attributes(attributes) +// .image_url((String) attributes.get("picture")) +// .build(); +// } +// +// public User toEntity(){ +// return User.builder() +// .email(email) +// .nickname(name) +// .image_url(image_url) +// .roles(Collections.singletonList("ROLE_USER")) +// .build(); +// } +// +//} diff --git a/src/main/java/org/prgrms/nabimarketbe/oauth2/google/member/oauth2/service/CustomOAuth2UserService.java b/src/main/java/org/prgrms/nabimarketbe/oauth2/google/member/oauth2/service/CustomOAuth2UserService.java index 6c60416e..f5011fde 100644 --- a/src/main/java/org/prgrms/nabimarketbe/oauth2/google/member/oauth2/service/CustomOAuth2UserService.java +++ b/src/main/java/org/prgrms/nabimarketbe/oauth2/google/member/oauth2/service/CustomOAuth2UserService.java @@ -1,62 +1,62 @@ -package org.prgrms.nabimarketbe.oauth2.google.member.oauth2.service; - -import java.util.Collections; -import java.util.Optional; - -import javax.transaction.Transactional; - -import org.prgrms.nabimarketbe.domain.user.entity.User; -import org.prgrms.nabimarketbe.domain.user.repository.UserJpaRepo; -import org.prgrms.nabimarketbe.oauth2.google.member.dto.OAuth2Attributes; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; -import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; -import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; -import org.springframework.security.oauth2.core.OAuth2AuthenticationException; -import org.springframework.security.oauth2.core.user.DefaultOAuth2User; -import org.springframework.security.oauth2.core.user.OAuth2User; -import org.springframework.stereotype.Service; - -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; - -@RequiredArgsConstructor -@Service -@Transactional -@Slf4j -public class CustomOAuth2UserService implements OAuth2UserService { - - private final UserJpaRepo userRepository; - - @Override - public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { - OAuth2UserService delegate = new DefaultOAuth2UserService(); - OAuth2User oAuth2User = delegate.loadUser(userRequest); - - log.info("loadUser : {} ", userRequest.toString()); - - String registrationId = userRequest.getClientRegistration().getRegistrationId(); - String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint() - .getUserNameAttributeName(); - - OAuth2Attributes attributes = OAuth2Attributes.of(registrationId, userNameAttributeName, oAuth2User.getAttributes()); - - User user = saveIfNotPresent(attributes); - - return new DefaultOAuth2User(Collections.singleton( - new SimpleGrantedAuthority(user.getRoles().get(0))), - attributes.getAttributes(), - attributes.getNameAttributeKey() - ); - } - - // TODO : 메소드 기능에 맞게 수정하기 - private User saveIfNotPresent(OAuth2Attributes attributes){ - Optional user = userRepository.findByEmail(attributes.getEmail()); - if(user.isEmpty()) { - return userRepository.save(attributes.toEntity()); - } - - return user.get(); - } -} +//package org.prgrms.nabimarketbe.oauth2.google.member.oauth2.service; +// +//import java.util.Collections; +//import java.util.Optional; +// +//import javax.transaction.Transactional; +// +//import org.prgrms.nabimarketbe.domain.user.entity.User; +//import org.prgrms.nabimarketbe.domain.user.repository.UserJpaRepo; +//import org.prgrms.nabimarketbe.oauth2.google.member.dto.OAuth2Attributes; +//import org.springframework.security.core.authority.SimpleGrantedAuthority; +//import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; +//import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; +//import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; +//import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +//import org.springframework.security.oauth2.core.user.DefaultOAuth2User; +//import org.springframework.security.oauth2.core.user.OAuth2User; +//import org.springframework.stereotype.Service; +// +//import lombok.RequiredArgsConstructor; +//import lombok.extern.slf4j.Slf4j; +// +//@RequiredArgsConstructor +//@Service +//@Transactional +//@Slf4j +//public class CustomOAuth2UserService implements OAuth2UserService { +// +// private final UserJpaRepo userRepository; +// +// @Override +// public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { +// OAuth2UserService delegate = new DefaultOAuth2UserService(); +// OAuth2User oAuth2User = delegate.loadUser(userRequest); +// +// log.info("loadUser : {} ", userRequest.toString()); +// +// String registrationId = userRequest.getClientRegistration().getRegistrationId(); +// String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint() +// .getUserNameAttributeName(); +// +// OAuth2Attributes attributes = OAuth2Attributes.of(registrationId, userNameAttributeName, oAuth2User.getAttributes()); +// +// User user = saveIfNotPresent(attributes); +// +// return new DefaultOAuth2User(Collections.singleton( +// new SimpleGrantedAuthority(user.getRole())), +// attributes.getAttributes(), +// attributes.getNameAttributeKey() +// ); +// } +// +// // TODO : 메소드 기능에 맞게 수정하기 +// private User saveIfNotPresent(OAuth2Attributes attributes){ +// Optional user = userRepository.findByEmail(attributes.getEmail()); +// if(user.isEmpty()) { +// return userRepository.save(attributes.toEntity()); +// } +// +// return user.get(); +// } +//} diff --git a/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/api/OAuth2Controller.java b/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/api/OAuth2Controller.java index 5cd03b62..38e29e80 100644 --- a/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/api/OAuth2Controller.java +++ b/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/api/OAuth2Controller.java @@ -2,20 +2,18 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.prgrms.nabimarketbe.global.security.jwt.dto.TokenDto; -import org.prgrms.nabimarketbe.global.security.jwt.dto.TokenRequestDto; + import org.prgrms.nabimarketbe.domain.user.service.SignService; import org.prgrms.nabimarketbe.global.util.model.CommonResult; import org.prgrms.nabimarketbe.global.util.ResponseFactory; +import org.prgrms.nabimarketbe.oauth2.kakao.dto.KakaoProfile; import org.prgrms.nabimarketbe.oauth2.kakao.service.OAuth2Service; -import org.prgrms.nabimarketbe.global.util.model.SingleResult; -import org.springframework.beans.factory.annotation.Value; + import org.springframework.core.env.Environment; import org.springframework.http.*; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; -import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -23,7 +21,7 @@ @Slf4j @RestController @RequiredArgsConstructor -@RequestMapping("/oauth/kakao") +@RequestMapping("/api/v1/users/oauth2/authorize/kakao") public class OAuth2Controller { private final RestTemplate restTemplate; @@ -35,38 +33,21 @@ public class OAuth2Controller { private final ResponseFactory responseFactory; - @Value("${spring.url.base}") - private String baseUrl; - - @Value("${social.kakao.client-id}") - private String kakaoClientId; - - @Value("${social.kakao.redirect}") - private String kakaoRedirectUri; - @GetMapping("/login") public void socialLogin(HttpServletResponse response) throws IOException { - StringBuilder loginUri = new StringBuilder() - .append(env.getProperty("social.kakao.url.login")) - .append("?response_type=code") - .append("&client_id=").append(kakaoClientId) - .append("&redirect_uri=").append(baseUrl).append(kakaoRedirectUri); - + StringBuilder loginUri = OAuth2Service.createUri(); response.sendRedirect(String.valueOf(loginUri)); } @GetMapping(value = "/redirect") - public CommonResult redirectKakao( - ModelAndView mav, - @RequestParam String code) { - //받은 token info 에서 acccess token 추출 - String accessToken = OAuth2Service.getKakaoTokenInfo(code).getAccess_token(); - - log.info(accessToken); + public CommonResult redirectKakao(@RequestParam String code) { + KakaoProfile profile = OAuth2Service.getResultProfile(code); + if (profile == null) throw new RuntimeException("카카오에 해당 회원이 없습니다."); - return signService.signupBySocial(accessToken); + return signService.signInBySocial(profile); } + //TODO : 사용자가 accessToken 넘기는건 아닌거 같음 @GetMapping(value = "/unlink") public CommonResult unlinkKakao(@RequestParam String accessToken) { String unlinkUri = env.getProperty("social.kakao.url.unlink"); @@ -88,11 +69,4 @@ public CommonResult unlinkKakao(@RequestParam String accessToken) { throw new RuntimeException("CommunicationException"); } - - //엑세스 토큰 만료시 회원 검증 후 리프레쉬 토큰을 검증해서 액세스 토큰과 리프레시 토큰을 재발급 - @PostMapping("/reissue") - public SingleResult reissue( - @RequestBody TokenRequestDto tokenRequestDto) { - return responseFactory.getSingleResult(signService.reissue(tokenRequestDto)); - } } diff --git a/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/dto/KakaoProfile.java b/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/dto/KakaoProfile.java index 4bce3bf4..8a7f1d94 100644 --- a/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/dto/KakaoProfile.java +++ b/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/dto/KakaoProfile.java @@ -5,7 +5,7 @@ @Getter public class KakaoProfile { - private Long id; + private String id; private Properties properties; diff --git a/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/service/CustomUserDetailsService.java b/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/service/CustomUserDetailsService.java index 7b480685..9b93fcb1 100644 --- a/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/service/CustomUserDetailsService.java +++ b/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/service/CustomUserDetailsService.java @@ -1,7 +1,7 @@ package org.prgrms.nabimarketbe.oauth2.kakao.service; import lombok.RequiredArgsConstructor; -import org.prgrms.nabimarketbe.domain.user.repository.UserJpaRepo; +import org.prgrms.nabimarketbe.domain.user.repository.UserRepository; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; @@ -12,12 +12,12 @@ @Service public class CustomUserDetailsService implements UserDetailsService { - private final UserJpaRepo userJpaRepo; + private final UserRepository userRepository; @Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String userPk) throws UsernameNotFoundException { - return userJpaRepo.findById(Long.parseLong(userPk)) + return userRepository.findById(Long.parseLong(userPk)) .orElseThrow(() -> new RuntimeException("user not found exception")); } } diff --git a/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/service/OAuth2Service.java b/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/service/OAuth2Service.java index 951d7088..04db56b5 100644 --- a/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/service/OAuth2Service.java +++ b/src/main/java/org/prgrms/nabimarketbe/oauth2/kakao/service/OAuth2Service.java @@ -32,6 +32,16 @@ public class OAuth2Service { @Value("${social.kakao.redirect}") private String kakaoRedirectUri; + public StringBuilder createUri() { + StringBuilder loginUri = new StringBuilder() + .append(env.getProperty("social.kakao.url.login")) + .append("?response_type=code") + .append("&client_id=").append(kakaoClientId) + .append("&redirect_uri=").append(baseUrl).append(kakaoRedirectUri); + + return loginUri; + } + public KakaoProfile getKakaoProfile(String kakaoAccessToken) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); @@ -77,4 +87,8 @@ public RetKakaoOAuth getKakaoTokenInfo(String code) { throw new RuntimeException("CommunicationException"); } + + public KakaoProfile getResultProfile(String code) { + return getKakaoProfile(getKakaoTokenInfo(code).getAccess_token()); + } } diff --git a/src/main/resources/templates/social/login.ftl b/src/main/resources/templates/social/login.ftl deleted file mode 100644 index 4479c6ad..00000000 --- a/src/main/resources/templates/social/login.ftl +++ /dev/null @@ -1,6 +0,0 @@ - - \ No newline at end of file diff --git a/src/main/resources/templates/social/redirectKakao.ftl b/src/main/resources/templates/social/redirectKakao.ftl deleted file mode 100644 index e738d13d..00000000 --- a/src/main/resources/templates/social/redirectKakao.ftl +++ /dev/null @@ -1,8 +0,0 @@ -
    -
  1. token_type : ${authInfo.token_type}
  2. -
  3. access_token : ${authInfo.access_token}
  4. -
  5. expires_in : ${authInfo.expires_in}
  6. -
  7. refresh_token : ${authInfo.refresh_token}
  8. -
  9. refresh_token_expires_in : ${authInfo.refresh_token_expires_in}
  10. -
  11. scope : ${authInfo.scope}
  12. -
\ No newline at end of file diff --git a/src/test/java/org/prgrms/nabimarketbe/user/controller/UserControllerTest.java b/src/test/java/org/prgrms/nabimarketbe/user/controller/UserControllerTest.java index f6282368..f05c950a 100644 --- a/src/test/java/org/prgrms/nabimarketbe/user/controller/UserControllerTest.java +++ b/src/test/java/org/prgrms/nabimarketbe/user/controller/UserControllerTest.java @@ -2,13 +2,13 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.prgrms.nabimarketbe.domain.user.Role; import org.prgrms.nabimarketbe.domain.user.entity.User; -import org.prgrms.nabimarketbe.domain.user.repository.UserJpaRepo; +import org.prgrms.nabimarketbe.domain.user.repository.UserRepository; import org.prgrms.nabimarketbe.domain.user.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; @@ -16,8 +16,6 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import java.util.Collections; - import static org.hamcrest.core.Is.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -36,18 +34,15 @@ public class UserControllerTest { UserService userService; @Autowired - UserJpaRepo userJpaRepo; - - @Autowired - PasswordEncoder passwordEncoder; + UserRepository userRepository; private static int id; @BeforeEach public void setUp() { - User save = userJpaRepo.save(User.builder() + User save = userRepository.save(User.builder() .nickname("xinxinzara") - .roles(Collections.singletonList("ROLE_USER")) + .role(Role.USER) .build()); id = Math.toIntExact(save.getUserId()); } diff --git a/src/test/java/org/prgrms/nabimarketbe/user/repository/UserJpaRepoTest.java b/src/test/java/org/prgrms/nabimarketbe/user/repository/UserRepositoryTest.java similarity index 74% rename from src/test/java/org/prgrms/nabimarketbe/user/repository/UserJpaRepoTest.java rename to src/test/java/org/prgrms/nabimarketbe/user/repository/UserRepositoryTest.java index e95ae456..eb719721 100644 --- a/src/test/java/org/prgrms/nabimarketbe/user/repository/UserJpaRepoTest.java +++ b/src/test/java/org/prgrms/nabimarketbe/user/repository/UserRepositoryTest.java @@ -1,13 +1,12 @@ package org.prgrms.nabimarketbe.user.repository; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.prgrms.nabimarketbe.domain.user.Role; import org.prgrms.nabimarketbe.domain.user.entity.User; -import org.prgrms.nabimarketbe.domain.user.repository.UserJpaRepo; +import org.prgrms.nabimarketbe.domain.user.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.util.Collections; @@ -17,14 +16,13 @@ import static org.junit.jupiter.api.Assertions.*; import static org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.*; -@RunWith(SpringRunner.class) @DataJpaTest @Transactional @AutoConfigureTestDatabase(replace = Replace.NONE) -public class UserJpaRepoTest { +public class UserRepositoryTest { @Autowired - private UserJpaRepo userJpaRepo; + private UserRepository userRepository; private String nickname = "xinxinzara"; private String password = "myPassWord"; @@ -33,13 +31,13 @@ public class UserJpaRepoTest { public void 회원저장_후_이메일로_회원검색() throws Exception { //given - userJpaRepo.save(User.builder() + userRepository.save(User.builder() .nickname(nickname) - .roles(Collections.singletonList("ROLE_USER")) + .role(Role.USER) .build()); //when - User user = userJpaRepo.findByNickname(nickname) + User user = userRepository.findByNickname(nickname) .orElseThrow(() -> new RuntimeException("해당 회원이 없습니다.")); //then @@ -51,12 +49,12 @@ public class UserJpaRepoTest { public void 카카오_가입자_조회() throws Exception { //given - userJpaRepo.save(User.builder() + userRepository.save(User.builder() .nickname(nickname) .provider("kakao") .build()); //when - Optional kakao = userJpaRepo.findByNicknameAndProvider(nickname, "kakao"); + Optional kakao = userRepository.findByNicknameAndProvider(nickname, "kakao"); //then assertThat(kakao).isNotNull(); diff --git a/src/test/java/org/prgrms/nabimarketbe/user/service/UserServiceTest.java b/src/test/java/org/prgrms/nabimarketbe/user/service/UserServiceTest.java index 459a79c2..0bb67ea9 100644 --- a/src/test/java/org/prgrms/nabimarketbe/user/service/UserServiceTest.java +++ b/src/test/java/org/prgrms/nabimarketbe/user/service/UserServiceTest.java @@ -2,20 +2,18 @@ import static org.junit.jupiter.api.Assertions.*; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.prgrms.nabimarketbe.domain.user.service.UserService; -import org.prgrms.nabimarketbe.domain.user.dto.sign.UserSignupRequestDto; +import org.prgrms.nabimarketbe.domain.user.dto.request.UserSignInRequestDTO; import org.prgrms.nabimarketbe.domain.user.service.SignService; -import org.prgrms.nabimarketbe.domain.user.dto.UserRequestDto; -import org.prgrms.nabimarketbe.domain.user.dto.UserResponseDto; +import org.prgrms.nabimarketbe.domain.user.dto.request.UserRequestDTO; +import org.prgrms.nabimarketbe.domain.user.dto.response.UserResponseDTO; import org.prgrms.nabimarketbe.domain.user.entity.User; -import org.prgrms.nabimarketbe.domain.user.repository.UserJpaRepo; +import org.prgrms.nabimarketbe.domain.user.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; @@ -23,7 +21,6 @@ import static org.assertj.core.api.Assertions.*; -@RunWith(SpringRunner.class) @SpringBootTest @Transactional @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @@ -32,14 +29,14 @@ public class UserServiceTest { @Autowired UserService userService; @Autowired - UserJpaRepo userJpaRepo; + UserRepository userRepository; @Autowired SignService signService; @Autowired PasswordEncoder passwordEncoder; - private UserSignupRequestDto getUserSignupRequestDto(int number) { - return UserSignupRequestDto.builder() + private UserSignInRequestDTO getUserSignupRequestDto(int number) { + return UserSignInRequestDTO.builder() .nickname("nickName" + number) .build(); } @@ -47,17 +44,17 @@ private UserSignupRequestDto getUserSignupRequestDto(int number) { @Test public void 회원등록() { // given - UserSignupRequestDto userA = + UserSignInRequestDTO userA = getUserSignupRequestDto(1); - User savedUser = userJpaRepo.save(userA.toEntity()); + User savedUser = userRepository.save(userA.toEntity()); // when - UserResponseDto userB = userService.findById(savedUser.getUserId()); - User byId = userJpaRepo.findById(savedUser.getUserId()) + UserResponseDTO userB = userService.findById(savedUser.getUserId()); + User byId = userRepository.findById(savedUser.getUserId()) .orElseThrow(() -> new RuntimeException("해당 회원이 없습니다.")); // then - assertThat(userA.getNickname()).isEqualTo(userB.getNickName()); + assertThat(userA.nickname()).isEqualTo(userB.getNickName()); assertThat( userService.findById(savedUser.getUserId()).getNickName()) .isEqualTo(byId.getNickname()); @@ -66,43 +63,43 @@ private UserSignupRequestDto getUserSignupRequestDto(int number) { @Test public void 회원등록_이메일검증() { // given - UserSignupRequestDto userA = + UserSignInRequestDTO userA = getUserSignupRequestDto(1); - User user = userJpaRepo.save(userA.toEntity()); + User user = userRepository.save(userA.toEntity()); // when - UserResponseDto dtoA = userService.findById(user.getUserId()); + UserResponseDTO dtoA = userService.findById(user.getUserId()); // then - assertThat(userA.getNickname()).isEqualTo(dtoA.getNickName()); + assertThat(userA.nickname()).isEqualTo(dtoA.getNickName()); } @Test public void 전체_회원조회() { // given - UserSignupRequestDto userA = + UserSignInRequestDTO userA = getUserSignupRequestDto(1); - UserSignupRequestDto userB = + UserSignInRequestDTO userB = getUserSignupRequestDto(2); // when - userJpaRepo.save(userA.toEntity()); - userJpaRepo.save(userB.toEntity()); + userRepository.save(userA.toEntity()); + userRepository.save(userB.toEntity()); // then - List allUser = userService.findAllUser(); + List allUser = userService.findAllUser(); assertThat(allUser.size()).isSameAs(3); } @Test public void 회원수정_닉네임() { // given - UserSignupRequestDto userA = + UserSignInRequestDTO userA = getUserSignupRequestDto(1); - User user = userJpaRepo.save(userA.toEntity()); + User user = userRepository.save(userA.toEntity()); // when - UserRequestDto updateUser = UserRequestDto.builder() + UserRequestDTO updateUser = UserRequestDTO.builder() .nickName("bbb") .build(); userService.update(user.getUserId(), updateUser); @@ -114,9 +111,9 @@ private UserSignupRequestDto getUserSignupRequestDto(int number) { @Test public void 회원삭제() { // given - UserSignupRequestDto userA = + UserSignInRequestDTO userA = getUserSignupRequestDto(1); - User user = userJpaRepo.save(userA.toEntity()); + User user = userRepository.save(userA.toEntity()); // when userService.delete(user.getUserId()); @@ -130,12 +127,12 @@ private UserSignupRequestDto getUserSignupRequestDto(int number) { //given LocalDateTime now = LocalDateTime .of(2021, 8, 5, 22, 31, 0); - UserSignupRequestDto userA = + UserSignInRequestDTO userA = getUserSignupRequestDto(1); //when - userJpaRepo.save(userA.toEntity()); - List users = userJpaRepo.findAll(); + userRepository.save(userA.toEntity()); + List users = userRepository.findAll(); //then User firstUser = users.get(1);