diff --git a/server/build.gradle b/server/build.gradle index db79c5b3..26dda73c 100644 --- a/server/build.gradle +++ b/server/build.gradle @@ -54,6 +54,9 @@ dependencies { implementation 'io.jsonwebtoken:jjwt-api:0.11.5' runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' + //OAuth 2 의존성 추가 + implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' + //스프링 테스트를 위한 의존성추가 testImplementation 'org.springframework.security:spring-security-test' implementation 'junit:junit:4.13.1' diff --git a/server/src/main/java/com/rainbow/sof/domain/user/auth/filter/JwtAuthenticationFilter.java b/server/src/main/java/com/rainbow/sof/domain/user/auth/filter/JwtAuthenticationFilter.java index 43e40133..6a4e8046 100644 --- a/server/src/main/java/com/rainbow/sof/domain/user/auth/filter/JwtAuthenticationFilter.java +++ b/server/src/main/java/com/rainbow/sof/domain/user/auth/filter/JwtAuthenticationFilter.java @@ -1,6 +1,7 @@ package com.rainbow.sof.domain.user.auth.filter; import com.fasterxml.jackson.databind.ObjectMapper; +import com.rainbow.sof.domain.user.auth.jwt.DelegateTokenService; import com.rainbow.sof.domain.user.auth.jwt.JwtTokenizer; import com.rainbow.sof.domain.user.dto.singleDto.UserDto; import com.rainbow.sof.domain.user.entity.User; @@ -22,9 +23,12 @@ public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; private final JwtTokenizer tokenizer; - public JwtAuthenticationFilter(AuthenticationManager authenticationManager, JwtTokenizer tokenizer) { + public final DelegateTokenService delegateTokenService; + + public JwtAuthenticationFilter(AuthenticationManager authenticationManager, JwtTokenizer tokenizer, DelegateTokenService delegateTokenService) { this.authenticationManager = authenticationManager; this.tokenizer = tokenizer; + this.delegateTokenService = delegateTokenService; } @Override @@ -47,8 +51,8 @@ protected void successfulAuthentication(HttpServletRequest request, HttpServletR User user = (User)authResult.getPrincipal(); - String accessToken = delegateAccessToken(user); - String refreshToken = delegateRefreshToken(user); + String accessToken = delegateTokenService.delegateAccessToken(user); + String refreshToken = delegateTokenService.delegateRefreshToken(user); response.setHeader("Authorization", "Bearer " + accessToken); response.setHeader("Refresh",refreshToken); @@ -57,25 +61,26 @@ protected void successfulAuthentication(HttpServletRequest request, HttpServletR } - private String delegateAccessToken(User user){ - Map claims = new HashMap<>(); - claims.put("email",user.getEmail()); - - Date expiration = tokenizer.getTokenExpiration(tokenizer.getAccessTokenExpirationMinutes()); - String base64EncodedSecretKeyString = tokenizer.secretKeyEncodeBase64(tokenizer.getSecretKeySting()); - String subject=user.getEmail(); - - return tokenizer.generateAccessToken(claims,subject,expiration,base64EncodedSecretKeyString); - - } - - private String delegateRefreshToken(User user){ - - Date expiration = tokenizer.getTokenExpiration(tokenizer.getAccessTokenExpirationMinutes()); - String base64EncodedSecretKeyString = tokenizer.secretKeyEncodeBase64(tokenizer.getSecretKeySting()); - String subject=user.getEmail(); - - return tokenizer.generateRefreshToken(subject,expiration,base64EncodedSecretKeyString); - - } + //TODO: 이전 토큰 생성 메서드 +// private String delegateAccessToken(User user){ +// Map claims = new HashMap<>(); +// claims.put("email",user.getEmail()); +// +// Date expiration = tokenizer.getTokenExpiration(tokenizer.getAccessTokenExpirationMinutes()); +// String base64EncodedSecretKeyString = tokenizer.secretKeyEncodeBase64(tokenizer.getSecretKeySting()); +// String subject=user.getEmail(); +// +// return tokenizer.generateAccessToken(claims,subject,expiration,base64EncodedSecretKeyString); +// +// } +// +// private String delegateRefreshToken(User user){ +// +// Date expiration = tokenizer.getTokenExpiration(tokenizer.getAccessTokenExpirationMinutes()); +// String base64EncodedSecretKeyString = tokenizer.secretKeyEncodeBase64(tokenizer.getSecretKeySting()); +// String subject=user.getEmail(); +// +// return tokenizer.generateRefreshToken(subject,expiration,base64EncodedSecretKeyString); +// +// } } diff --git a/server/src/main/java/com/rainbow/sof/domain/user/auth/handler/oauthHandler/OAuth2FailureHandler.java b/server/src/main/java/com/rainbow/sof/domain/user/auth/handler/oauthHandler/OAuth2FailureHandler.java new file mode 100644 index 00000000..5670b51b --- /dev/null +++ b/server/src/main/java/com/rainbow/sof/domain/user/auth/handler/oauthHandler/OAuth2FailureHandler.java @@ -0,0 +1,16 @@ +//package com.rainbow.sof.domain.user.auth.handler.oauthHandler; +// +//import org.springframework.security.core.AuthenticationException; +//import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; +// +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import java.io.IOException; +// +//public class OAuth2FailureHandler extends SimpleUrlAuthenticationFailureHandler { +// @Override +// public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { +// chain.doFilter(httpRequest,response); +// } +//} diff --git a/server/src/main/java/com/rainbow/sof/domain/user/auth/handler/oauthHandler/OAuth2SuccessHandler.java b/server/src/main/java/com/rainbow/sof/domain/user/auth/handler/oauthHandler/OAuth2SuccessHandler.java new file mode 100644 index 00000000..ac620469 --- /dev/null +++ b/server/src/main/java/com/rainbow/sof/domain/user/auth/handler/oauthHandler/OAuth2SuccessHandler.java @@ -0,0 +1,94 @@ +package com.rainbow.sof.domain.user.auth.handler.oauthHandler; + +import com.rainbow.sof.domain.user.auth.jwt.DelegateTokenService; +import com.rainbow.sof.domain.user.auth.jwt.JwtTokenizer; +import com.rainbow.sof.domain.user.entity.User; +import com.rainbow.sof.domain.user.service.UserService; +import com.rainbow.sof.global.error.BusinessLogicException; +import com.rainbow.sof.global.error.ExceptionCode; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.core.user.OAuth2User; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; +import org.springframework.util.MultiValueMap; +import org.springframework.web.util.UriComponentsBuilder; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URI; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import static com.rainbow.sof.domain.user.util.CustomEnumUri.*; + +@Slf4j +public class OAuth2SuccessHandler extends SimpleUrlAuthenticationSuccessHandler { + private final DelegateTokenService delegateTokenService; + private final UserService userService; + + public OAuth2SuccessHandler(DelegateTokenService delegateTokenService, UserService userService) { + this.delegateTokenService = delegateTokenService; + this.userService = userService; + } + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { + OAuth2User UserData = (OAuth2User)authentication.getPrincipal(); + String email = String.valueOf(UserData.getAttributes().get("email")); + String name = String.valueOf(UserData.getAttributes().get("name")); + + User createUser = User.builder().email(email) + .name(name) + .password("Q1234123452234522").build(); + User oAuth2User= saveUser(createUser); + log.info("onAuthenticationSuccess: {} ", oAuth2User.getName()); + log.info("onAuthenticationSuccess: {}" ,oAuth2User.getEmail()); + redirect(request, response,oAuth2User); + + } + + private User saveUser(User oAuth2User) { + try { + return userService.createUser(oAuth2User); + }catch (BusinessLogicException e){ + + return e.getExceptionCode().equals(ExceptionCode.USER_EXISTS) ? + userService.findByUserFromEmail(oAuth2User.getEmail()) : + null; + } + } + + private void redirect(HttpServletRequest request, HttpServletResponse response, User user) throws IOException { + String accessToken = delegateTokenService.delegateAccessToken(user); + String refreshToken = delegateTokenService.delegateRefreshToken(user); + + + String uri = createURI().toString(); + response.setHeader("Authorization", "Bearer " + accessToken); + response.setHeader("Refresh",refreshToken); + + getRedirectStrategy().sendRedirect(request, response, "/mypage"); + String s = getRedirectStrategy().toString(); + } + + //TODO: 클라이언트 주소로 변경 필요 + private URI createURI() { + return UriComponentsBuilder + .newInstance() + .scheme("http") + .host("localhost") +// .port(80) + .path("/receive-token.html") + .build() + .toUri(); + } + + +} +// Map oAuth2UserData = new HashMap<>(); +// oAuth2UserData.put("email", String.valueOf(oAuth2User.getAttributes().get("email"))); +// oAuth2UserData.put("name", String.valueOf(oAuth2User.getAttributes().get("name"))); +// User createUser= saveUser(oAuth2UserData); \ No newline at end of file diff --git a/server/src/main/java/com/rainbow/sof/domain/user/auth/jwt/DelegateTokenService.java b/server/src/main/java/com/rainbow/sof/domain/user/auth/jwt/DelegateTokenService.java new file mode 100644 index 00000000..922924dc --- /dev/null +++ b/server/src/main/java/com/rainbow/sof/domain/user/auth/jwt/DelegateTokenService.java @@ -0,0 +1,40 @@ +package com.rainbow.sof.domain.user.auth.jwt; + +import com.rainbow.sof.domain.user.entity.User; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + + +@Component +public class DelegateTokenService { + private final JwtTokenizer tokenizer; + + public DelegateTokenService(JwtTokenizer tokenizer) { + this.tokenizer = tokenizer; + } + + public String delegateAccessToken(User user){ + Map claims = new HashMap<>(); + claims.put("email",user.getEmail()); + + Date expiration = tokenizer.getTokenExpiration(tokenizer.getAccessTokenExpirationMinutes()); + String base64EncodedSecretKeyString = tokenizer.secretKeyEncodeBase64(tokenizer.getSecretKeySting()); + String subject=user.getEmail(); + + return tokenizer.generateAccessToken(claims,subject,expiration,base64EncodedSecretKeyString); + + } + + public String delegateRefreshToken(User user){ + + Date expiration = tokenizer.getTokenExpiration(tokenizer.getAccessTokenExpirationMinutes()); + String base64EncodedSecretKeyString = tokenizer.secretKeyEncodeBase64(tokenizer.getSecretKeySting()); + String subject=user.getEmail(); + + return tokenizer.generateRefreshToken(subject,expiration,base64EncodedSecretKeyString); + + } +} diff --git a/server/src/main/java/com/rainbow/sof/domain/user/auth/jwt/JwtTokenizer.java b/server/src/main/java/com/rainbow/sof/domain/user/auth/jwt/JwtTokenizer.java index 5c3d4156..904a4d42 100644 --- a/server/src/main/java/com/rainbow/sof/domain/user/auth/jwt/JwtTokenizer.java +++ b/server/src/main/java/com/rainbow/sof/domain/user/auth/jwt/JwtTokenizer.java @@ -8,6 +8,7 @@ import io.jsonwebtoken.security.Keys; import lombok.Getter; import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.nio.charset.StandardCharsets; @@ -18,19 +19,21 @@ public class JwtTokenizer { @Getter + @Value("${User.mail.admin}") private static String ADMIN_SUBJECT = "ADMIN@ADMIN.com"; @Getter + @Value("${User.mail.disable}") private static String USER_DISABLE_MAIL="disable@disable.com"; @Getter - @Value("thisIsTestScretKeythisIsTestScretKeythisIsTestScretKeythisIsTestScretKey") + @Value("${jwt.key.secret}") private String secretKeySting; @Getter - @Value("60") + @Value("${jwt.access-token-expiration-minutes}") private int accessTokenExpirationMinutes; @Getter - @Value("300") + @Value("${jwt.refresh-token-expiration-minutes}") private int refreshTokenExpirationMinutes; //시크릿키로 이용할 무작위 문자열을 바이트배열로 변환 diff --git a/server/src/main/java/com/rainbow/sof/domain/user/config/CustomFilterConfigurer.java b/server/src/main/java/com/rainbow/sof/domain/user/config/CustomFilterConfigurer.java index bf3c54e5..405fd1f6 100644 --- a/server/src/main/java/com/rainbow/sof/domain/user/config/CustomFilterConfigurer.java +++ b/server/src/main/java/com/rainbow/sof/domain/user/config/CustomFilterConfigurer.java @@ -4,25 +4,35 @@ import com.rainbow.sof.domain.user.auth.filter.JwtVerificationFilterV2; import com.rainbow.sof.domain.user.auth.handler.loginhandle.UserAuthenticationFailureHandler; import com.rainbow.sof.domain.user.auth.handler.loginhandle.UserAuthenticationSuccessHandler; +import com.rainbow.sof.domain.user.auth.handler.oauthHandler.OAuth2SuccessHandler; +import com.rainbow.sof.domain.user.auth.jwt.DelegateTokenService; import com.rainbow.sof.domain.user.auth.jwt.JwtTokenizer; +import com.rainbow.sof.domain.user.service.UserService; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter; +import org.springframework.stereotype.Component; +@Component public class CustomFilterConfigurer extends AbstractHttpConfigurer { private final JwtTokenizer jwtTokenizer; + public final DelegateTokenService delegateTokenService; - public CustomFilterConfigurer(JwtTokenizer jwtTokenizer) { + + public CustomFilterConfigurer(JwtTokenizer jwtTokenizer, DelegateTokenService delegateTokenService) { this.jwtTokenizer = jwtTokenizer; + this.delegateTokenService = delegateTokenService; + } @Override public void configure(HttpSecurity builder) throws Exception { AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class); - JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager,jwtTokenizer); + JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager,jwtTokenizer,delegateTokenService); jwtAuthenticationFilter.setFilterProcessesUrl("/api/v1/login"); jwtAuthenticationFilter.setAuthenticationSuccessHandler(new UserAuthenticationSuccessHandler()); @@ -30,7 +40,11 @@ public void configure(HttpSecurity builder) throws Exception { JwtVerificationFilterV2 jwtVerificationFilterV2 = new JwtVerificationFilterV2(jwtTokenizer); - builder.addFilter(jwtAuthenticationFilter) - .addFilterAfter(jwtVerificationFilterV2,JwtAuthenticationFilter.class); + builder.addFilterAfter(jwtVerificationFilterV2, OAuth2LoginAuthenticationFilter.class) + .addFilterBefore(jwtAuthenticationFilter,JwtVerificationFilterV2.class); } + +//.addFilter(jwtAuthenticationFilter) +// .addFilterAfter(jwtVerificationFilterV2,JwtAuthenticationFilter.class); + } diff --git a/server/src/main/java/com/rainbow/sof/domain/user/config/SecurityConfiguration.java b/server/src/main/java/com/rainbow/sof/domain/user/config/SecurityConfiguration.java index 9d69382a..3cf31d04 100644 --- a/server/src/main/java/com/rainbow/sof/domain/user/config/SecurityConfiguration.java +++ b/server/src/main/java/com/rainbow/sof/domain/user/config/SecurityConfiguration.java @@ -1,15 +1,22 @@ package com.rainbow.sof.domain.user.config; import com.rainbow.sof.domain.user.auth.handler.authError.UserAuthenticationEntryPoint; +import com.rainbow.sof.domain.user.auth.handler.oauthHandler.OAuth2SuccessHandler; +import com.rainbow.sof.domain.user.auth.jwt.DelegateTokenService; import com.rainbow.sof.domain.user.auth.jwt.JwtTokenizer; import com.rainbow.sof.domain.user.config.CustomFilterConfigurer; +import com.rainbow.sof.domain.user.service.UserService; +import lombok.SneakyThrows; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.stereotype.Component; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @@ -23,15 +30,20 @@ @Configuration public class SecurityConfiguration { private final JwtTokenizer jwtTokenizer; + private final DelegateTokenService delegateTokenService; + private final UserService userService; + private final static String USER_DETAIL_URL="/api/v1/users"; - public SecurityConfiguration(JwtTokenizer jwtTokenizer) { + public SecurityConfiguration(JwtTokenizer jwtTokenizer, DelegateTokenService delegateTokenService, UserService userService) { this.jwtTokenizer = jwtTokenizer; + this.delegateTokenService = delegateTokenService; + this.userService = userService; } - @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ + http .headers().frameOptions().sameOrigin() .and() @@ -44,9 +56,14 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ .exceptionHandling() .authenticationEntryPoint(new UserAuthenticationEntryPoint()) .and() - .apply(customFilterConfigurer()) + .oauth2Login(oauth2 -> oauth2 + .loginPage("/api/v1/oath/login") + .successHandler(new OAuth2SuccessHandler(delegateTokenService,userService)) + ) + .apply(customFilterConfigurers()) .and() .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry + .antMatchers("/api/v1/oath/login").permitAll() .antMatchers(HttpMethod.PATCH,"/api/v1/questions/**").hasRole("USER") .antMatchers(HttpMethod.POST,"/api/v1/questions/**").hasRole("USER") .antMatchers(HttpMethod.DELETE,"/api/v1/questions/**").hasRole("USER") @@ -57,14 +74,16 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ } @Bean - public CustomFilterConfigurer customFilterConfigurer(){ - return new CustomFilterConfigurer(jwtTokenizer); - } - @Bean - public PasswordEncoder passwordEncoder(){ - return PasswordEncoderFactories.createDelegatingPasswordEncoder(); + public CustomFilterConfigurer customFilterConfigurers(){ + return new CustomFilterConfigurer(jwtTokenizer, delegateTokenService); } +// @Bean +// public PasswordEncoder passwordEncoder(){ +// return PasswordEncoderFactories.createDelegatingPasswordEncoder(); +// } + + @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); diff --git a/server/src/main/java/com/rainbow/sof/domain/user/controller/UserController.java b/server/src/main/java/com/rainbow/sof/domain/user/controller/UserController.java index 98e7c7ad..d239cded 100644 --- a/server/src/main/java/com/rainbow/sof/domain/user/controller/UserController.java +++ b/server/src/main/java/com/rainbow/sof/domain/user/controller/UserController.java @@ -37,18 +37,10 @@ public ResponseEntity postSignup(@Valid @RequestBody UserDto.SignUpPost signU User user = mapper.userSignupPostToUser(signUpPost); User createUser=service.createUser(user); URI location = UriCreator.createUri(USER_DEFAULT_URL.getUri(), createUser.getUserId()); - return ResponseEntity.created(location).build(); + return ResponseEntity.created(location).body(mapper.userToUserUserDtoResponse(user)); } -// @PostMapping("/login") -// public ResponseEntity postLogin(@AuthenticationName String email){ -// User user = service.findByUserFromEmail(email); -// URI location = UriCreator.createUri(USER_DEFAULT_URL,user.getUserId()); -// response.setHeader("Location", String.valueOf(location)); -// return ResponseEntity.ok().body(user.getUserId()); -// } - // @PostMapping("/logout") // public ResponseEntity postLogin(){ // diff --git a/server/src/main/java/com/rainbow/sof/domain/user/dto/singleDto/UserDto.java b/server/src/main/java/com/rainbow/sof/domain/user/dto/singleDto/UserDto.java index d7773eb0..2e91df6c 100644 --- a/server/src/main/java/com/rainbow/sof/domain/user/dto/singleDto/UserDto.java +++ b/server/src/main/java/com/rainbow/sof/domain/user/dto/singleDto/UserDto.java @@ -21,9 +21,9 @@ public static class SignUpPost{ private String name; @NotBlank - @Size(min = 8,message = "비밀번호는 최수 8자리 이상이어야합니다.") - @Pattern(regexp="^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$", - message = "비밀번호는 하나이상의 숫자와 문자가 조합 되어야합니다.") + @Size(min = 8,message = "비밀번호는 최소 8자리 이상이어야합니다.") +// @Pattern(regexp="^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$", +// message = "비밀번호는 하나이상의 숫자와 문자가 조합 되어야합니다.") private String password; @NotBlank @@ -58,7 +58,7 @@ public Patch(String name) { @Getter @Builder public static class Response{ - private long memberId; + private long userId; private String name; private String email; private LocalDateTime createdAt; diff --git a/server/src/main/java/com/rainbow/sof/domain/user/entity/User.java b/server/src/main/java/com/rainbow/sof/domain/user/entity/User.java index d692c7a1..10da457a 100644 --- a/server/src/main/java/com/rainbow/sof/domain/user/entity/User.java +++ b/server/src/main/java/com/rainbow/sof/domain/user/entity/User.java @@ -41,7 +41,7 @@ public User(long userId, String password, String email, String name, @Column(nullable = false) private String password; @Email - @Column(nullable = false, updatable = false) + @Column(nullable = false) private String email; @Column(nullable = false) diff --git a/server/src/main/java/com/rainbow/sof/domain/user/mapper/UserMapper.java b/server/src/main/java/com/rainbow/sof/domain/user/mapper/UserMapper.java index 5492aef8..95ca7be6 100644 --- a/server/src/main/java/com/rainbow/sof/domain/user/mapper/UserMapper.java +++ b/server/src/main/java/com/rainbow/sof/domain/user/mapper/UserMapper.java @@ -14,6 +14,7 @@ @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface UserMapper { User userSignupPostToUser(UserDto.SignUpPost signUpPost); + UserDto.Response userToUserUserDtoResponse(User user); User userLoginPostTouser(UserDto.CreationLoginDto creationLoginDto); UserDto.LoginResponse userToLoginDto(User user); @@ -32,7 +33,7 @@ default MyPageResponseDto userToMyPageDto(User user){ List AnsweList = user.getAnswerList().stream() .map(answer ->AnswerDto.MyPageAnswerResponse.builder() .answerId(answer.getAnswerId()) - .modifiedAt(answer.getModifiedAt()) + .createdAt(answer.getModifiedAt()) .modifiedAt(answer.getModifiedAt()) .content(answer.getContent()) .build()) @@ -42,6 +43,7 @@ default MyPageResponseDto userToMyPageDto(User user){ .name(user.getName()) .createdAt(user.getCreatedAt()) .questionList(questionList) + .AnswerList(AnsweList) .build(); } } diff --git a/server/src/main/java/com/rainbow/sof/domain/user/service/PasswordEncoderBean.java b/server/src/main/java/com/rainbow/sof/domain/user/service/PasswordEncoderBean.java new file mode 100644 index 00000000..042bb42d --- /dev/null +++ b/server/src/main/java/com/rainbow/sof/domain/user/service/PasswordEncoderBean.java @@ -0,0 +1,15 @@ +package com.rainbow.sof.domain.user.service; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; + +@Component +public class PasswordEncoderBean { + @Bean + public PasswordEncoder passwordEncoder() { + + return PasswordEncoderFactories.createDelegatingPasswordEncoder(); + } +} diff --git a/server/src/main/java/com/rainbow/sof/domain/user/service/UserService.java b/server/src/main/java/com/rainbow/sof/domain/user/service/UserService.java index 43146905..e38ae7bb 100644 --- a/server/src/main/java/com/rainbow/sof/domain/user/service/UserService.java +++ b/server/src/main/java/com/rainbow/sof/domain/user/service/UserService.java @@ -12,6 +12,7 @@ import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; +import java.util.Map; import java.util.Optional; @Service @@ -28,6 +29,21 @@ public User createUser(User user){ return saveUser(user); } + public User OauhtCreateUser(User user){ + verifyExistsEmail(user.getEmail()); + String passwordEncode = passwordEncoder.encode(user.getPassword()); + user.updatePassword(passwordEncode); + return saveUser(user); + } + +// public User createUser(Map userdata){ +// verifyExistsEmail(email); +// User user = findByUserFromEmail(email); +// String passwordEncode = passwordEncoder.encode(user.getPassword()); +// user.updatePassword(passwordEncode); +// return saveUser(user); +// } + public User updateUser(String email, long id, UserDto.Patch patchUser){ verifyExistsEmail(patchUser.getName()); User updateUser = checkToFindByUserFromEmail(email,id); diff --git a/server/src/main/java/com/rainbow/sof/domain/user/util/CustomEnumUri.java b/server/src/main/java/com/rainbow/sof/domain/user/util/CustomEnumUri.java index a891ff79..87783fc8 100644 --- a/server/src/main/java/com/rainbow/sof/domain/user/util/CustomEnumUri.java +++ b/server/src/main/java/com/rainbow/sof/domain/user/util/CustomEnumUri.java @@ -4,7 +4,7 @@ public enum CustomEnumUri { - + DEFAULT_URL("/api/v1"), USER_DEFAULT_URL("/api/v1/users"), DELETE_ACTION_URL("/signup"), QUESTION_DEFAULT_URL("/api/v1/questions"); diff --git a/server/src/main/resources/application.yml b/server/src/main/resources/application.yml index 38d82643..1af3263f 100644 --- a/server/src/main/resources/application.yml +++ b/server/src/main/resources/application.yml @@ -12,7 +12,16 @@ spring: properties: hibernate: format_sql: true - + security: + oauth2: + client: + registration: + google: + clientId: ${GOOGLE_CLIENTID} + clientSecret: ${GOOGLE_CLIENTSECRET} + scope: + - email + - profile logging: logback: rollingpolicy: @@ -26,4 +35,19 @@ springdoc: default-produces-media-type: application/json;charset=UTF-8 swagger-ui: url: /docs/open-api-3.0.1.json - path: /docs/swagger \ No newline at end of file + path: /docs/swagger + + + +jwt: + key: + secret: ${JWT_SECRET_KEY} + access-token-expiration-minutes: ${ACCESS_EXPIRATION_MINUTES} + refresh-token-expiration-minutes: ${REFRESH_EXPIRATION_MINUTES} + +User: + mail: + admin: ${ADMIN_EMAIL} + disable: ${DISABLE_USER} +##${ADMIN_EMAIL} +##${DISABLE_USER} \ No newline at end of file diff --git a/server/src/test/java/com/rainbow/sof/domain/answer/AnswerControllerTest.java b/server/src/test/java/com/rainbow/sof/domain/answer/AnswerControllerTest.java index 262efd5c..d89c5bc6 100644 --- a/server/src/test/java/com/rainbow/sof/domain/answer/AnswerControllerTest.java +++ b/server/src/test/java/com/rainbow/sof/domain/answer/AnswerControllerTest.java @@ -17,6 +17,7 @@ import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.HttpHeaders; @@ -37,8 +38,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@Import({SecurityConfiguration.class, JwtTokenizer.class}) -@WebMvcTest(AnswerController.class) +//@Import({SecurityConfiguration.class, JwtTokenizer.class}) +//@WebMvcTest(AnswerController.class) +@SpringBootTest @AutoConfigureMockMvc @AutoConfigureRestDocs @TestInstance(TestInstance.Lifecycle.PER_CLASS) diff --git a/server/src/test/java/com/rainbow/sof/domain/question/QuestionControllerTest.java b/server/src/test/java/com/rainbow/sof/domain/question/QuestionControllerTest.java index b817b847..a51f51e0 100644 --- a/server/src/test/java/com/rainbow/sof/domain/question/QuestionControllerTest.java +++ b/server/src/test/java/com/rainbow/sof/domain/question/QuestionControllerTest.java @@ -20,6 +20,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; @@ -49,8 +50,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@Import({SecurityConfiguration.class, JwtTokenizer.class}) -@WebMvcTest(QuestionController.class) +//@Import({SecurityConfiguration.class, JwtTokenizer.class}) +//@WebMvcTest(QuestionController.class) +@SpringBootTest @AutoConfigureMockMvc @AutoConfigureRestDocs @TestInstance(TestInstance.Lifecycle.PER_CLASS) diff --git a/server/src/test/java/com/rainbow/sof/domain/question/QuestionVoteControllerTest.java b/server/src/test/java/com/rainbow/sof/domain/question/QuestionVoteControllerTest.java index 605f8d8f..8874fe45 100644 --- a/server/src/test/java/com/rainbow/sof/domain/question/QuestionVoteControllerTest.java +++ b/server/src/test/java/com/rainbow/sof/domain/question/QuestionVoteControllerTest.java @@ -18,6 +18,7 @@ import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.HttpHeaders; @@ -38,8 +39,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@Import({SecurityConfiguration.class, JwtTokenizer.class}) -@WebMvcTest(QuestionVoteController.class) +//@Import({SecurityConfiguration.class, JwtTokenizer.class}) +//@WebMvcTest(QuestionVoteController.class) +@SpringBootTest @AutoConfigureMockMvc @AutoConfigureRestDocs @TestInstance(TestInstance.Lifecycle.PER_CLASS)