Skip to content

Commit

Permalink
fix:회의 내용 반영해서 고치기 (#24)
Browse files Browse the repository at this point in the history
* fix:소셜로그인 에러 확인

* fix:oAuth error

* fix:dockefile error

* fix:docker file error

* fix:dockerfile error

* fix:conflict

* feat:장소별 동행컨텐츠 조회

* fix:pr 리뷰 받고 수정

* fix:소셜 로그인, 쿼리 고쳐야할것 들 고치기 (230822회의)
  • Loading branch information
JjungminLee authored Aug 23, 2023
1 parent 0100c64 commit e7fd335
Show file tree
Hide file tree
Showing 13 changed files with 94 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,12 @@ public Member(Long memberId,String name, Age ageRange, String email, Role role,
this.birthDay = birthDay;
this.gender = gender;
}
@Builder
public Member(Long memberId,String profileImg) {

this.memberId=memberId;
this.profileImg=profileImg;
}

@Override
public ArrayList<GrantedAuthority> getAuthorities() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package com.onna.onnaback.domain.spark.adapter.in.web;


import com.onna.onnaback.domain.spark.adapter.in.web.response.SparkResponse;
import com.onna.onnaback.domain.spark.application.port.in.SparkUseCase;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/spark")
Expand All @@ -23,8 +24,8 @@ public class SparkController {
@GetMapping("/{placeId}")
public ResponseEntity<List<SparkResponse>> getSparkList(@PathVariable("placeId") Long placeId,
@RequestParam(value="page",required = false,defaultValue = "1")int page,
@RequestParam(value="size",required = false,defaultValue = "5")int size){

@RequestParam(value="size",required = false,defaultValue = "5")int size
){
return ResponseEntity.ok().body(
this.sparkUseCase.getSparkListByPlaceId(page,size,placeId)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ public class SparkResponse {

private long sparkId;

private long placeId;

private String title;

private SparkType sparkType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,11 @@ public Optional<Spark> getById(Long sparkId) {
public List<SparkResponse> getSparkListByPlaceId(Pageable pageable, Long placeId) {
Place place=placeRepository.findByPlaceId(placeId);
System.err.println(place.getName());
Specification<Spark> spec = (root, query, criteriaBuilder) -> null;
spec.and(equalPlace(place));
return sparkRepository.findAll(spec,pageable).getContent().stream().map(spark ->
return sparkRepository.findSparksByPlace(place,pageable).getContent().stream().map(spark ->
SparkResponse.builder()
.sparkId(spark.getSparkId())
.description(spark.getDescription())
.placeId(spark.getPlace().getPlaceId())
.detailAddress(spark.getPlace().getDetailAddress())
.lat(spark.getPlace().getLatitude())
.lng(spark.getPlace().getLongitude())
Expand Down Expand Up @@ -97,11 +96,11 @@ public String saveApply(Member host, Place place, HostDto hostDto) {
return "host success";
}

private Specification<Spark> equalPlace(Place place){
private Specification<Spark> equalPlace(Long placeId){
return new Specification<Spark>() {
@Override
public Predicate toPredicate(Root<Spark> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
return criteriaBuilder.equal(root.get("place"),place);
return criteriaBuilder.equal(root.get("placeId"),placeId);
}
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.lang.Nullable;

public interface SparkRepository extends JpaRepository<Spark, Long>, JpaSpecificationExecutor<Spark> {
Optional<Spark> findById(Long sparkId);

@Query("select s from Spark s where place = :place")
Page<Spark> findSparksByPlace(@Param("place") Place place,Pageable pageable);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import com.onna.onnaback.domain.spark.adapter.in.web.response.SparkResponse;
import com.onna.onnaback.domain.spark.application.port.out.SaveSparkPort;
import com.onna.onnaback.domain.spark.domain.Spark;
import com.onna.onnaback.global.oauth.service.CustomOAuth2UserService;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.onna.onnaback.domain.spark.application.port.in.SparkUseCase;
Expand All @@ -26,6 +28,7 @@
public class SparkService implements SparkUseCase {

private final MemberUseCase memberUseCase;

private final PlaceUseCase placeUseCase;
private final LoadSparkPort loadSparkPort;
private final SaveSparkPort saveSparkPort;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,6 @@ public Spark(String title, String description, SparkType type, LocalDateTime spa
this.place = place;
}



}
23 changes: 23 additions & 0 deletions src/main/java/com/onna/onnaback/global/config/CorsConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.onna.onnaback.global.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**",config);
return new CorsFilter(source);
}
}
3 changes: 2 additions & 1 deletion src/main/java/com/onna/onnaback/global/jwt/JwtService.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Optional;

Expand Down Expand Up @@ -72,7 +74,6 @@ public String createRefreshToken() {
.withExpiresAt(new Date(now.getTime() + refreshTokenExpirationPeriod))
.sign(Algorithm.HMAC512(secretKey));
}

/**
* AccessToken 헤더에 실어서 보내기
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,6 @@ private static OAuthAttributes ofKakao(String userNameAttributeName, Map<String,
*/

public Member toEntity(SocialType socialType, OAuth2UserInfo oauth2UserInfo) {
System.err.println(oauth2UserInfo.getEmail());


return Member.builder()
.name(oauth2UserInfo.getNickname())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,28 @@
import com.onna.onnaback.global.oauth.CustomOAuth2User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
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.nio.charset.StandardCharsets;

@Slf4j
@Component
@RequiredArgsConstructor
public class OAuth2LoginSuccessHandler implements AuthenticationSuccessHandler {
public class OAuth2LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

private final JwtService jwtService;
private final MemberRepository memberRepository;
@Value("${jwt.url}")
private String redirectUrl;

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Expand All @@ -31,21 +37,39 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo

// User의 Role이 GUEST일 경우 처음 요청한 회원이므로 회원가입 페이지로 리다이렉트
if(oAuth2User.getRole() == Role.GUEST) {
String accessToken = jwtService.createAccessToken(oAuth2User.getEmail());
response.addHeader(jwtService.getAccessHeader(), "Bearer " + accessToken);
response.sendRedirect("oauth2/sign-up"); // 프론트의 회원가입 추가 정보 입력 폼으로 리다이렉트

jwtService.sendAccessAndRefreshToken(response, accessToken, null);
// String accessToken = jwtService.createAccessToken(oAuth2User.getEmail());
// response.addHeader(jwtService.getAccessHeader(), "Bearer " + accessToken);
// response.sendRedirect("oauth2/sign-up"); // 프론트의 회원가입 추가 정보 입력 폼으로 리다이렉트
//
// jwtService.sendAccessAndRefreshToken(response, accessToken, null);
String targetUrl = UriComponentsBuilder.fromUriString(redirectUrl)
.queryParam("email", (String) oAuth2User.getAttribute("email"))
.build()
.encode(StandardCharsets.UTF_8)
.toUriString();
// 회원가입 페이지로 리다이렉트 시킨다.
getRedirectStrategy().sendRedirect(request, response, targetUrl);

} else {
loginSuccess(response, oAuth2User); // 로그인에 성공한 경우 access, refresh 토큰 생성
// loginSuccess(response, oAuth2User); // 로그인에 성공한 경우 access, refresh 토큰 생성
// accessToken을 쿼리스트링에 담는 url을 만들어준다.
String targetUrl = UriComponentsBuilder.fromUriString(redirectUrl)
.queryParam("accessToken", jwtService.createAccessToken(oAuth2User.getEmail()))
.build()
.encode(StandardCharsets.UTF_8)
.toUriString();
log.info("redirect 준비");
// 로그인 확인 페이지로 리다이렉트 시킨다.
getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
} catch (Exception e) {
throw e;
}

}



private void loginSuccess(HttpServletResponse response, CustomOAuth2User oAuth2User) throws IOException {
String accessToken = jwtService.createAccessToken(oAuth2User.getEmail());
String refreshToken = jwtService.createRefreshToken();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ else if(KAKAO.equals(registrationId)) {
* SocialType과 attributes에 들어있는 소셜 로그인의 식별값 id를 통해 회원을 찾아 반환하는 메소드
* 만약 찾은 회원이 있다면, 그대로 반환하고 없다면 saveUser()를 호출하여 회원을 저장한다.
*/
private Member getUser(OAuthAttributes attributes, SocialType socialType) {
public Member getUser(OAuthAttributes attributes, SocialType socialType) {
Member findUser = memberRepository.findBySocialTypeAndSocialId(socialType,
attributes.getOauth2UserInfo().getId()).orElse(null);

Expand Down
27 changes: 10 additions & 17 deletions src/main/java/com/onna/onnaback/global/security/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.onna.onnaback.domain.member.adapter.out.persistence.MemberRepository;
import com.onna.onnaback.global.config.CorsConfig;
import com.onna.onnaback.global.jwt.JwtService;
import com.onna.onnaback.global.jwt.LoginService;
import com.onna.onnaback.global.jwt.filter.CustomJsonUsernameAuthenticationFilter;
Expand Down Expand Up @@ -42,6 +43,8 @@ public class SecurityConfig {
private final OAuth2LoginFailureHandler oAuth2LoginFailureHandler;
private final CustomOAuth2UserService customOAuth2UserService;

private final CorsConfig corsConfig;

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
Expand All @@ -53,8 +56,6 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

.headers().frameOptions().disable()
.and()
.cors().configurationSource(corsConfigurationSource())
.and()
// 세션 사용하지 않으므로 STATELESS로 설정
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

Expand All @@ -64,22 +65,26 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
//== URL별 권한 관리 옵션 ==//
.authorizeRequests()
.antMatchers("/swagger-ui/**","/v3/api-docs", "/swagger-resources/**").permitAll()
.antMatchers("/login/*","/login/oauth2/code/*").permitAll()
.antMatchers("/login/*","/login/oauth2/code/*","/login/success/*").permitAll()
.antMatchers("/sign-up").permitAll() // 회원가입 접근 가능
.anyRequest().authenticated() // 위의 경로 이외에는 모두 인증된 사용자만 접근 가능
.and()

// [PART 3]
//== 소셜 로그인 설정 ==//
.oauth2Login()
.userInfoEndpoint()
.userService(customOAuth2UserService)// customUserService 설정
.and()
.successHandler(oAuth2LoginSuccessHandler) // 동의하고 계속하기를 눌렀을 때 Handler 설정
.failureHandler(oAuth2LoginFailureHandler) // 소셜 로그인 실패 시 핸들러 설정
.userInfoEndpoint().userService(customOAuth2UserService); // customUserService 설정
.failureHandler(oAuth2LoginFailureHandler); // 소셜 로그인 실패 시 핸들러 설정


// [PART4]
// 원래 스프링 시큐리티 필터 순서가 LogoutFilter 이후에 로그인 필터 동작
// 따라서, LogoutFilter 이후에 우리가 만든 필터 동작하도록 설정
// 순서 : LogoutFilter -> JwtAuthenticationProcessingFilter -> CustomJsonUsernamePasswordAuthenticationFilter
http.addFilter(corsConfig.corsFilter());
http.addFilterAfter(customJsonUsernamePasswordAuthenticationFilter(), LogoutFilter.class);
http.addFilterBefore(jwtAuthenticationProcessingFilter(), CustomJsonUsernameAuthenticationFilter.class);

Expand Down Expand Up @@ -135,19 +140,7 @@ public Filter jwtAuthenticationProcessingFilter() {
JwtAuthenticationProcessingFilter jwtAuthenticationFilter = new JwtAuthenticationProcessingFilter(jwtService, memberRepository);
return jwtAuthenticationFilter;
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();

configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.setAllowCredentials(true);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}


}

0 comments on commit e7fd335

Please sign in to comment.