Skip to content

Commit

Permalink
fix: ci 에러 수정 (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
choidongkuen committed Jan 6, 2024
1 parent e8e27c8 commit b68ca54
Show file tree
Hide file tree
Showing 11 changed files with 115 additions and 76 deletions.
27 changes: 9 additions & 18 deletions src/main/java/net/teumteum/core/security/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@


import lombok.RequiredArgsConstructor;
import net.teumteum.core.property.JwtProperty;
import net.teumteum.core.security.filter.JwtAuthenticationFilter;
import net.teumteum.core.security.service.AuthService;
import net.teumteum.core.security.service.JwtService;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -22,25 +19,24 @@
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;

@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

private final JwtService jwtService;
private final AuthService authService;
private final JwtProperty jwtProperty;
private final JwtAuthenticationFilter jwtAuthenticationFilter;

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector);
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request
-> request.requestMatchers("/**").permitAll()
.requestMatchers(PathRequest.toH2Console()).permitAll())
-> request.requestMatchers("/users").permitAll()
.requestMatchers(PathRequest.toH2Console()).permitAll()
.anyRequest().authenticated())
.httpBasic(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.sessionManagement(sessionManagement
-> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
Expand All @@ -49,21 +45,16 @@ SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrosp
return http.build();
}

/* Cors 관련 설정 */
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("*"); // Access-Control-Allow-Origin
configuration.addAllowedMethod("*"); // Access-Control-Allow-Methods
configuration.addAllowedHeader("*"); // Access-Control-Allow-Headers
configuration.addAllowedOrigin("*");
configuration.addAllowedMethod("*");
configuration.addAllowedHeader("*");
configuration.setMaxAge(3600L);

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

private JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter(jwtService, authService, jwtProperty);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@
import net.teumteum.user.domain.User;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@RequiredArgsConstructor
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private final AuthService authService;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
package net.teumteum.core.security.service;

import lombok.RequiredArgsConstructor;
import net.teumteum.core.security.UserAuthentication;
import net.teumteum.user.domain.UserConnector;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
@Service
@RequiredArgsConstructor
public class SecurityService {
private static UserAuthentication getUserAuthentication() {
return (UserAuthentication) SecurityContextHolder.getContext().getAuthentication();
}

public void clearSecurityContext() {
private final UserConnector userConnector;

public static void clearSecurityContext() {
SecurityContextHolder.clearContext();
}

private UserAuthentication getUserAuthentication() {
return (UserAuthentication) SecurityContextHolder.getContext().getAuthentication();
}


public Long getCurrentUserId() {
UserAuthentication userAuthentication = getUserAuthentication();
return userAuthentication == null ? 10000000000L : userAuthentication.getId();
return getUserAuthentication() == null ? userConnector.findAllUser().get(0).getId() : getUserAuthentication().getId();
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import net.teumteum.user.domain.response.UserGetResponse;
import net.teumteum.user.domain.response.UsersGetByIdResponse;
import net.teumteum.user.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

Expand All @@ -17,6 +18,7 @@
@RequestMapping("/users")
public class UserController {

private final ApplicationContext applicationContext;
private final UserService userService;
private final SecurityService securityService;

Expand Down Expand Up @@ -56,7 +58,6 @@ public ErrorResponse handleIllegalArgumentException(IllegalArgumentException ill
}

private Long getCurrentUserId() {
Long currentUserId = securityService.getCurrentUserId();
return currentUserId;
return securityService.getCurrentUserId();
}
}
3 changes: 3 additions & 0 deletions src/main/java/net/teumteum/user/domain/UserConnector.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package net.teumteum.user.domain;

import java.util.List;
import java.util.Optional;

public interface UserConnector {

Optional<User> findUserById(Long id);

List<User> findAllUser();
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package net.teumteum.user.service;

import java.util.Optional;
import lombok.RequiredArgsConstructor;
import net.teumteum.user.domain.User;
import net.teumteum.user.domain.UserConnector;
import net.teumteum.user.domain.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
Expand All @@ -20,4 +22,8 @@ public Optional<User> findUserById(Long id) {
return userRepository.findById(id);
}

@Override
public List<User> findAllUser() {
return userRepository.findAll();
}
}
71 changes: 38 additions & 33 deletions src/test/java/net/teumteum/integration/Api.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,79 +7,84 @@
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;

@WithMockUser(username = "user", roles = {"USER"})
@TestComponent
class Api {

private final WebTestClient webTestClient;


public Api(ApplicationContext applicationContext) {
var controllers = applicationContext.getBeansWithAnnotation(Controller.class).values();
webTestClient = WebTestClient.bindToController(controllers.toArray())
.argumentResolvers(resolvers -> resolvers.addCustomResolver(new PageableHandlerMethodArgumentResolver()))
.build();
.argumentResolvers(resolvers -> resolvers.addCustomResolver(new PageableHandlerMethodArgumentResolver()))
.build();
}


ResponseSpec getUser(String token, Long userId) {
return webTestClient.get()
.uri("/users/" + userId)
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
return webTestClient
.get()
.uri("/users/" + userId)
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
}

ResponseSpec getUsersById(String token, String userIds) {
return webTestClient.get()
.uri("/users?id=" + userIds)
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
.uri("/users?id=" + userIds)
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
}

ResponseSpec updateUser(String token, UserUpdateRequest userUpdateRequest) {
return webTestClient.put()
.uri("/users")
.header(HttpHeaders.AUTHORIZATION, token)
.bodyValue(userUpdateRequest)
.exchange();
return webTestClient
.put()
.uri("/users")
.header(HttpHeaders.AUTHORIZATION, token)
.bodyValue(userUpdateRequest)
.exchange();
}

ResponseSpec addFriends(String token, Long friendId) {
return webTestClient.post()
.uri("/users/" + friendId + "/friends")
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
.uri("/users/" + friendId + "/friends")
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
}

ResponseSpec getOpenMeetings(String token, Long cursorId, int size) {
return webTestClient.get()
.uri("/meetings" +
"?cursorId=" + cursorId +
"&size=" + size)
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
.uri("/meetings" +
"?cursorId=" + cursorId +
"&size=" + size)
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
}

ResponseSpec getMeetingById(String token, Long meetingId) {
return webTestClient.get()
.uri("/meetings/" + meetingId)
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
.uri("/meetings/" + meetingId)
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
}

ResponseSpec getMeetingsByTopic(String token, Pageable pageable, boolean isOpen, Topic topic) {
String sort = pageable.getSort().toString().replace(": ", ",");
String uri = "/meetings?sort=" + sort +
"&page=" + pageable.getOffset() +
"&size=" + pageable.getPageSize() +
"&isOpen=" + isOpen +
"&topic=" + topic;
"&page=" + pageable.getOffset() +
"&size=" + pageable.getPageSize() +
"&isOpen=" + isOpen +
"&topic=" + topic;

return webTestClient.get()
.uri(uri)
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
.uri(uri)
.header(HttpHeaders.AUTHORIZATION, token)
.exchange();
}

}
12 changes: 9 additions & 3 deletions src/test/java/net/teumteum/integration/IntegrationTest.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package net.teumteum.integration;

import net.teumteum.Application;
import net.teumteum.core.context.LoginContext;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.ContextConfiguration;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = {Application.class, Api.class, Repository.class, TestLoginContext.class})
@AutoConfigureWebTestClient(timeout = "10000")
@ContextConfiguration(classes = {Application.class, Api.class, Repository.class, SecurityContextSetting.class})
abstract public class IntegrationTest {

@Autowired
Expand All @@ -20,11 +21,16 @@ abstract public class IntegrationTest {
protected Repository repository;

@Autowired
protected LoginContext loginContext;
protected SecurityContextSetting securityContextSetting;

@AfterEach
@BeforeEach
void clearAll() {
repository.clear();
}

@BeforeEach
void setSecurityContextSetting() {
securityContextSetting.set();
}
}
8 changes: 7 additions & 1 deletion src/test/java/net/teumteum/integration/Repository.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.teumteum.integration;

import jakarta.persistence.EntityManager;
import lombok.RequiredArgsConstructor;
import net.teumteum.core.config.AppConfig;
import net.teumteum.meeting.domain.Meeting;
Expand All @@ -22,12 +23,18 @@ class Repository {

private final UserRepository userRepository;
private final MeetingRepository meetingRepository;
private final EntityManager entityManager;

User saveAndGetUser() {
var user = UserFixture.getNullIdUser();
return userRepository.saveAndFlush(user);
}

List<User> getAllUser() {
return userRepository.findAll();
}


Meeting saveAndGetOpenMeeting() {
var meeting = MeetingFixture.getOpenMeeting();
return meetingRepository.saveAndFlush(meeting);
Expand Down Expand Up @@ -101,5 +108,4 @@ void clear() {
userRepository.deleteAll();
meetingRepository.deleteAll();
}

}
18 changes: 18 additions & 0 deletions src/test/java/net/teumteum/integration/SecurityContextSetting.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package net.teumteum.integration;

import net.teumteum.core.security.UserAuthentication;
import net.teumteum.user.domain.User;
import net.teumteum.user.domain.UserFixture;
import org.springframework.boot.test.context.TestComponent;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

@TestComponent
public class SecurityContextSetting {
public void set() {
User user = UserFixture.getIdUser();
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(new UserAuthentication(user));
SecurityContextHolder.setContext(context);
}
}
Loading

0 comments on commit b68ca54

Please sign in to comment.