├── .gitignore ├── board-api-server ├── Dockerfile ├── build.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── waterfogsw │ │ │ └── board │ │ │ ├── BoardApiApplication.java │ │ │ ├── board │ │ │ ├── controller │ │ │ │ └── BoardRestController.java │ │ │ ├── dto │ │ │ │ ├── BoardCreateRequest.java │ │ │ │ ├── BoardGetDetailResponse.java │ │ │ │ ├── BoardSliceRequest.java │ │ │ │ ├── BoardSliceResponse.java │ │ │ │ └── BoardUpdateRequest.java │ │ │ └── service │ │ │ │ ├── BoardCommandService.java │ │ │ │ └── BoardQueryService.java │ │ │ ├── common │ │ │ ├── auth │ │ │ │ ├── Auth.java │ │ │ │ ├── Authentication.java │ │ │ │ ├── AuthenticationContextHolder.java │ │ │ │ ├── AuthenticationFilter.java │ │ │ │ ├── AuthenticationInterceptor.java │ │ │ │ └── AuthenticationTokenResolver.java │ │ │ ├── config │ │ │ │ ├── PropertyConfig.java │ │ │ │ └── WebConfig.java │ │ │ ├── exception │ │ │ │ └── RestControllerAdvisor.java │ │ │ └── property │ │ │ │ └── JwtProperties.java │ │ │ ├── post │ │ │ ├── controller │ │ │ │ └── PostRestController.java │ │ │ ├── dto │ │ │ │ ├── PostCreateRequest.java │ │ │ │ ├── PostGetDetailResponse.java │ │ │ │ ├── PostSliceRequest.java │ │ │ │ ├── PostSliceResponse.java │ │ │ │ └── PostUpdateRequest.java │ │ │ └── service │ │ │ │ ├── PostCommandService.java │ │ │ │ └── PostQueryService.java │ │ │ └── user │ │ │ ├── dto │ │ │ └── UserInfo.java │ │ │ └── service │ │ │ └── UserService.java │ └── resources │ │ └── application.yml │ └── test │ └── kotlin │ └── com │ └── waterfogsw │ └── board │ └── board │ └── controller │ └── BoardRestControllerTest.kt ├── board-auth-server ├── Dockerfile ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── waterfogsw │ │ └── board │ │ ├── BoardAuthApplication.java │ │ └── auth │ │ ├── common │ │ ├── config │ │ │ ├── OAuthPropertyConfig.java │ │ │ ├── PropertyConfig.java │ │ │ └── RedisConfig.java │ │ └── property │ │ │ ├── JwtProperties.java │ │ │ ├── OAuthProperties.java │ │ │ └── RedisProperties.java │ │ ├── jwt │ │ └── JwtTokenProvider.java │ │ └── oauth │ │ ├── clientRegistration │ │ ├── ClientRegistrationMemoryRepository.java │ │ ├── ClientRegistrationRepository.java │ │ ├── OAuthClientRegistration.java │ │ └── OAuthClientRegistrationPropertiesAdapter.java │ │ ├── controller │ │ └── OAuthRestController.java │ │ ├── dto │ │ ├── LoginResponse.java │ │ ├── OAuthTokenResponse.java │ │ ├── OAuthUserProfile.java │ │ ├── TokenRefreshRequest.java │ │ └── TokenRefreshResponse.java │ │ ├── service │ │ ├── OAuthAuthorizationServerClient.java │ │ └── OAuthService.java │ │ └── userProfile │ │ ├── OAuthUserProfile.java │ │ ├── OAuthUserProfileExtractorFactory.java │ │ └── extractorStrategy │ │ ├── GoogleOAuthUserProfileExtractor.java │ │ └── OAuthUserProfileExtractor.java │ └── resources │ ├── application.yml │ └── static │ └── index.html ├── board-chat-server ├── Dockerfile ├── build.gradle.kts └── src │ └── main │ ├── java │ └── com │ │ └── waterfogsw │ │ └── board │ │ └── BoardChatApplication.kt │ └── resources │ └── application.yml ├── board-core ├── build.gradle └── src │ ├── main │ └── java │ │ └── com │ │ └── waterfogsw │ │ └── board │ │ └── core │ │ ├── board │ │ ├── domain │ │ │ └── Board.java │ │ └── repository │ │ │ ├── BoardQueryRepository.java │ │ │ └── BoardRepository.java │ │ ├── common │ │ ├── entity │ │ │ └── BaseTime.java │ │ └── exception │ │ │ ├── AuthenticationException.java │ │ │ └── NotFoundException.java │ │ ├── config │ │ ├── JpaConfig.java │ │ └── QueryDslConfig.java │ │ ├── post │ │ ├── entity │ │ │ └── Post.java │ │ └── repository │ │ │ ├── PostQueryRepository.java │ │ │ └── PostRepository.java │ │ └── user │ │ ├── domain │ │ ├── Role.java │ │ └── User.java │ │ └── repository │ │ └── UserRepository.java │ └── test │ ├── java │ └── com │ │ └── waterfogsw │ │ └── board │ │ └── core │ │ ├── TestConfig.java │ │ ├── board │ │ └── repository │ │ │ └── BoardQueryRepositoryTest.java │ │ ├── post │ │ └── repository │ │ │ └── PostQueryRepositoryTest.java │ │ └── util │ │ ├── BaseRepositoryTest.java │ │ └── TestDataGenerator.java │ ├── kotlin │ └── com │ │ └── waterfogsw │ │ └── board │ │ └── util │ │ └── restdoc │ │ ├── DocField.kt │ │ ├── DocFieldsType.kt │ │ ├── DocParam.kt │ │ └── DocUtil.kt │ └── resources │ └── application-test.yml ├── build.gradle ├── docker-compose.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── lombok.config └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | 39 | ### Env ### 40 | *.env 41 | -------------------------------------------------------------------------------- /board-api-server/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:17-jdk 2 | ARG JAR_FILE="build/libs/*.jar" 3 | COPY ${JAR_FILE} board-api-server.jar 4 | ENTRYPOINT ["java", "-jar","/board-api-server.jar"] 5 | -------------------------------------------------------------------------------- /board-api-server/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation project(':board-core') 3 | 4 | implementation('io.jsonwebtoken:jjwt:0.9.1') 5 | implementation('org.springframework.boot:spring-boot-starter-web') 6 | runtimeOnly('com.mysql:mysql-connector-j:8.0.31') 7 | annotationProcessor('org.springframework.boot:spring-boot-configuration-processor') 8 | 9 | testImplementation project(':board-core').sourceSets.test.output 10 | } 11 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/BoardApiApplication.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class BoardApiApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(BoardApiApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/board/controller/BoardRestController.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.board.controller; 2 | 3 | import java.util.List; 4 | 5 | import javax.validation.Valid; 6 | 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.web.bind.annotation.DeleteMapping; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.PathVariable; 11 | import org.springframework.web.bind.annotation.PostMapping; 12 | import org.springframework.web.bind.annotation.PutMapping; 13 | import org.springframework.web.bind.annotation.RequestBody; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | import org.springframework.web.bind.annotation.ResponseStatus; 16 | import org.springframework.web.bind.annotation.RestController; 17 | 18 | import com.waterfogsw.board.board.dto.BoardCreateRequest; 19 | import com.waterfogsw.board.board.dto.BoardGetDetailResponse; 20 | import com.waterfogsw.board.board.dto.BoardSliceRequest; 21 | import com.waterfogsw.board.board.dto.BoardSliceResponse; 22 | import com.waterfogsw.board.board.dto.BoardUpdateRequest; 23 | import com.waterfogsw.board.board.service.BoardCommandService; 24 | import com.waterfogsw.board.board.service.BoardQueryService; 25 | import com.waterfogsw.board.common.auth.Auth; 26 | import com.waterfogsw.board.core.user.domain.Role; 27 | 28 | import lombok.RequiredArgsConstructor; 29 | import lombok.extern.slf4j.Slf4j; 30 | 31 | @Slf4j 32 | @RestController 33 | @RequiredArgsConstructor 34 | @RequestMapping("api/v1/boards") 35 | public class BoardRestController { 36 | 37 | private final BoardCommandService boardCommandService; 38 | private final BoardQueryService boardQueryService; 39 | 40 | @Auth(role = Role.USER) 41 | @PostMapping 42 | @ResponseStatus(HttpStatus.CREATED) 43 | public void create( 44 | @Valid @RequestBody 45 | BoardCreateRequest request 46 | ) { 47 | boardCommandService.create(request); 48 | } 49 | 50 | @GetMapping("{id}") 51 | @ResponseStatus(HttpStatus.OK) 52 | public BoardGetDetailResponse getDetail(@PathVariable long id) { 53 | return boardQueryService.getDetail(id); 54 | } 55 | 56 | @Auth(role = Role.USER) 57 | @PutMapping("{id}") 58 | @ResponseStatus(HttpStatus.OK) 59 | public void update( 60 | @PathVariable 61 | long id, 62 | @RequestBody 63 | BoardUpdateRequest request 64 | ) { 65 | boardCommandService.update(id, request); 66 | } 67 | 68 | @Auth(role = Role.USER) 69 | @DeleteMapping("{id}") 70 | @ResponseStatus(HttpStatus.OK) 71 | public void delete(@PathVariable long id) { 72 | boardCommandService.delete(id); 73 | } 74 | 75 | @GetMapping 76 | @ResponseStatus(HttpStatus.OK) 77 | public List getSliceBoard(BoardSliceRequest request) { 78 | return boardQueryService.getSliceOfBoard(request); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/board/dto/BoardCreateRequest.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.board.dto; 2 | 3 | import javax.validation.constraints.NotBlank; 4 | 5 | import org.hibernate.validator.constraints.Length; 6 | 7 | public record BoardCreateRequest( 8 | @NotBlank 9 | @Length(max = 20) 10 | String title, 11 | @NotBlank 12 | @Length(max = 200) 13 | String description 14 | ) { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/board/dto/BoardGetDetailResponse.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.board.dto; 2 | 3 | import com.waterfogsw.board.core.board.domain.Board; 4 | import com.waterfogsw.board.user.dto.UserInfo; 5 | 6 | import lombok.Builder; 7 | 8 | @Builder 9 | public record BoardGetDetailResponse( 10 | long id, 11 | String title, 12 | String description, 13 | UserInfo creatorInfo, 14 | String createdAt 15 | ) { 16 | 17 | public static BoardGetDetailResponse from(Board board) { 18 | UserInfo creatorInfo = UserInfo.from(board.getOwner()); 19 | 20 | return BoardGetDetailResponse.builder() 21 | .id(board.getId()) 22 | .title(board.getTitle()) 23 | .description(board.getDescription()) 24 | .creatorInfo(creatorInfo) 25 | .createdAt( 26 | board.getCreatedAt() 27 | .toLocalDate() 28 | .toString() 29 | ) 30 | .build(); 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/board/dto/BoardSliceRequest.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.board.dto; 2 | 3 | import org.springframework.lang.Nullable; 4 | 5 | public record BoardSliceRequest( 6 | @Nullable 7 | Long id, 8 | Integer size, 9 | @Nullable 10 | String keyword 11 | ) { 12 | 13 | public BoardSliceRequest( 14 | @Nullable 15 | Long id, 16 | Integer size, 17 | @Nullable 18 | String keyword 19 | ) { 20 | this.id = id; 21 | this.size = size == null ? 10 : size; 22 | this.keyword = keyword; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/board/dto/BoardSliceResponse.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.board.dto; 2 | 3 | import com.waterfogsw.board.core.board.domain.Board; 4 | import com.waterfogsw.board.user.dto.UserInfo; 5 | 6 | public record BoardSliceResponse( 7 | long id, 8 | String title, 9 | String description, 10 | UserInfo userInfo 11 | ) { 12 | 13 | public static BoardSliceResponse from(Board board) { 14 | UserInfo userInfo = UserInfo.from(board.getOwner()); 15 | return new BoardSliceResponse(board.getId(), board.getTitle(), board.getDescription(), userInfo); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/board/dto/BoardUpdateRequest.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.board.dto; 2 | 3 | public record BoardUpdateRequest( 4 | String title, 5 | String description 6 | ) { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/board/service/BoardCommandService.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.board.service; 2 | 3 | import org.springframework.stereotype.Service; 4 | import org.springframework.transaction.annotation.Transactional; 5 | 6 | import com.waterfogsw.board.board.dto.BoardCreateRequest; 7 | import com.waterfogsw.board.board.dto.BoardUpdateRequest; 8 | import com.waterfogsw.board.core.board.domain.Board; 9 | import com.waterfogsw.board.core.board.repository.BoardRepository; 10 | import com.waterfogsw.board.core.common.exception.AuthenticationException; 11 | import com.waterfogsw.board.core.common.exception.NotFoundException; 12 | import com.waterfogsw.board.core.user.domain.User; 13 | import com.waterfogsw.board.user.service.UserService; 14 | 15 | import lombok.NonNull; 16 | import lombok.RequiredArgsConstructor; 17 | import lombok.extern.slf4j.Slf4j; 18 | 19 | @Slf4j 20 | @Service 21 | @RequiredArgsConstructor 22 | public class BoardCommandService { 23 | 24 | private final BoardRepository boardRepository; 25 | private final UserService userService; 26 | 27 | @Transactional 28 | public void create(@NonNull BoardCreateRequest request) { 29 | User user = userService.getCurrentUser(); 30 | Board board = Board.builder() 31 | .title(request.title()) 32 | .description(request.description()) 33 | .owner(user) 34 | .build(); 35 | 36 | boardRepository.save(board); 37 | } 38 | 39 | @Transactional 40 | public void update( 41 | long id, 42 | @NonNull 43 | BoardUpdateRequest request 44 | ) { 45 | User user = userService.getCurrentUser(); 46 | Board board = boardRepository.findById(id) 47 | .orElseThrow(() -> new NotFoundException("Board not found")); 48 | 49 | checkBoardOwner(user, board); 50 | board.update(request.title(), request.description()); 51 | } 52 | 53 | @Transactional 54 | public void delete(long id) { 55 | User user = userService.getCurrentUser(); 56 | Board board = boardRepository.findById(id) 57 | .orElseThrow(() -> new NotFoundException("Board not found")); 58 | 59 | checkBoardOwner(user, board); 60 | boardRepository.delete(board); 61 | } 62 | 63 | private void checkBoardOwner( 64 | User user, 65 | Board board 66 | ) { 67 | if (!user.equals(board.getOwner())) { 68 | throw new AuthenticationException(); 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/board/service/BoardQueryService.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.board.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.stereotype.Service; 6 | 7 | import com.waterfogsw.board.board.dto.BoardGetDetailResponse; 8 | import com.waterfogsw.board.board.dto.BoardSliceRequest; 9 | import com.waterfogsw.board.board.dto.BoardSliceResponse; 10 | import com.waterfogsw.board.core.board.repository.BoardQueryRepository; 11 | import com.waterfogsw.board.core.common.exception.NotFoundException; 12 | 13 | import lombok.RequiredArgsConstructor; 14 | 15 | @Service 16 | @RequiredArgsConstructor 17 | public class BoardQueryService { 18 | 19 | private final BoardQueryRepository boardQueryRepository; 20 | 21 | public BoardGetDetailResponse getDetail(long id) { 22 | return boardQueryRepository.getDetail(id) 23 | .map(BoardGetDetailResponse::from) 24 | .orElseThrow(() -> new NotFoundException("Board not found")); 25 | } 26 | 27 | public List getSliceOfBoard(BoardSliceRequest request) { 28 | return boardQueryRepository.getSliceOfBoard(request.id(), request.size(), request.keyword()) 29 | .stream() 30 | .map(BoardSliceResponse::from) 31 | .toList(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/common/auth/Auth.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.common.auth; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | import com.waterfogsw.board.core.user.domain.Role; 9 | 10 | @Target(ElementType.METHOD) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | public @interface Auth { 13 | 14 | Role role() default Role.USER; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/common/auth/Authentication.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.common.auth; 2 | 3 | import com.waterfogsw.board.core.user.domain.Role; 4 | 5 | public record Authentication( 6 | long userId, 7 | Role role 8 | ) { 9 | 10 | public static Authentication createEmptyAuthentication() { 11 | return new Authentication(-1L, Role.GUEST); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/common/auth/AuthenticationContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.common.auth; 2 | 3 | public class AuthenticationContextHolder { 4 | 5 | private static final ThreadLocal authenticationHolder = new ThreadLocal<>(); 6 | 7 | public static void clearContext() { 8 | authenticationHolder.remove(); 9 | } 10 | 11 | public static Authentication getAuthentication() { 12 | Authentication authentication = authenticationHolder.get(); 13 | if (authentication == null) { 14 | authentication = Authentication.createEmptyAuthentication(); 15 | authenticationHolder.set(authentication); 16 | } 17 | return authentication; 18 | } 19 | 20 | public static void setAuthentication(Authentication authentication) { 21 | authenticationHolder.set(authentication); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/common/auth/AuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.common.auth; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.FilterChain; 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.web.filter.OncePerRequestFilter; 12 | 13 | import io.jsonwebtoken.JwtException; 14 | import lombok.RequiredArgsConstructor; 15 | import lombok.extern.slf4j.Slf4j; 16 | 17 | @Slf4j 18 | @Component 19 | @RequiredArgsConstructor 20 | public class AuthenticationFilter extends OncePerRequestFilter { 21 | 22 | private static final String TOKEN_HEADER = "Authorization"; 23 | private final AuthenticationTokenResolver tokenResolver; 24 | 25 | @Override 26 | protected void doFilterInternal( 27 | HttpServletRequest request, 28 | HttpServletResponse response, 29 | FilterChain filterChain 30 | ) throws ServletException, IOException { 31 | 32 | try { 33 | String token = extractTokenFromHeader(request); 34 | if (tokenResolver.isTokenNotExpired(token)) { 35 | throw new JwtException("Invalid token exception"); 36 | } 37 | Authentication authentication = tokenResolver.getAuthentication(token); 38 | log.info("test={}", authentication.toString()); 39 | AuthenticationContextHolder.setAuthentication(authentication); 40 | } catch (Exception e) { 41 | log.debug(e.getMessage()); 42 | } 43 | 44 | doFilter(request, response, filterChain); 45 | AuthenticationContextHolder.clearContext(); 46 | } 47 | 48 | private String extractTokenFromHeader(HttpServletRequest request) { 49 | String authorization = request.getHeader(TOKEN_HEADER); 50 | if (authorization == null) { 51 | throw new IllegalArgumentException("Token not found"); 52 | } 53 | try { 54 | return authorization.split(" ")[1]; 55 | } catch (Exception e) { 56 | throw new IllegalArgumentException("Invalid token format"); 57 | } 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/common/auth/AuthenticationInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.common.auth; 2 | 3 | import java.util.Objects; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | import org.springframework.stereotype.Component; 9 | import org.springframework.web.method.HandlerMethod; 10 | import org.springframework.web.servlet.HandlerInterceptor; 11 | import org.springframework.web.servlet.ModelAndView; 12 | 13 | import com.waterfogsw.board.core.common.exception.AuthenticationException; 14 | import com.waterfogsw.board.core.user.domain.Role; 15 | 16 | import lombok.RequiredArgsConstructor; 17 | 18 | @Component 19 | @RequiredArgsConstructor 20 | public class AuthenticationInterceptor implements HandlerInterceptor { 21 | 22 | @Override 23 | public boolean preHandle( 24 | HttpServletRequest request, 25 | HttpServletResponse response, 26 | Object handler 27 | ) { 28 | if (!(handler instanceof HandlerMethod handlerMethod)) { 29 | return true; 30 | } 31 | 32 | if (isNeedsAuthorization(handlerMethod)) { 33 | return true; 34 | } 35 | 36 | Authentication authentication = AuthenticationContextHolder.getAuthentication(); 37 | Role clientRole = authentication.role(); 38 | Role handlerRole = getMethodRole(handlerMethod); 39 | 40 | if (!clientRole.hasAuthority(handlerRole)) { 41 | throw new AuthenticationException(); 42 | } 43 | 44 | AuthenticationContextHolder.setAuthentication(authentication); 45 | 46 | return true; 47 | } 48 | 49 | @Override 50 | public void postHandle( 51 | HttpServletRequest request, 52 | HttpServletResponse response, 53 | Object handler, 54 | ModelAndView modelAndView 55 | ) { 56 | AuthenticationContextHolder.clearContext(); 57 | } 58 | 59 | private Role getMethodRole(HandlerMethod handlerMethod) { 60 | return Objects.requireNonNull(handlerMethod.getMethodAnnotation(Auth.class)) 61 | .role(); 62 | } 63 | 64 | private boolean isNeedsAuthorization(HandlerMethod handlerMethod) { 65 | return handlerMethod.getMethodAnnotation(Auth.class) == null; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/common/auth/AuthenticationTokenResolver.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.common.auth; 2 | 3 | import java.util.Date; 4 | 5 | import org.springframework.stereotype.Component; 6 | 7 | import com.waterfogsw.board.common.property.JwtProperties; 8 | import com.waterfogsw.board.core.user.domain.Role; 9 | 10 | import io.jsonwebtoken.Claims; 11 | import io.jsonwebtoken.Jwts; 12 | import lombok.RequiredArgsConstructor; 13 | 14 | @Component 15 | @RequiredArgsConstructor 16 | public class AuthenticationTokenResolver { 17 | 18 | private final JwtProperties properties; 19 | private static final String ROLE_CLAIM_NAME = "role"; 20 | 21 | public Authentication getAuthentication(String token) { 22 | Claims claims = getClaims(token); 23 | 24 | String subject = claims.getSubject(); 25 | long userId = Long.parseLong(subject); 26 | 27 | String roleStr = claims.get(ROLE_CLAIM_NAME) 28 | .toString(); 29 | Role role = Role.valueOf(roleStr); 30 | 31 | return new Authentication(userId, role); 32 | } 33 | 34 | public boolean isTokenNotExpired(String token) { 35 | return getClaims(token).getExpiration() 36 | .before(new Date()); 37 | } 38 | 39 | private Claims getClaims(String token) { 40 | return Jwts.parser() 41 | .setSigningKey(properties.clientSecret()) 42 | .parseClaimsJws(token) 43 | .getBody(); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/common/config/PropertyConfig.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.common.config; 2 | 3 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import com.waterfogsw.board.common.property.JwtProperties; 7 | 8 | @Configuration 9 | @EnableConfigurationProperties({ 10 | JwtProperties.class 11 | }) 12 | public class PropertyConfig { 13 | 14 | } 15 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/common/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.common.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 | 7 | import com.waterfogsw.board.common.auth.AuthenticationInterceptor; 8 | 9 | import lombok.RequiredArgsConstructor; 10 | 11 | @Configuration 12 | @RequiredArgsConstructor 13 | public class WebConfig implements WebMvcConfigurer { 14 | 15 | private final AuthenticationInterceptor authenticationInterceptor; 16 | 17 | @Override 18 | public void addInterceptors(InterceptorRegistry registry) { 19 | registry.addInterceptor(authenticationInterceptor); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/common/exception/RestControllerAdvisor.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.common.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ExceptionHandler; 5 | import org.springframework.web.bind.annotation.ResponseStatus; 6 | import org.springframework.web.bind.annotation.RestControllerAdvice; 7 | 8 | import com.waterfogsw.board.core.common.exception.AuthenticationException; 9 | import com.waterfogsw.board.core.common.exception.NotFoundException; 10 | 11 | import lombok.extern.slf4j.Slf4j; 12 | 13 | @Slf4j 14 | @RestControllerAdvice 15 | public class RestControllerAdvisor { 16 | 17 | @ResponseStatus(HttpStatus.FORBIDDEN) 18 | @ExceptionHandler(AuthenticationException.class) 19 | public void forbidden(AuthenticationException e) { 20 | log.info("exception={}, message={}", e, e.getMessage()); 21 | } 22 | 23 | @ResponseStatus(HttpStatus.NOT_FOUND) 24 | @ExceptionHandler(NotFoundException.class) 25 | public void notfound(NotFoundException e) { 26 | log.debug("exception={}, message={}", e.getClass(), e.getMessage()); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/common/property/JwtProperties.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.common.property; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.boot.context.properties.ConstructorBinding; 5 | 6 | @ConstructorBinding 7 | @ConfigurationProperties(prefix = "jwt") 8 | public record JwtProperties( 9 | String clientSecret 10 | ) { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/post/controller/PostRestController.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.post.controller; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.web.bind.annotation.DeleteMapping; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PathVariable; 9 | import org.springframework.web.bind.annotation.PostMapping; 10 | import org.springframework.web.bind.annotation.PutMapping; 11 | import org.springframework.web.bind.annotation.RequestBody; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.ResponseStatus; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | import com.waterfogsw.board.common.auth.Auth; 17 | import com.waterfogsw.board.core.user.domain.Role; 18 | import com.waterfogsw.board.post.dto.PostCreateRequest; 19 | import com.waterfogsw.board.post.dto.PostGetDetailResponse; 20 | import com.waterfogsw.board.post.dto.PostSliceRequest; 21 | import com.waterfogsw.board.post.dto.PostSliceResponse; 22 | import com.waterfogsw.board.post.dto.PostUpdateRequest; 23 | import com.waterfogsw.board.post.service.PostCommandService; 24 | import com.waterfogsw.board.post.service.PostQueryService; 25 | 26 | import lombok.RequiredArgsConstructor; 27 | 28 | @RestController 29 | @RequiredArgsConstructor 30 | @RequestMapping("api/v1/posts") 31 | public class PostRestController { 32 | 33 | private final PostCommandService postCommandService; 34 | private final PostQueryService postQueryService; 35 | 36 | @Auth(role = Role.USER) 37 | @PostMapping 38 | @ResponseStatus(HttpStatus.CREATED) 39 | public void create(@RequestBody PostCreateRequest request) { 40 | postCommandService.create(request); 41 | } 42 | 43 | @Auth(role = Role.USER) 44 | @PutMapping("{id}") 45 | @ResponseStatus(HttpStatus.OK) 46 | public void update( 47 | @PathVariable 48 | long id, 49 | @RequestBody 50 | PostUpdateRequest request 51 | ) { 52 | postCommandService.update(id, request); 53 | } 54 | 55 | @Auth(role = Role.USER) 56 | @DeleteMapping("{id}") 57 | @ResponseStatus(HttpStatus.OK) 58 | public void delete(@PathVariable long id) { 59 | postCommandService.delete(id); 60 | } 61 | 62 | @GetMapping("{id}") 63 | @ResponseStatus(HttpStatus.OK) 64 | public PostGetDetailResponse getDetail(@PathVariable long id) { 65 | return postQueryService.getDetail(id); 66 | } 67 | 68 | @GetMapping 69 | @ResponseStatus(HttpStatus.OK) 70 | public List getSlice(PostSliceRequest request) { 71 | return postQueryService.getSlice(request); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/post/dto/PostCreateRequest.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.post.dto; 2 | 3 | public record PostCreateRequest( 4 | String title, 5 | String content, 6 | long boardId 7 | ) { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/post/dto/PostGetDetailResponse.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.post.dto; 2 | 3 | import com.waterfogsw.board.core.post.entity.Post; 4 | import com.waterfogsw.board.user.dto.UserInfo; 5 | 6 | import lombok.Builder; 7 | 8 | @Builder 9 | public record PostGetDetailResponse( 10 | long id, 11 | String title, 12 | String content, 13 | UserInfo writer, 14 | String createdAt, 15 | String updatedAt 16 | ) { 17 | 18 | public static PostGetDetailResponse from(Post post) { 19 | UserInfo writer = UserInfo.from(post.getWriter()); 20 | return PostGetDetailResponse.builder() 21 | .id(post.getId()) 22 | .title(post.getTitle()) 23 | .content(post.getContent()) 24 | .writer(writer) 25 | .createdAt( 26 | post.getCreatedAt() 27 | .toString() 28 | ) 29 | .updatedAt( 30 | post.getUpdatedAt() 31 | .toString() 32 | ) 33 | .build(); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/post/dto/PostSliceRequest.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.post.dto; 2 | 3 | import javax.annotation.Nullable; 4 | 5 | public record PostSliceRequest( 6 | @Nullable 7 | Long id, 8 | long boardId, 9 | Integer size, 10 | @Nullable 11 | String keyword 12 | ) { 13 | 14 | public PostSliceRequest( 15 | @Nullable 16 | Long id, 17 | long boardId, 18 | Integer size, 19 | @Nullable 20 | String keyword 21 | ) { 22 | this.id = id; 23 | this.boardId = boardId; 24 | this.size = size == null ? 10 : size; 25 | this.keyword = keyword; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/post/dto/PostSliceResponse.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.post.dto; 2 | 3 | import com.waterfogsw.board.core.post.entity.Post; 4 | import com.waterfogsw.board.user.dto.UserInfo; 5 | 6 | import lombok.Builder; 7 | 8 | @Builder 9 | public record PostSliceResponse( 10 | long id, 11 | String title, 12 | String content, 13 | UserInfo writer, 14 | String createdAt, 15 | String updatedAt 16 | ) { 17 | 18 | public static PostSliceResponse from(Post post) { 19 | UserInfo writer = UserInfo.from(post.getWriter()); 20 | return PostSliceResponse.builder() 21 | .id(post.getId()) 22 | .title(post.getTitle()) 23 | .content(post.getContent()) 24 | .writer(writer) 25 | .createdAt( 26 | post.getCreatedAt() 27 | .toString() 28 | ) 29 | .updatedAt( 30 | post.getUpdatedAt() 31 | .toString() 32 | ) 33 | .build(); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/post/dto/PostUpdateRequest.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.post.dto; 2 | 3 | public record PostUpdateRequest( 4 | String title, 5 | String content 6 | ) { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/post/service/PostCommandService.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.post.service; 2 | 3 | import org.springframework.stereotype.Service; 4 | import org.springframework.transaction.annotation.Transactional; 5 | 6 | import com.waterfogsw.board.core.board.domain.Board; 7 | import com.waterfogsw.board.core.board.repository.BoardRepository; 8 | import com.waterfogsw.board.core.common.exception.AuthenticationException; 9 | import com.waterfogsw.board.core.common.exception.NotFoundException; 10 | import com.waterfogsw.board.core.post.entity.Post; 11 | import com.waterfogsw.board.core.post.repository.PostRepository; 12 | import com.waterfogsw.board.core.user.domain.User; 13 | import com.waterfogsw.board.post.dto.PostCreateRequest; 14 | import com.waterfogsw.board.post.dto.PostUpdateRequest; 15 | import com.waterfogsw.board.user.service.UserService; 16 | 17 | import lombok.RequiredArgsConstructor; 18 | 19 | @Service 20 | @RequiredArgsConstructor 21 | public class PostCommandService { 22 | 23 | private final PostRepository postRepository; 24 | private final BoardRepository boardRepository; 25 | private final UserService userService; 26 | 27 | @Transactional 28 | public void create(PostCreateRequest request) { 29 | User user = userService.getCurrentUser(); 30 | 31 | Board board = boardRepository.findById(request.boardId()) 32 | .orElseThrow(() -> new NotFoundException("Board not found")); 33 | 34 | Post post = Post.builder() 35 | .title(request.title()) 36 | .content(request.content()) 37 | .writer(user) 38 | .board(board) 39 | .build(); 40 | 41 | postRepository.save(post); 42 | } 43 | 44 | @Transactional 45 | public void update( 46 | long id, 47 | PostUpdateRequest request 48 | ) { 49 | User user = userService.getCurrentUser(); 50 | Post post = postRepository.findById(id) 51 | .orElseThrow(() -> new NotFoundException("Post not found")); 52 | 53 | checkPostOwner(user, post); 54 | post.update(request.title(), request.content()); 55 | } 56 | 57 | @Transactional 58 | public void delete(long id) { 59 | User user = userService.getCurrentUser(); 60 | Post post = postRepository.findById(id) 61 | .orElseThrow(() -> new NotFoundException("Post not found")); 62 | 63 | checkPostOwner(user, post); 64 | postRepository.delete(post); 65 | } 66 | 67 | private void checkPostOwner( 68 | User user, 69 | Post post 70 | ) { 71 | if (!user.equals(post.getWriter())) { 72 | throw new AuthenticationException(); 73 | } 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/post/service/PostQueryService.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.post.service; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.stereotype.Service; 6 | 7 | import com.waterfogsw.board.core.common.exception.NotFoundException; 8 | import com.waterfogsw.board.core.post.repository.PostQueryRepository; 9 | import com.waterfogsw.board.post.dto.PostGetDetailResponse; 10 | import com.waterfogsw.board.post.dto.PostSliceRequest; 11 | import com.waterfogsw.board.post.dto.PostSliceResponse; 12 | 13 | import lombok.RequiredArgsConstructor; 14 | 15 | @Service 16 | @RequiredArgsConstructor 17 | public class PostQueryService { 18 | 19 | private final PostQueryRepository postQueryRepository; 20 | 21 | public PostGetDetailResponse getDetail(long id) { 22 | return postQueryRepository.getDetail(id) 23 | .map(PostGetDetailResponse::from) 24 | .orElseThrow(() -> new NotFoundException("Post not found")); 25 | } 26 | 27 | public List getSlice(PostSliceRequest request) { 28 | return postQueryRepository.getSlice(request.id(), request.boardId(), request.size(), request.keyword()) 29 | .stream() 30 | .map(PostSliceResponse::from) 31 | .toList(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/user/dto/UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.user.dto; 2 | 3 | import com.waterfogsw.board.core.user.domain.User; 4 | 5 | public record UserInfo( 6 | long id, 7 | String name, 8 | String imageUrl 9 | ) { 10 | 11 | public static UserInfo from(User user) { 12 | return new UserInfo(user.getId(), user.getName(), user.getImageUrl()); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /board-api-server/src/main/java/com/waterfogsw/board/user/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.user.service; 2 | 3 | import org.springframework.stereotype.Service; 4 | 5 | import com.waterfogsw.board.common.auth.Authentication; 6 | import com.waterfogsw.board.common.auth.AuthenticationContextHolder; 7 | import com.waterfogsw.board.core.common.exception.NotFoundException; 8 | import com.waterfogsw.board.core.user.domain.User; 9 | import com.waterfogsw.board.core.user.repository.UserRepository; 10 | 11 | import lombok.RequiredArgsConstructor; 12 | 13 | @Service 14 | @RequiredArgsConstructor 15 | public class UserService { 16 | 17 | private final UserRepository userRepository; 18 | 19 | public User getUser(long userId) { 20 | return userRepository.findById(userId) 21 | .orElseThrow(() -> new NotFoundException("User not found")); 22 | } 23 | 24 | public User getCurrentUser() { 25 | Authentication authentication = AuthenticationContextHolder.getAuthentication(); 26 | long userId = authentication.userId(); 27 | return getUser(userId); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /board-api-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8081 3 | 4 | spring: 5 | jpa: 6 | database: mysql 7 | hibernate: 8 | ddl-auto: update 9 | open-in-view: false 10 | properties: 11 | dialect: org.hibernate.dialect.MySQL8Dialect 12 | datasource: 13 | url: ${datasource_url} 14 | username: ${datasource_username} 15 | password: ${datasource_password} 16 | 17 | jwt: 18 | client-secret: ${token_client_secret} 19 | -------------------------------------------------------------------------------- /board-api-server/src/test/kotlin/com/waterfogsw/board/board/controller/BoardRestControllerTest.kt: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.board.controller 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper 4 | import com.waterfogsw.board.board.dto.* 5 | import com.waterfogsw.board.board.service.BoardCommandService 6 | import com.waterfogsw.board.board.service.BoardQueryService 7 | import com.waterfogsw.board.common.auth.* 8 | import com.waterfogsw.board.core.user.domain.Role 9 | import com.waterfogsw.board.user.dto.UserInfo 10 | import com.waterfogsw.board.util.restdoc.* 11 | import io.kotest.core.spec.style.DescribeSpec 12 | import org.junit.jupiter.api.extension.ExtendWith 13 | import org.mockito.ArgumentMatchers.anyLong 14 | import org.mockito.BDDMockito.given 15 | import org.springframework.beans.factory.annotation.Autowired 16 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest 17 | import org.springframework.boot.test.mock.mockito.MockBean 18 | import org.springframework.boot.test.mock.mockito.MockBeans 19 | import org.springframework.http.HttpMethod 20 | import org.springframework.http.MediaType 21 | import org.springframework.restdocs.ManualRestDocumentation 22 | import org.springframework.restdocs.RestDocumentationExtension 23 | import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get 24 | import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.request 25 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status 26 | import org.springframework.web.context.WebApplicationContext 27 | import java.time.LocalDateTime 28 | 29 | @MockBeans( 30 | MockBean(AuthenticationTokenResolver::class) 31 | ) 32 | @WebMvcTest(BoardRestController::class) 33 | @ExtendWith(RestDocumentationExtension::class) 34 | class BoardRestControllerTest( 35 | @MockBean 36 | private val commandService: BoardCommandService, 37 | @MockBean 38 | private val queryService: BoardQueryService, 39 | @Autowired 40 | private val context: WebApplicationContext, 41 | @Autowired 42 | private val mapper: ObjectMapper, 43 | ) : DescribeSpec({ 44 | val restDocumentation = ManualRestDocumentation() 45 | val mockMvc = restDocMockMvcBuild(context, restDocumentation) 46 | 47 | beforeEach { restDocumentation.beforeTest(javaClass, it.name.testName) } 48 | afterEach { restDocumentation.afterTest() } 49 | 50 | describe("POST : /api/v1/boards") { 51 | val url = "/api/v1/boards" 52 | context("유효한 요청이 전달 되면") { 53 | val authentication = Authentication(1L, Role.USER) 54 | AuthenticationContextHolder.setAuthentication(authentication) 55 | 56 | val requestBody = BoardCreateRequest("Test", "Test") 57 | val requestJson = mapper.writeValueAsString(requestBody) 58 | val request = request(HttpMethod.POST, url) 59 | .contentType(MediaType.APPLICATION_JSON) 60 | .content(requestJson) 61 | 62 | it("201 응답") { 63 | mockMvc 64 | .perform(request) 65 | .andExpect(status().isCreated) 66 | .andDocument( 67 | "Create Board", ( 68 | requestBody( 69 | "title" fieldType STRING means "게시판 이름" isOptional false, 70 | "description" fieldType STRING means "게시판 설명" isOptional true 71 | )) 72 | ) 73 | } 74 | } 75 | 76 | context("제목의 길이가 1~20사이가 아니면") { 77 | val authentication = Authentication(1L, Role.USER) 78 | AuthenticationContextHolder.setAuthentication(authentication) 79 | 80 | val titles = listOf(null, "", "\n", "a".repeat(21)) 81 | titles.forEach { title -> 82 | val requestBody = BoardCreateRequest(title, "Test") 83 | val requestJson = mapper.writeValueAsString(requestBody) 84 | val request = request(HttpMethod.POST, url) 85 | .contentType(MediaType.APPLICATION_JSON) 86 | .content(requestJson) 87 | 88 | it("400 응답") { 89 | mockMvc 90 | .perform(request) 91 | .andExpect(status().isBadRequest) 92 | } 93 | } 94 | } 95 | 96 | context("설명의 길이가 1~200사이가 아니면") { 97 | val authentication = Authentication(1L, Role.USER) 98 | AuthenticationContextHolder.setAuthentication(authentication) 99 | 100 | val descriptions = listOf(null, "", "\n", "a".repeat(201)) 101 | descriptions.forEach { description -> 102 | val requestBody = BoardCreateRequest("Test", description) 103 | val requestJson = mapper.writeValueAsString(requestBody) 104 | val request = request(HttpMethod.POST, url) 105 | .contentType(MediaType.APPLICATION_JSON) 106 | .content(requestJson) 107 | 108 | it("400 응답") { 109 | mockMvc 110 | .perform(request) 111 | .andExpect(status().isBadRequest) 112 | } 113 | } 114 | } 115 | } 116 | 117 | describe("GET : /api/v1/boards/{id}") { 118 | val url = "/api/v1/boards/{id}" 119 | context("유효한 요청이 전달 되면") { 120 | val id = 1L 121 | val request = request(HttpMethod.GET, url, id) 122 | it("200 응답") { 123 | val response = getTestBoardGetDetailResponse() 124 | given(queryService.getDetail(anyLong())).willReturn(response) 125 | mockMvc 126 | .perform(request) 127 | .andExpect(status().isOk) 128 | .andDocument( 129 | "Lookup Board", 130 | pathParameters( 131 | "id" pathMeans "게시판 번호" 132 | ), 133 | responseBody( 134 | "id" fieldType NUMBER means "게시판 번호" isOptional false, 135 | "title" fieldType STRING means "게시판 제목" isOptional false, 136 | "description" fieldType STRING means "게시판 제목" isOptional true, 137 | "creatorInfo.id" fieldType NUMBER means "게시판 생성자 번호" isOptional false, 138 | "creatorInfo.name" fieldType STRING means "게시판 생성자 이름" isOptional false, 139 | "creatorInfo.imageUrl" fieldType STRING means "게시판 생성자 이미지 URL" isOptional false, 140 | "createdAt" fieldType STRING means "게시판 생성일" isOptional false, 141 | ) 142 | ) 143 | } 144 | } 145 | } 146 | 147 | describe("GET : /api/v1/boards") { 148 | val url = "/api/v1/boards" 149 | context("유효한 요청이 전달 되면") { 150 | val request = get(url) 151 | .param("id", "1") 152 | .param("size", "10") 153 | .param("keyword", "test") 154 | it("200 응답") { 155 | val response = getTestBoardGetDetailResponse() 156 | given(queryService.getDetail(anyLong())).willReturn(response) 157 | mockMvc 158 | .perform(request) 159 | .andExpect(status().isOk) 160 | .andDocument( 161 | "Slice Board", 162 | pathParameters( 163 | "id" pathMeans "조회 시작 게시판 번호", 164 | "size" pathMeans "조회할 게시판 개수", 165 | "keyword" pathMeans "게시판 검색어" 166 | ), 167 | responseBody( 168 | "id" fieldType NUMBER means "게시판 번호" isOptional false, 169 | "title" fieldType STRING means "게시판 제목" isOptional false, 170 | "description" fieldType STRING means "게시판 제목" isOptional true, 171 | "creatorInfo.id" fieldType NUMBER means "게시판 생성자 번호" isOptional false, 172 | "creatorInfo.name" fieldType STRING means "게시판 생성자 이름" isOptional false, 173 | "creatorInfo.imageUrl" fieldType STRING means "게시판 생성자 이미지 URL" isOptional false, 174 | "createdAt" fieldType STRING means "게시판 생성일" isOptional false, 175 | ) 176 | ) 177 | } 178 | } 179 | } 180 | 181 | describe("PUT : /api/v1/boards/{id}") { 182 | val url = "/api/v1/boards/{id}" 183 | context("유효한 요청이 전달 되면") { 184 | val authentication = Authentication(1L, Role.USER) 185 | AuthenticationContextHolder.setAuthentication(authentication) 186 | 187 | val id = 1L 188 | val requestBody = BoardUpdateRequest("Test", "Test") 189 | val requestJson = mapper.writeValueAsString(requestBody) 190 | val request = request(HttpMethod.PUT, url, id) 191 | .contentType(MediaType.APPLICATION_JSON) 192 | .content(requestJson) 193 | it("200 응답") { 194 | mockMvc 195 | .perform(request) 196 | .andExpect(status().isOk) 197 | .andDocument( 198 | "Update Board", 199 | pathParameters( 200 | "id" pathMeans "게시판 번호" 201 | ), 202 | requestBody( 203 | "title" fieldType STRING means "게시판 이름" isOptional false, 204 | "description" fieldType STRING means "게시판 설명" isOptional true 205 | ) 206 | ) 207 | } 208 | } 209 | } 210 | 211 | describe("DELETE : /api/v1/boards/{id}") { 212 | val url = "/api/v1/boards/{id}" 213 | context("유효한 요청이 전달 되면") { 214 | val authentication = Authentication(1L, Role.USER) 215 | AuthenticationContextHolder.setAuthentication(authentication) 216 | 217 | val id = 1L 218 | val request = request(HttpMethod.DELETE, url, id) 219 | 220 | it("200 응답") { 221 | mockMvc 222 | .perform(request) 223 | .andExpect(status().isOk) 224 | .andDocument( 225 | "Delete Board", 226 | pathParameters( 227 | "id" pathMeans "게시판 번호" 228 | ) 229 | ) 230 | } 231 | } 232 | } 233 | }) 234 | 235 | fun getTestUserInfo(): UserInfo { 236 | return UserInfo(1L, "Garry", "https://sublimeygmewhw4zeus.iqg") 237 | } 238 | 239 | fun getTestBoardGetDetailResponse(): BoardGetDetailResponse { 240 | return BoardGetDetailResponse( 241 | 1L, 242 | "firms", 243 | "Canadian interface avoiding resorts paper manitoba", 244 | getTestUserInfo(), 245 | LocalDateTime 246 | .now() 247 | .toString() 248 | ) 249 | } 250 | -------------------------------------------------------------------------------- /board-auth-server/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:17-jdk 2 | ARG JAR_FILE="build/libs/*.jar" 3 | COPY ${JAR_FILE} board-auth-server.jar 4 | ENTRYPOINT ["java", "-jar","/board-auth-server.jar"] 5 | -------------------------------------------------------------------------------- /board-auth-server/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation project(':board-core') 3 | 4 | implementation('org.springframework.boot:spring-boot-starter-web') 5 | implementation('org.springframework.boot:spring-boot-starter-webflux') 6 | implementation('org.springframework.boot:spring-boot-starter-data-redis') 7 | implementation('io.netty:netty-resolver-dns-native-macos:4.1.85.Final:osx-aarch_64') 8 | implementation('io.jsonwebtoken:jjwt:0.9.1') 9 | runtimeOnly('com.mysql:mysql-connector-j:8.0.31') 10 | annotationProcessor('org.springframework.boot:spring-boot-configuration-processor') 11 | testImplementation('org.springframework.restdocs:spring-restdocs-mockmvc') 12 | } 13 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/BoardAuthApplication.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class BoardAuthApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(BoardAuthApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/common/config/OAuthPropertyConfig.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.common.config; 2 | 3 | import java.util.Map; 4 | 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | import com.waterfogsw.board.auth.common.property.OAuthProperties; 9 | import com.waterfogsw.board.auth.oauth.clientRegistration.ClientRegistrationMemoryRepository; 10 | import com.waterfogsw.board.auth.oauth.clientRegistration.ClientRegistrationRepository; 11 | import com.waterfogsw.board.auth.oauth.clientRegistration.OAuthClientRegistration; 12 | import com.waterfogsw.board.auth.oauth.clientRegistration.OAuthClientRegistrationPropertiesAdapter; 13 | 14 | import lombok.RequiredArgsConstructor; 15 | 16 | @Configuration 17 | @RequiredArgsConstructor 18 | public class OAuthPropertyConfig { 19 | 20 | private final OAuthProperties properties; 21 | 22 | @Bean 23 | public ClientRegistrationRepository clientRegistrationRepository() { 24 | Map oauthProviders = 25 | OAuthClientRegistrationPropertiesAdapter.getOauthProviders(properties); 26 | 27 | return new ClientRegistrationMemoryRepository(oauthProviders); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/common/config/PropertyConfig.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.common.config; 2 | 3 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import com.waterfogsw.board.auth.common.property.JwtProperties; 7 | import com.waterfogsw.board.auth.common.property.OAuthProperties; 8 | import com.waterfogsw.board.auth.common.property.RedisProperties; 9 | 10 | @Configuration 11 | @EnableConfigurationProperties({ 12 | OAuthProperties.class, 13 | JwtProperties.class, 14 | RedisProperties.class 15 | }) 16 | public class PropertyConfig { 17 | 18 | } 19 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/common/config/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.common.config; 2 | 3 | import static io.lettuce.core.ReadFrom.*; 4 | 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.data.redis.connection.RedisConnectionFactory; 8 | import org.springframework.data.redis.connection.RedisStaticMasterReplicaConfiguration; 9 | import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; 10 | import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; 11 | import org.springframework.data.redis.core.StringRedisTemplate; 12 | import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; 13 | import org.springframework.data.redis.serializer.StringRedisSerializer; 14 | 15 | import com.waterfogsw.board.auth.common.property.RedisProperties; 16 | 17 | import lombok.RequiredArgsConstructor; 18 | 19 | @Configuration 20 | @EnableRedisRepositories 21 | @RequiredArgsConstructor 22 | public class RedisConfig { 23 | 24 | private final RedisProperties redisProperties; 25 | 26 | @Bean 27 | public RedisConnectionFactory redisConnectionFactory() { 28 | LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder() 29 | .readFrom(REPLICA_PREFERRED) 30 | .build(); 31 | RedisProperties.RedisInfo masterInfo = redisProperties.master(); 32 | RedisProperties.RedisInfo slaveInfo = redisProperties.slave(); 33 | 34 | RedisStaticMasterReplicaConfiguration redisConfig = 35 | new RedisStaticMasterReplicaConfiguration(masterInfo.host(), masterInfo.port()); 36 | 37 | redisConfig.addNode(slaveInfo.host(), slaveInfo.port()); 38 | 39 | return new LettuceConnectionFactory(redisConfig, clientConfig); 40 | } 41 | 42 | @Bean 43 | public StringRedisTemplate stringRedisTemplate() { 44 | StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); 45 | stringRedisTemplate.setKeySerializer(new StringRedisSerializer()); 46 | stringRedisTemplate.setValueSerializer(new StringRedisSerializer()); 47 | stringRedisTemplate.setConnectionFactory(redisConnectionFactory()); 48 | return stringRedisTemplate; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/common/property/JwtProperties.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.common.property; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.boot.context.properties.ConstructorBinding; 5 | 6 | @ConstructorBinding 7 | @ConfigurationProperties(prefix = "jwt") 8 | public record JwtProperties( 9 | String accessTokenHeader, 10 | String refreshTokenHeader, 11 | String issuer, 12 | String prefix, 13 | String clientSecret, 14 | Long accessTokenExpirySeconds, 15 | Long refreshTokenExpirySeconds 16 | ) { 17 | 18 | } 19 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/common/property/OAuthProperties.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.common.property; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.springframework.boot.context.properties.ConfigurationProperties; 7 | 8 | import lombok.Getter; 9 | 10 | @Getter 11 | @ConfigurationProperties(prefix = "oauth2") 12 | public class OAuthProperties { 13 | 14 | private final Map clients = new HashMap<>(); 15 | private final Map providers = new HashMap<>(); 16 | 17 | public record Client( 18 | String clientId, 19 | String clientSecret, 20 | String redirectUri 21 | ) { 22 | 23 | } 24 | 25 | public record Provider( 26 | String tokenUri, 27 | String userInfoUri, 28 | String userNameAttribute 29 | ) { 30 | 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/common/property/RedisProperties.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.common.property; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.boot.context.properties.ConstructorBinding; 5 | 6 | @ConstructorBinding 7 | @ConfigurationProperties(prefix = "redis") 8 | public record RedisProperties( 9 | RedisInfo master, 10 | RedisInfo slave 11 | ) { 12 | 13 | public static record RedisInfo( 14 | String host, 15 | int port 16 | ) { 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/jwt/JwtTokenProvider.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.jwt; 2 | 3 | import java.util.Date; 4 | 5 | import org.springframework.stereotype.Component; 6 | 7 | import com.waterfogsw.board.auth.common.property.JwtProperties; 8 | import com.waterfogsw.board.core.user.domain.Role; 9 | import com.waterfogsw.board.core.user.domain.User; 10 | 11 | import io.jsonwebtoken.ExpiredJwtException; 12 | import io.jsonwebtoken.JwtException; 13 | import io.jsonwebtoken.Jwts; 14 | import io.jsonwebtoken.SignatureAlgorithm; 15 | import lombok.RequiredArgsConstructor; 16 | 17 | @Component 18 | @RequiredArgsConstructor 19 | public class JwtTokenProvider { 20 | 21 | private final JwtProperties properties; 22 | 23 | private static final String ROLE_CLAIM_NAME = "role"; 24 | 25 | public String createAccessToken(User user) { 26 | Long userId = user.getId(); 27 | Role userRole = user.getRole(); 28 | 29 | long expirySeconds = properties.accessTokenExpirySeconds(); 30 | Date now = new Date(); 31 | Date validity = new Date(now.getTime() + expirySeconds); 32 | 33 | return Jwts.builder() 34 | .claim(ROLE_CLAIM_NAME, userRole.name()) 35 | .setSubject(userId.toString()) 36 | .setIssuedAt(now) 37 | .setExpiration(validity) 38 | .signWith(SignatureAlgorithm.HS256, properties.clientSecret()) 39 | .compact(); 40 | 41 | } 42 | 43 | public String createRefreshToken(String payload) { 44 | long expirySeconds = properties.refreshTokenExpirySeconds(); 45 | 46 | Date now = new Date(); 47 | Date validity = new Date(now.getTime() + expirySeconds); 48 | 49 | return Jwts.builder() 50 | .setSubject(payload) 51 | .setIssuedAt(now) 52 | .setExpiration(validity) 53 | .signWith(SignatureAlgorithm.HS256, properties.clientSecret()) 54 | .compact(); 55 | } 56 | 57 | public String getPayload(String token) { 58 | try { 59 | return Jwts.parser() 60 | .setSigningKey(properties.clientSecret()) 61 | .parseClaimsJws(token) 62 | .getBody() 63 | .getSubject(); 64 | } catch (ExpiredJwtException e) { 65 | return e.getClaims() 66 | .getSubject(); 67 | } catch (JwtException e) { 68 | throw new IllegalArgumentException("Invalid token"); 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/clientRegistration/ClientRegistrationMemoryRepository.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.clientRegistration; 2 | 3 | import java.util.Map; 4 | 5 | import lombok.RequiredArgsConstructor; 6 | 7 | @RequiredArgsConstructor 8 | public class ClientRegistrationMemoryRepository implements ClientRegistrationRepository { 9 | 10 | private final Map clientRegistrations; 11 | 12 | public OAuthClientRegistration findByProviderName(String name) { 13 | return clientRegistrations.get(name); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/clientRegistration/ClientRegistrationRepository.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.clientRegistration; 2 | 3 | public interface ClientRegistrationRepository { 4 | 5 | OAuthClientRegistration findByProviderName(String name); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/clientRegistration/OAuthClientRegistration.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.clientRegistration; 2 | 3 | import com.waterfogsw.board.auth.common.property.OAuthProperties; 4 | 5 | import lombok.Builder; 6 | 7 | @Builder 8 | public record OAuthClientRegistration( 9 | String clientId, 10 | String clientSecret, 11 | String redirectUrl, 12 | String tokenUrl, 13 | String userInfoUrl 14 | ) { 15 | 16 | public static OAuthClientRegistration of( 17 | OAuthProperties.Client client, 18 | OAuthProperties.Provider provider 19 | ) { 20 | return builder().clientId(client.clientId()) 21 | .clientSecret(client.clientSecret()) 22 | .redirectUrl(client.redirectUri()) 23 | .tokenUrl(provider.tokenUri()) 24 | .userInfoUrl(provider.userInfoUri()) 25 | .build(); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/clientRegistration/OAuthClientRegistrationPropertiesAdapter.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.clientRegistration; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import com.waterfogsw.board.auth.common.property.OAuthProperties; 7 | 8 | import lombok.AccessLevel; 9 | import lombok.NoArgsConstructor; 10 | 11 | @NoArgsConstructor(access = AccessLevel.PRIVATE) 12 | public class OAuthClientRegistrationPropertiesAdapter { 13 | 14 | public static Map getOauthProviders(OAuthProperties properties) { 15 | Map provider = new HashMap<>(); 16 | properties.getClients() 17 | .forEach((k, v) -> provider.put(k, getOAuthClientRegistration(k, v, properties))); 18 | return provider; 19 | } 20 | 21 | private static OAuthClientRegistration getOAuthClientRegistration( 22 | String key, 23 | OAuthProperties.Client value, 24 | OAuthProperties properties 25 | ) { 26 | Map providers = properties.getProviders(); 27 | 28 | return OAuthClientRegistration.of(value, providers.get(key)); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/controller/OAuthRestController.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.controller; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.PathVariable; 6 | import org.springframework.web.bind.annotation.PostMapping; 7 | import org.springframework.web.bind.annotation.RequestBody; 8 | import org.springframework.web.bind.annotation.RequestParam; 9 | import org.springframework.web.bind.annotation.ResponseStatus; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import com.waterfogsw.board.auth.oauth.dto.LoginResponse; 13 | import com.waterfogsw.board.auth.oauth.dto.TokenRefreshRequest; 14 | import com.waterfogsw.board.auth.oauth.dto.TokenRefreshResponse; 15 | import com.waterfogsw.board.auth.oauth.service.OAuthService; 16 | 17 | import lombok.RequiredArgsConstructor; 18 | 19 | @RestController 20 | @RequiredArgsConstructor 21 | public class OAuthRestController { 22 | 23 | private final OAuthService oAuthService; 24 | 25 | @GetMapping("/login/oauth/{provider}") 26 | @ResponseStatus(HttpStatus.OK) 27 | public LoginResponse login( 28 | @PathVariable String provider, 29 | @RequestParam String code 30 | ) { 31 | return oAuthService.login(provider, code); 32 | } 33 | 34 | @PostMapping("/auth/refresh") 35 | @ResponseStatus(HttpStatus.OK) 36 | public TokenRefreshResponse refresh(@RequestBody TokenRefreshRequest request) { 37 | return oAuthService.refresh(request); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/dto/LoginResponse.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.dto; 2 | 3 | import com.waterfogsw.board.core.user.domain.Role; 4 | 5 | import lombok.Builder; 6 | 7 | @Builder 8 | public record LoginResponse( 9 | long id, 10 | String email, 11 | String name, 12 | String imageUrl, 13 | Role role, 14 | String tokenType, 15 | String accessToken, 16 | String refreshToken 17 | ) { 18 | 19 | } 20 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/dto/OAuthTokenResponse.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.dto; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | public record OAuthTokenResponse( 6 | @JsonProperty("access_token") 7 | String accessToken, 8 | 9 | String scope, 10 | 11 | @JsonProperty("token_type") 12 | String tokenType 13 | ) { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/dto/OAuthUserProfile.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.dto; 2 | 3 | import lombok.Builder; 4 | 5 | @Builder 6 | public record OAuthUserProfile( 7 | String oauthId, 8 | String email, 9 | String name, 10 | String imageUrl 11 | ) { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/dto/TokenRefreshRequest.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.dto; 2 | 3 | public record TokenRefreshRequest( 4 | String accessToken, 5 | String refreshToken 6 | ) { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/dto/TokenRefreshResponse.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.dto; 2 | 3 | import com.waterfogsw.board.core.user.domain.Role; 4 | 5 | import lombok.Builder; 6 | 7 | @Builder 8 | public record TokenRefreshResponse( 9 | long id, 10 | String email, 11 | String name, 12 | String imageUrl, 13 | Role role, 14 | String tokenType, 15 | String accessToken 16 | ) { 17 | 18 | } 19 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/service/OAuthAuthorizationServerClient.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.service; 2 | 3 | import java.nio.charset.StandardCharsets; 4 | import java.util.Collections; 5 | import java.util.Map; 6 | 7 | import org.springframework.core.ParameterizedTypeReference; 8 | import org.springframework.http.MediaType; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.util.LinkedMultiValueMap; 11 | import org.springframework.util.MultiValueMap; 12 | import org.springframework.web.reactive.function.client.WebClient; 13 | 14 | import com.waterfogsw.board.auth.oauth.clientRegistration.OAuthClientRegistration; 15 | import com.waterfogsw.board.auth.oauth.dto.OAuthTokenResponse; 16 | 17 | @Component 18 | public class OAuthAuthorizationServerClient { 19 | 20 | public OAuthTokenResponse getToken( 21 | String code, 22 | OAuthClientRegistration registration 23 | ) { 24 | return WebClient.create() 25 | .post() 26 | .uri(registration.tokenUrl()) 27 | .headers(header -> { 28 | header.setBasicAuth(registration.clientId(), registration.clientSecret()); 29 | header.setContentType(MediaType.APPLICATION_FORM_URLENCODED); 30 | header.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); 31 | header.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8)); 32 | }) 33 | .bodyValue(tokenRequest(code, registration)) 34 | .retrieve() 35 | .bodyToMono(OAuthTokenResponse.class) 36 | .block(); 37 | } 38 | 39 | public Map getUserAttributes( 40 | OAuthClientRegistration registration, 41 | OAuthTokenResponse tokenResponse 42 | ) { 43 | return WebClient.create() 44 | .get() 45 | .uri(registration.userInfoUrl()) 46 | .headers(header -> header.setBearerAuth(tokenResponse.accessToken())) 47 | .retrieve() 48 | .bodyToMono(new ParameterizedTypeReference>() { 49 | }) 50 | .block(); 51 | } 52 | 53 | private MultiValueMap tokenRequest( 54 | String code, 55 | OAuthClientRegistration registration 56 | ) { 57 | MultiValueMap formData = new LinkedMultiValueMap<>(); 58 | formData.add("code", code); 59 | formData.add("grant_type", "authorization_code"); 60 | formData.add("redirect_uri", registration.redirectUrl()); 61 | return formData; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/service/OAuthService.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.service; 2 | 3 | import java.util.Map; 4 | import java.util.UUID; 5 | 6 | import org.springframework.data.redis.core.StringRedisTemplate; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.waterfogsw.board.auth.jwt.JwtTokenProvider; 10 | import com.waterfogsw.board.auth.oauth.clientRegistration.ClientRegistrationRepository; 11 | import com.waterfogsw.board.auth.oauth.clientRegistration.OAuthClientRegistration; 12 | import com.waterfogsw.board.auth.oauth.dto.LoginResponse; 13 | import com.waterfogsw.board.auth.oauth.dto.OAuthTokenResponse; 14 | import com.waterfogsw.board.auth.oauth.dto.OAuthUserProfile; 15 | import com.waterfogsw.board.auth.oauth.dto.TokenRefreshRequest; 16 | import com.waterfogsw.board.auth.oauth.dto.TokenRefreshResponse; 17 | import com.waterfogsw.board.auth.oauth.userProfile.OAuthUserProfileExtractorFactory; 18 | import com.waterfogsw.board.auth.oauth.userProfile.extractorStrategy.OAuthUserProfileExtractor; 19 | import com.waterfogsw.board.core.user.domain.Role; 20 | import com.waterfogsw.board.core.user.domain.User; 21 | import com.waterfogsw.board.core.user.repository.UserRepository; 22 | 23 | import io.jsonwebtoken.JwtException; 24 | import lombok.RequiredArgsConstructor; 25 | 26 | @Service 27 | @RequiredArgsConstructor 28 | public class OAuthService { 29 | 30 | private final UserRepository userRepository; 31 | private final JwtTokenProvider jwtTokenProvider; 32 | private final StringRedisTemplate redisTemplate; 33 | private final ClientRegistrationRepository clientRegistrationRepository; 34 | private final OAuthAuthorizationServerClient oAuthAuthorizationServerClient; 35 | private final OAuthUserProfileExtractorFactory oAuthUserProfileExtractorFactory; 36 | 37 | private static final String LOGIN_TOKEN_TYPE = "Bearer"; 38 | 39 | public LoginResponse login( 40 | String provider, 41 | String code 42 | ) { 43 | OAuthClientRegistration registration = clientRegistrationRepository.findByProviderName(provider); 44 | 45 | OAuthTokenResponse tokenResponse = oAuthAuthorizationServerClient.getToken(code, registration); 46 | 47 | OAuthUserProfile userProfile = getUserProfile(provider, tokenResponse, registration); 48 | 49 | User user = getUser(userProfile); 50 | 51 | String accessToken = jwtTokenProvider.createAccessToken(user); 52 | 53 | UUID uuid = UUID.randomUUID(); 54 | String refreshToken = jwtTokenProvider.createRefreshToken(uuid.toString()); 55 | 56 | redisTemplate.opsForValue() 57 | .set(uuid.toString(), refreshToken); 58 | 59 | return LoginResponse.builder() 60 | .id(user.getId()) 61 | .name(user.getName()) 62 | .email(user.getEmail()) 63 | .imageUrl(user.getImageUrl()) 64 | .role(user.getRole()) 65 | .tokenType(LOGIN_TOKEN_TYPE) 66 | .accessToken(accessToken) 67 | .refreshToken(refreshToken) 68 | .build(); 69 | } 70 | 71 | public TokenRefreshResponse refresh(TokenRefreshRequest request) { 72 | String refreshTokenId = jwtTokenProvider.getPayload(request.refreshToken()); 73 | if (redisTemplate.opsForValue() 74 | .get(refreshTokenId) == null) { 75 | throw new JwtException("Refresh token not found"); 76 | } 77 | 78 | long tokenUserId = Long.parseLong(jwtTokenProvider.getPayload(request.accessToken())); 79 | 80 | User user = userRepository.findById(tokenUserId) 81 | .orElseThrow(() -> new RuntimeException("User not found")); 82 | 83 | String accessToken = jwtTokenProvider.createAccessToken(user); 84 | 85 | return TokenRefreshResponse.builder() 86 | .id(user.getId()) 87 | .name(user.getName()) 88 | .email(user.getEmail()) 89 | .imageUrl(user.getImageUrl()) 90 | .role(user.getRole()) 91 | .tokenType(LOGIN_TOKEN_TYPE) 92 | .accessToken(accessToken) 93 | .build(); 94 | } 95 | 96 | private OAuthUserProfile getUserProfile( 97 | String provider, 98 | OAuthTokenResponse tokenResponse, 99 | OAuthClientRegistration registration 100 | ) { 101 | Map userAttributes = oAuthAuthorizationServerClient.getUserAttributes(registration, tokenResponse); 102 | 103 | OAuthUserProfileExtractor extractor = oAuthUserProfileExtractorFactory.getExtractor(provider); 104 | 105 | return extractor.extract(userAttributes); 106 | } 107 | 108 | private User getUser(OAuthUserProfile userProfile) { 109 | return userRepository.findByOauthId(userProfile.oauthId()) 110 | .map(user -> updateUser(user, userProfile)) 111 | .orElseGet(() -> createUser(userProfile)); 112 | } 113 | 114 | private User createUser(OAuthUserProfile userProfile) { 115 | User user = User.builder() 116 | .oauthId(userProfile.oauthId()) 117 | .email(userProfile.email()) 118 | .name(userProfile.name()) 119 | .imageUrl(userProfile.imageUrl()) 120 | .role(Role.USER) 121 | .build(); 122 | return userRepository.save(user); 123 | } 124 | 125 | private User updateUser( 126 | User user, 127 | OAuthUserProfile userProfile 128 | ) { 129 | return user.update(userProfile.email(), userProfile.name(), userProfile.imageUrl()); 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/userProfile/OAuthUserProfile.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.userProfile; 2 | 3 | import lombok.Builder; 4 | 5 | @Builder 6 | public record OAuthUserProfile( 7 | String email, 8 | String name, 9 | String imageUrl, 10 | String oauthId 11 | ) { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/userProfile/OAuthUserProfileExtractorFactory.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.userProfile; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | import org.springframework.stereotype.Component; 8 | 9 | import com.waterfogsw.board.auth.oauth.userProfile.extractorStrategy.OAuthUserProfileExtractor; 10 | 11 | @Component 12 | public class OAuthUserProfileExtractorFactory { 13 | 14 | private final Map extractors; 15 | 16 | public OAuthUserProfileExtractorFactory(Set extractorSet) { 17 | extractors = new HashMap<>(); 18 | initExtractors(extractorSet); 19 | } 20 | 21 | public OAuthUserProfileExtractor getExtractor(String provider) { 22 | return extractors.get(provider); 23 | } 24 | 25 | private void initExtractors(Set extractorSet) { 26 | extractorSet.forEach(extractor -> extractors.put(extractor.getExtractorName(), extractor)); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/userProfile/extractorStrategy/GoogleOAuthUserProfileExtractor.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.userProfile.extractorStrategy; 2 | 3 | import java.util.Map; 4 | 5 | import org.springframework.stereotype.Component; 6 | 7 | import com.waterfogsw.board.auth.oauth.dto.OAuthUserProfile; 8 | 9 | @Component 10 | public class GoogleOAuthUserProfileExtractor implements OAuthUserProfileExtractor { 11 | 12 | private static final String PROVIDER_NAME = "google"; 13 | 14 | @Override 15 | public OAuthUserProfile extract(Map attributes) { 16 | return OAuthUserProfile.builder() 17 | .oauthId((String)attributes.get("sub")) 18 | .email((String)attributes.get("email")) 19 | .name((String)attributes.get("name")) 20 | .imageUrl((String)attributes.get("picture")) 21 | .build(); 22 | } 23 | 24 | @Override 25 | public String getExtractorName() { 26 | return PROVIDER_NAME; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /board-auth-server/src/main/java/com/waterfogsw/board/auth/oauth/userProfile/extractorStrategy/OAuthUserProfileExtractor.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.auth.oauth.userProfile.extractorStrategy; 2 | 3 | import java.util.Map; 4 | 5 | import com.waterfogsw.board.auth.oauth.dto.OAuthUserProfile; 6 | 7 | public interface OAuthUserProfileExtractor { 8 | 9 | OAuthUserProfile extract(Map attributes); 10 | 11 | String getExtractorName(); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /board-auth-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | 4 | spring: 5 | jpa: 6 | database: mysql 7 | hibernate: 8 | ddl-auto: update 9 | open-in-view: false 10 | properties: 11 | dialect: org.hibernate.dialect.MySQL8Dialect 12 | datasource: 13 | url: ${datasource_url} 14 | username: ${datasource_username} 15 | password: ${datasource_password} 16 | 17 | redis: 18 | master: 19 | host: ${redis_master_host} 20 | port: ${redis_master_port} 21 | slave: 22 | host: ${redis_slave_host} 23 | port: ${redis_slave_port} 24 | 25 | jwt: 26 | access-token-header: AccessToken 27 | refresh-token-header: RefreshToken 28 | issuer: waterfogsw 29 | prefix: bearer 30 | client-secret: ${token_client_secret} 31 | access-token-expiry-seconds: 1800000 32 | refresh-token-expiry-seconds: 1209600000 33 | 34 | oauth2: 35 | clients: 36 | google: 37 | client-id: 843006986889-onjkm3cerb7n62vktp76mre0tk7cpoqs.apps.googleusercontent.com 38 | client-secret: ${google_client_secret} 39 | redirect-uri: http://localhost:8080/redirect/oauth 40 | providers: 41 | google: 42 | token-uri: https://www.googleapis.com/oauth2/v4/token 43 | user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo 44 | -------------------------------------------------------------------------------- /board-auth-server/src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Google 5 | Login
6 | 7 | 8 | -------------------------------------------------------------------------------- /board-chat-server/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:17-jdk 2 | ARG JAR_FILE="build/libs/*.jar" 3 | COPY ${JAR_FILE} board-chat-server.jar 4 | ENTRYPOINT ["java", "-jar","/board-chat-server.jar"] 5 | -------------------------------------------------------------------------------- /board-chat-server/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | kotlin("jvm") version "1.6.21" 5 | kotlin("plugin.spring") version "1.6.21" 6 | } 7 | 8 | dependencies { 9 | implementation(project(":board-core")) 10 | 11 | //web 12 | implementation("org.springframework.boot:spring-boot-starter-web") 13 | 14 | //mysql 15 | runtimeOnly("mysql:mysql-connector-java") 16 | 17 | //kotlin 18 | implementation("com.fasterxml.jackson.module:jackson-module-kotlin") 19 | implementation("org.jetbrains.kotlin:kotlin-reflect") 20 | implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") 21 | } 22 | 23 | tasks.withType { 24 | kotlinOptions { 25 | freeCompilerArgs = listOf("-Xjsr305=strict") 26 | jvmTarget = "17" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /board-chat-server/src/main/java/com/waterfogsw/board/BoardChatApplication.kt: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | 6 | @SpringBootApplication 7 | class BoardChatApplication 8 | 9 | fun main(args: Array) { 10 | runApplication(*args) 11 | } 12 | -------------------------------------------------------------------------------- /board-chat-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8082 3 | 4 | spring: 5 | jpa: 6 | database: mysql 7 | hibernate: 8 | ddl-auto: update 9 | open-in-view: false 10 | properties: 11 | dialect: org.hibernate.dialect.MySQL8Dialect 12 | datasource: 13 | url: ${datasource_url} 14 | username: ${datasource_username} 15 | password: ${datasource_password} 16 | 17 | jwt: 18 | client-secret: ${token_client_secret} 19 | -------------------------------------------------------------------------------- /board-core/build.gradle: -------------------------------------------------------------------------------- 1 | bootJar { enabled = false } 2 | jar { enabled = true } 3 | 4 | buildscript { 5 | ext { 6 | queryDslVersion = "5.0.0" 7 | } 8 | } 9 | 10 | dependencies { 11 | // QueryDSL 12 | implementation "com.querydsl:querydsl-jpa:${queryDslVersion}" 13 | 14 | annotationProcessor("javax.persistence:javax.persistence-api") 15 | annotationProcessor("javax.annotation:javax.annotation-api") 16 | annotationProcessor("com.querydsl:querydsl-apt:${queryDslVersion}:jpa") 17 | 18 | // TestContainers 19 | testRuntimeOnly('com.mysql:mysql-connector-j:8.0.31') 20 | testImplementation("org.testcontainers:mysql:1.17.6") 21 | testImplementation("org.testcontainers:junit-jupiter:1.17.6") 22 | } 23 | 24 | // QueryDSL 25 | sourceSets { 26 | main { 27 | java { 28 | srcDirs = ["$projectDir/src/main/java", "$projectDir/build/generated"] 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/board/domain/Board.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.board.domain; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.FetchType; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.persistence.ManyToOne; 10 | 11 | import com.waterfogsw.board.core.common.entity.BaseTime; 12 | import com.waterfogsw.board.core.user.domain.User; 13 | 14 | import lombok.AccessLevel; 15 | import lombok.Builder; 16 | import lombok.Getter; 17 | import lombok.NoArgsConstructor; 18 | 19 | @Getter 20 | @Entity 21 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 22 | public class Board extends BaseTime { 23 | 24 | @Id 25 | @GeneratedValue(strategy = GenerationType.IDENTITY) 26 | private Long id; 27 | 28 | @Column(length = 20) 29 | private String title; 30 | 31 | @Column(length = 200) 32 | private String description; 33 | 34 | @ManyToOne(fetch = FetchType.LAZY) 35 | private User owner; 36 | 37 | @Builder 38 | public Board( 39 | String title, 40 | String description, 41 | User owner 42 | ) { 43 | this.title = title; 44 | this.description = description; 45 | this.owner = owner; 46 | } 47 | 48 | public void update( 49 | String title, 50 | String description 51 | ) { 52 | this.title = title; 53 | this.description = description; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/board/repository/BoardQueryRepository.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.board.repository; 2 | 3 | import static com.waterfogsw.board.core.board.domain.QBoard.*; 4 | import static com.waterfogsw.board.core.user.domain.QUser.*; 5 | import static org.springframework.util.StringUtils.*; 6 | 7 | import java.util.List; 8 | import java.util.Optional; 9 | 10 | import org.springframework.lang.Nullable; 11 | import org.springframework.stereotype.Repository; 12 | 13 | import com.querydsl.core.types.dsl.BooleanExpression; 14 | import com.querydsl.jpa.impl.JPAQueryFactory; 15 | import com.waterfogsw.board.core.board.domain.Board; 16 | 17 | import lombok.RequiredArgsConstructor; 18 | 19 | @Repository 20 | @RequiredArgsConstructor 21 | public class BoardQueryRepository { 22 | 23 | private final JPAQueryFactory jpaQueryFactory; 24 | 25 | public Optional getDetail(long id) { 26 | Board result = jpaQueryFactory.selectFrom(board) 27 | .where(board.id.eq(id)) 28 | .join(board.owner, user) 29 | .fetchJoin() 30 | .distinct() 31 | .fetchOne(); 32 | 33 | return Optional.ofNullable(result); 34 | } 35 | 36 | public List getSliceOfBoard( 37 | @Nullable 38 | Long id, 39 | int size, 40 | @Nullable 41 | String keyword 42 | ) { 43 | return jpaQueryFactory.selectFrom(board) 44 | .where(ltBoardId(id), search(keyword)) 45 | .join(board.owner, user) 46 | .fetchJoin() 47 | .orderBy(board.id.desc()) 48 | .limit(size) 49 | .fetch(); 50 | } 51 | 52 | @SuppressWarnings("all") 53 | private BooleanExpression search(String keyword) { 54 | return hasText(keyword) ? containsTitle(keyword).or(containsDescription(keyword)) : null; 55 | } 56 | 57 | private BooleanExpression containsTitle(@Nullable String title) { 58 | return hasText(title) ? board.title.contains(title) : null; 59 | } 60 | 61 | private BooleanExpression containsDescription(@Nullable String description) { 62 | return hasText(description) ? board.description.contains(description) : null; 63 | } 64 | 65 | private BooleanExpression ltBoardId(@Nullable Long id) { 66 | return id == null ? null : board.id.lt(id); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/board/repository/BoardRepository.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.board.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import com.waterfogsw.board.core.board.domain.Board; 6 | 7 | public interface BoardRepository extends JpaRepository { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/common/entity/BaseTime.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.common.entity; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | import javax.persistence.EntityListeners; 6 | import javax.persistence.MappedSuperclass; 7 | 8 | import org.springframework.data.annotation.CreatedDate; 9 | import org.springframework.data.annotation.LastModifiedDate; 10 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 11 | 12 | import lombok.Getter; 13 | 14 | @Getter 15 | @MappedSuperclass 16 | @EntityListeners(AuditingEntityListener.class) 17 | public class BaseTime { 18 | 19 | @CreatedDate 20 | private LocalDateTime createdAt; 21 | 22 | @LastModifiedDate 23 | private LocalDateTime updatedAt; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/common/exception/AuthenticationException.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.common.exception; 2 | 3 | public class AuthenticationException extends RuntimeException { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/common/exception/NotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.common.exception; 2 | 3 | public class NotFoundException extends RuntimeException { 4 | 5 | public NotFoundException() { 6 | super(); 7 | } 8 | 9 | public NotFoundException(String message) { 10 | super(message); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/config/JpaConfig.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 5 | 6 | @Configuration 7 | @EnableJpaAuditing 8 | public class JpaConfig { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/config/QueryDslConfig.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.config; 2 | 3 | import javax.persistence.EntityManager; 4 | import javax.persistence.PersistenceContext; 5 | 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | import com.querydsl.jpa.impl.JPAQueryFactory; 10 | 11 | @Configuration 12 | public class QueryDslConfig { 13 | 14 | @PersistenceContext 15 | private EntityManager entityManager; 16 | 17 | @Bean 18 | public JPAQueryFactory jpaQueryFactory() { 19 | return new JPAQueryFactory(entityManager); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/post/entity/Post.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.post.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.FetchType; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.GenerationType; 7 | import javax.persistence.Id; 8 | import javax.persistence.ManyToOne; 9 | 10 | import com.waterfogsw.board.core.board.domain.Board; 11 | import com.waterfogsw.board.core.common.entity.BaseTime; 12 | import com.waterfogsw.board.core.user.domain.User; 13 | 14 | import lombok.AccessLevel; 15 | import lombok.Builder; 16 | import lombok.Getter; 17 | import lombok.NoArgsConstructor; 18 | 19 | @Getter 20 | @Entity 21 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 22 | public class Post extends BaseTime { 23 | 24 | @Id 25 | @GeneratedValue(strategy = GenerationType.IDENTITY) 26 | private Long id; 27 | 28 | private String title; 29 | 30 | private String content; 31 | 32 | @ManyToOne(fetch = FetchType.LAZY) 33 | private Board board; 34 | 35 | @ManyToOne(fetch = FetchType.LAZY) 36 | private User writer; 37 | 38 | @Builder 39 | public Post( 40 | String title, 41 | String content, 42 | Board board, 43 | User writer 44 | ) { 45 | this.title = title; 46 | this.content = content; 47 | this.board = board; 48 | this.writer = writer; 49 | } 50 | 51 | public void update( 52 | String title, 53 | String content 54 | ) { 55 | this.title = title; 56 | this.content = content; 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/post/repository/PostQueryRepository.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.post.repository; 2 | 3 | import static com.waterfogsw.board.core.board.domain.QBoard.*; 4 | import static com.waterfogsw.board.core.post.entity.QPost.*; 5 | import static com.waterfogsw.board.core.user.domain.QUser.*; 6 | import static org.springframework.util.StringUtils.*; 7 | 8 | import java.util.List; 9 | import java.util.Optional; 10 | 11 | import javax.annotation.Nullable; 12 | 13 | import org.springframework.stereotype.Repository; 14 | 15 | import com.querydsl.core.types.dsl.BooleanExpression; 16 | import com.querydsl.jpa.impl.JPAQueryFactory; 17 | import com.waterfogsw.board.core.post.entity.Post; 18 | 19 | import lombok.RequiredArgsConstructor; 20 | 21 | @Repository 22 | @RequiredArgsConstructor 23 | public class PostQueryRepository { 24 | 25 | private final JPAQueryFactory jpaQueryFactory; 26 | 27 | public Optional getDetail(long id) { 28 | Post result = jpaQueryFactory.selectFrom(post) 29 | .where(post.id.eq(id)) 30 | .join(post.board, board) 31 | .fetchJoin() 32 | .join(post.writer, user) 33 | .fetchJoin() 34 | .distinct() 35 | .fetchOne(); 36 | 37 | return Optional.ofNullable(result); 38 | } 39 | 40 | public List getSlice( 41 | @Nullable 42 | Long id, 43 | long boardId, 44 | int size, 45 | @Nullable 46 | String keyword 47 | ) { 48 | return jpaQueryFactory.selectFrom(post) 49 | .where(ltPostId(id), search(keyword)) 50 | .join(post.writer, user) 51 | .fetchJoin() 52 | .join(post.board, board) 53 | .fetchJoin() 54 | .where(post.board.id.eq(boardId)) 55 | .orderBy(post.id.desc()) 56 | .limit(size) 57 | .fetch(); 58 | } 59 | 60 | @SuppressWarnings("all") 61 | private BooleanExpression search(String keyword) { 62 | return hasText(keyword) ? containsTitle(keyword).or(containsContent(keyword)) : null; 63 | } 64 | 65 | private BooleanExpression containsTitle(@Nullable String title) { 66 | return hasText(title) ? post.title.contains(title) : null; 67 | } 68 | 69 | private BooleanExpression containsContent(@Nullable String contents) { 70 | return hasText(contents) ? post.content.contains(contents) : null; 71 | } 72 | 73 | private BooleanExpression ltPostId(@Nullable Long id) { 74 | return id == null ? null : post.id.lt(id); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/post/repository/PostRepository.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.post.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import com.waterfogsw.board.core.post.entity.Post; 6 | 7 | public interface PostRepository extends JpaRepository { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/user/domain/Role.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.user.domain; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | 5 | @RequiredArgsConstructor 6 | public enum Role { 7 | 8 | ADMIN(1), USER(2), GUEST(3); 9 | 10 | private final int priority; 11 | 12 | public boolean hasAuthority(Role required) { 13 | return required.priority >= this.priority; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/user/domain/User.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.user.domain; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.EnumType; 6 | import javax.persistence.Enumerated; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | import javax.persistence.Table; 11 | 12 | import com.sun.istack.NotNull; 13 | import com.waterfogsw.board.core.common.entity.BaseTime; 14 | 15 | import lombok.AccessLevel; 16 | import lombok.Builder; 17 | import lombok.Getter; 18 | import lombok.NoArgsConstructor; 19 | 20 | @Getter 21 | @Entity 22 | @Table(name = "`user`") 23 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 24 | public class User extends BaseTime { 25 | 26 | @Id 27 | @GeneratedValue(strategy = GenerationType.IDENTITY) 28 | private Long id; 29 | 30 | private String email; 31 | 32 | private String name; 33 | 34 | private String imageUrl; 35 | 36 | @NotNull 37 | @Column(unique = true) 38 | private String oauthId; 39 | 40 | @Enumerated(EnumType.STRING) 41 | private Role role; 42 | 43 | @Builder 44 | public User( 45 | String email, 46 | String name, 47 | String imageUrl, 48 | String oauthId, 49 | Role role 50 | ) { 51 | this.email = email; 52 | this.name = name; 53 | this.imageUrl = imageUrl; 54 | this.oauthId = oauthId; 55 | this.role = role; 56 | } 57 | 58 | public User update( 59 | String email, 60 | String name, 61 | String imageUrl 62 | ) { 63 | this.email = email; 64 | this.name = name; 65 | this.imageUrl = imageUrl; 66 | return this; 67 | } 68 | 69 | @Override 70 | public boolean equals(Object o) { 71 | if (this == o) 72 | return true; 73 | if (o == null || getClass() != o.getClass()) 74 | return false; 75 | User user = (User)o; 76 | return id.equals(user.id); 77 | } 78 | 79 | @Override 80 | public int hashCode() { 81 | return id.hashCode(); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /board-core/src/main/java/com/waterfogsw/board/core/user/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.user.repository; 2 | 3 | import java.util.Optional; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | 7 | import com.waterfogsw.board.core.user.domain.User; 8 | 9 | public interface UserRepository extends JpaRepository { 10 | 11 | Optional findByOauthId(String oauthId); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /board-core/src/test/java/com/waterfogsw/board/core/TestConfig.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | 5 | @SpringBootApplication 6 | public class TestConfig { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /board-core/src/test/java/com/waterfogsw/board/core/board/repository/BoardQueryRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.board.repository; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.assertj.core.api.Assertions; 7 | import org.junit.jupiter.api.AfterEach; 8 | import org.junit.jupiter.api.DisplayName; 9 | import org.junit.jupiter.api.Nested; 10 | import org.junit.jupiter.api.Test; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | 13 | import com.waterfogsw.board.core.board.domain.Board; 14 | import com.waterfogsw.board.core.user.domain.User; 15 | import com.waterfogsw.board.core.user.repository.UserRepository; 16 | import com.waterfogsw.board.core.util.BaseRepositoryTest; 17 | import com.waterfogsw.board.core.util.TestDataGenerator; 18 | 19 | class BoardQueryRepositoryTest extends BaseRepositoryTest { 20 | 21 | @Autowired 22 | UserRepository userRepository; 23 | 24 | @Autowired 25 | BoardRepository boardRepository; 26 | 27 | @Autowired 28 | BoardQueryRepository boardQueryRepository; 29 | 30 | @AfterEach 31 | void tearDown() { 32 | boardRepository.deleteAllInBatch(); 33 | userRepository.deleteAllInBatch(); 34 | } 35 | 36 | @Nested 37 | @DisplayName("getDetail 메서드는") 38 | class DescribeGetDetail { 39 | 40 | @Nested 41 | @DisplayName("존재하지 않는 id를 조회하면") 42 | class ContextWithNotExistsId { 43 | 44 | @Test 45 | @DisplayName("빈 Optional값을 반환한다") 46 | void ItReturnEmptyOptionalValue() { 47 | //when, then 48 | Optional foundBoard = boardQueryRepository.getDetail(-1L); 49 | 50 | Assertions.assertThat(foundBoard.isEmpty()) 51 | .isTrue(); 52 | } 53 | 54 | } 55 | 56 | @Nested 57 | @DisplayName("존재하는 id를 조회하면") 58 | class ContextWithExitsId { 59 | 60 | @Test 61 | @DisplayName("엔티티가 들어있는 Optional 값을 반환한다") 62 | void ItReturnEntityAsOptionalValue() { 63 | //given 64 | User user = TestDataGenerator.getUser("alisong", "alisong@naver.com"); 65 | userRepository.saveAndFlush(user); 66 | 67 | Board board = TestDataGenerator.getBoard("meet", "direct", user); 68 | boardRepository.saveAndFlush(board); 69 | 70 | entityManager.clear(); 71 | 72 | //when, then 73 | Optional foundBoard = boardQueryRepository.getDetail(board.getId()); 74 | Assertions.assertThat(foundBoard.isPresent()) 75 | .isTrue(); 76 | } 77 | 78 | } 79 | 80 | } 81 | 82 | @Nested 83 | @DisplayName("getSliceBoard 메서드는") 84 | class DescribeGetSliceBoard { 85 | 86 | @Nested 87 | @DisplayName("null id값이 전달되면") 88 | class ContextWithNullId { 89 | 90 | @Test 91 | @DisplayName("가장 마지막 id부터 역순으로 size 만큼의 Board를 반환한다") 92 | void ItReturnBoardOfSizesInReverseOrderFromLastId() { 93 | //given 94 | int totalBoardCount = 20; 95 | int sliceSize = 10; 96 | User user = TestDataGenerator.getRandomUsers(1) 97 | .get(0); 98 | userRepository.saveAndFlush(user); 99 | 100 | List boards = TestDataGenerator.getRandomBoards(totalBoardCount, user); 101 | boardRepository.saveAllAndFlush(boards); 102 | 103 | entityManager.clear(); 104 | 105 | //when 106 | List sliceOfBoard = boardQueryRepository.getSliceOfBoard(null, sliceSize, null); 107 | 108 | //then 109 | Assertions.assertThat(sliceOfBoard.size()) 110 | .isEqualTo(sliceSize); 111 | } 112 | 113 | } 114 | 115 | @Nested 116 | @DisplayName("id값이 전달되면") 117 | class ContextWithId { 118 | 119 | @Test 120 | @DisplayName("해당 id보다 작은값부터 역순으로 size 만큼의 Board를 반환한다") 121 | void ItReturnBoardOfSizesInReverseOrderFromId() { 122 | //given 123 | int totalBoardCount = 20; 124 | int sliceSize = 10; 125 | User user = TestDataGenerator.getRandomUsers(1) 126 | .get(0); 127 | userRepository.saveAndFlush(user); 128 | 129 | List boards = TestDataGenerator.getRandomBoards(totalBoardCount, user); 130 | boardRepository.saveAllAndFlush(boards); 131 | 132 | long targetBoardId = boards.get(boards.size() - 1) 133 | .getId(); 134 | 135 | entityManager.clear(); 136 | 137 | //when 138 | List sliceOfBoard = boardQueryRepository.getSliceOfBoard(targetBoardId, sliceSize, null); 139 | 140 | //then 141 | Assertions.assertThat(sliceOfBoard.size()) 142 | .isEqualTo(sliceSize); 143 | 144 | Board firstSelectedBoard = sliceOfBoard.get(0); 145 | Assertions.assertThat(firstSelectedBoard.getId()) 146 | .isEqualTo(targetBoardId - 1); 147 | } 148 | 149 | } 150 | 151 | @Nested 152 | @DisplayName("keyword 값이 전달되면") 153 | class ContextWithKeyword { 154 | 155 | @Test 156 | @DisplayName("해당 keyword가 title에 포함되어 있는 Board를 반환한다") 157 | void ItReturnBoardThatContainKeywordInTitle() { 158 | //given 159 | String keyword = "hello"; 160 | String title = "hello world"; 161 | 162 | int totalBoardCount = 20; 163 | int sliceSize = 10; 164 | User user = TestDataGenerator.getRandomUsers(1) 165 | .get(0); 166 | userRepository.saveAndFlush(user); 167 | 168 | Board keywordBoard = TestDataGenerator.getBoard(title, "camping", user); 169 | List boards = TestDataGenerator.getRandomBoards(totalBoardCount, user); 170 | boardRepository.saveAndFlush(keywordBoard); 171 | boardRepository.saveAllAndFlush(boards); 172 | 173 | entityManager.clear(); 174 | 175 | //when 176 | List sliceOfBoard = boardQueryRepository.getSliceOfBoard(null, sliceSize, keyword); 177 | 178 | //then 179 | Board lastBoard = sliceOfBoard.get(0); 180 | Assertions.assertThat(lastBoard.getTitle()) 181 | .isEqualTo(title); 182 | } 183 | 184 | @Test 185 | @DisplayName("해당 keyword가 description에 포함되어 있는 Board를 반환한다") 186 | void ItReturnBoardThatContainKeywordInDescription() { 187 | //given 188 | String keyword = "hello"; 189 | String description = "hello world"; 190 | 191 | int totalBoardCount = 20; 192 | int sliceSize = 10; 193 | User user = TestDataGenerator.getRandomUsers(1) 194 | .get(0); 195 | userRepository.saveAndFlush(user); 196 | 197 | Board keywordBoard = TestDataGenerator.getBoard("camping", description, user); 198 | List boards = TestDataGenerator.getRandomBoards(totalBoardCount, user); 199 | boardRepository.saveAndFlush(keywordBoard); 200 | boardRepository.saveAllAndFlush(boards); 201 | 202 | entityManager.clear(); 203 | 204 | //when 205 | List sliceOfBoard = boardQueryRepository.getSliceOfBoard(null, sliceSize, keyword); 206 | 207 | //then 208 | Board lastBoard = sliceOfBoard.get(0); 209 | Assertions.assertThat(lastBoard.getDescription()) 210 | .isEqualTo(description); 211 | } 212 | 213 | } 214 | 215 | } 216 | 217 | } 218 | -------------------------------------------------------------------------------- /board-core/src/test/java/com/waterfogsw/board/core/post/repository/PostQueryRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.post.repository; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.assertj.core.api.Assertions; 7 | import org.junit.jupiter.api.AfterEach; 8 | import org.junit.jupiter.api.DisplayName; 9 | import org.junit.jupiter.api.Nested; 10 | import org.junit.jupiter.api.Test; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | 13 | import com.waterfogsw.board.core.board.domain.Board; 14 | import com.waterfogsw.board.core.board.repository.BoardRepository; 15 | import com.waterfogsw.board.core.post.entity.Post; 16 | import com.waterfogsw.board.core.user.domain.User; 17 | import com.waterfogsw.board.core.user.repository.UserRepository; 18 | import com.waterfogsw.board.core.util.BaseRepositoryTest; 19 | import com.waterfogsw.board.core.util.TestDataGenerator; 20 | 21 | class PostQueryRepositoryTest extends BaseRepositoryTest { 22 | 23 | @Autowired 24 | UserRepository userRepository; 25 | 26 | @Autowired 27 | BoardRepository boardRepository; 28 | 29 | @Autowired 30 | PostRepository postRepository; 31 | 32 | @Autowired 33 | PostQueryRepository postQueryRepository; 34 | 35 | @AfterEach 36 | void tearDown() { 37 | postRepository.deleteAllInBatch(); 38 | boardRepository.deleteAllInBatch(); 39 | userRepository.deleteAllInBatch(); 40 | } 41 | 42 | @Nested 43 | @DisplayName("getDetail 메서드는") 44 | class DescribeGetDetail { 45 | 46 | @Nested 47 | @DisplayName("존재하지 않는 id를 조회하면") 48 | class ContextWithNotExistsId { 49 | 50 | @Test 51 | @DisplayName("빈 Optional값을 반환한다") 52 | void ItReturnEmptyOptionalValue() { 53 | //when, then 54 | Optional foundPost = postQueryRepository.getDetail(-1L); 55 | 56 | Assertions.assertThat(foundPost.isEmpty()) 57 | .isTrue(); 58 | } 59 | 60 | } 61 | 62 | @Nested 63 | @DisplayName("존재하는 id를 조회하면") 64 | class ContextWithExitsId { 65 | 66 | @Test 67 | @DisplayName("엔티티가 들어있는 Optional 값을 반환한다") 68 | void ItReturnEntityAsOptionalValue() { 69 | //given 70 | User user = TestDataGenerator.getUser("alisong", "alisong@naver.com"); 71 | userRepository.saveAndFlush(user); 72 | 73 | Board board = TestDataGenerator.getBoard("meet", "direct", user); 74 | boardRepository.saveAndFlush(board); 75 | 76 | Post post = TestDataGenerator.getPost("hello", "world", user, board); 77 | postRepository.saveAndFlush(post); 78 | 79 | entityManager.clear(); 80 | 81 | //when, then 82 | Optional foundPost = postQueryRepository.getDetail(post.getId()); 83 | Assertions.assertThat(foundPost.isPresent()) 84 | .isTrue(); 85 | } 86 | 87 | } 88 | 89 | } 90 | 91 | @Nested 92 | @DisplayName("getSlice 메서드는") 93 | class DescribeGetSlice { 94 | 95 | @Nested 96 | @DisplayName("null id값이 전달되면") 97 | class ContextWithNullId { 98 | 99 | @Test 100 | @DisplayName("가장 마지막 id부터 역순으로 size 만큼의 Post를 반환한다") 101 | void ItReturnSizeOfPostInReverseOrderFromLastId() { 102 | //given 103 | int sliceSize = 10; 104 | User user = TestDataGenerator.getRandomUsers(1) 105 | .get(0); 106 | userRepository.saveAndFlush(user); 107 | 108 | List boards = TestDataGenerator.getRandomBoards(2, user); 109 | Board board1 = boards.get(0); 110 | Board board2 = boards.get(1); 111 | boardRepository.saveAllAndFlush(boards); 112 | 113 | List board1Posts = TestDataGenerator.getRandomPosts(10, user, board1); 114 | List board2Posts = TestDataGenerator.getRandomPosts(10, user, board2); 115 | postRepository.saveAllAndFlush(board1Posts); 116 | postRepository.saveAllAndFlush(board2Posts); 117 | 118 | entityManager.clear(); 119 | 120 | //when 121 | List slice = postQueryRepository.getSlice(null, board1.getId(), sliceSize, null); 122 | 123 | //then 124 | Assertions.assertThat(slice.size()) 125 | .isEqualTo(sliceSize); 126 | } 127 | 128 | } 129 | 130 | @Nested 131 | @DisplayName("id값이 전달되면") 132 | class ContextWithId { 133 | 134 | @Test 135 | @DisplayName("해당 id보다 작은값부터 역순으로 size 만큼의 Post를 반환한다") 136 | void ItReturnSizeOfPostInReverseOrderFromId() { 137 | //given 138 | int sliceSize = 10; 139 | User user = TestDataGenerator.getRandomUsers(1) 140 | .get(0); 141 | userRepository.saveAndFlush(user); 142 | 143 | List boards = TestDataGenerator.getRandomBoards(2, user); 144 | Board board1 = boards.get(0); 145 | Board board2 = boards.get(1); 146 | boardRepository.saveAllAndFlush(boards); 147 | 148 | List board1Posts = TestDataGenerator.getRandomPosts(20, user, board1); 149 | List board2Posts = TestDataGenerator.getRandomPosts(20, user, board2); 150 | postRepository.saveAllAndFlush(board1Posts); 151 | postRepository.saveAllAndFlush(board2Posts); 152 | 153 | long targetPostId = board1Posts.get(board1Posts.size() - 1) 154 | .getId(); 155 | entityManager.clear(); 156 | 157 | //when 158 | List slice = postQueryRepository.getSlice(targetPostId, board1.getId(), sliceSize, null); 159 | 160 | //then 161 | Assertions.assertThat(slice.size()) 162 | .isEqualTo(sliceSize); 163 | 164 | Post firstSelected = slice.get(0); 165 | Assertions.assertThat(firstSelected.getId()) 166 | .isEqualTo(targetPostId - 1); 167 | } 168 | 169 | } 170 | 171 | @Nested 172 | @DisplayName("keyword 값이 전달되면") 173 | class ContextWithKeyword { 174 | 175 | @Test 176 | @DisplayName("해당 keyword가 title에 포함되어 있는 Post 리스트를 반환한다") 177 | void ItReturnPostsThatContainKeywordInTitle() { 178 | //given 179 | String keyword = "hello"; 180 | String title = " hello world "; 181 | 182 | User user = TestDataGenerator.getUser("alisong", "alisong@naver.com"); 183 | userRepository.saveAndFlush(user); 184 | 185 | Board board = TestDataGenerator.getBoard("meet", "direct", user); 186 | boardRepository.saveAndFlush(board); 187 | 188 | Post post = TestDataGenerator.getPost(title, "world", user, board); 189 | postRepository.saveAndFlush(post); 190 | 191 | entityManager.clear(); 192 | 193 | //when 194 | List slice = postQueryRepository.getSlice(null, board.getId(), 10, keyword); 195 | 196 | //then 197 | Post found = slice.get(0); 198 | Assertions.assertThat(found.getTitle()) 199 | .isEqualTo(title); 200 | } 201 | 202 | } 203 | 204 | @Test 205 | @DisplayName("해당 keyword가 content에 포함되어 있는 Post 리스트를 반환한다") 206 | void ItReturnPostsThatContainKeywordInTitle() { 207 | //given 208 | String keyword = "hello"; 209 | String content = " hello world "; 210 | 211 | User user = TestDataGenerator.getUser("alisong", "alisong@naver.com"); 212 | userRepository.saveAndFlush(user); 213 | 214 | Board board = TestDataGenerator.getBoard("meet", "direct", user); 215 | boardRepository.saveAndFlush(board); 216 | 217 | Post post = TestDataGenerator.getPost("title", content, user, board); 218 | postRepository.saveAndFlush(post); 219 | 220 | entityManager.clear(); 221 | 222 | //when 223 | List slice = postQueryRepository.getSlice(null, board.getId(), 10, keyword); 224 | 225 | //then 226 | Post found = slice.get(0); 227 | Assertions.assertThat(found.getContent()) 228 | .isEqualTo(content); 229 | } 230 | 231 | } 232 | 233 | } 234 | -------------------------------------------------------------------------------- /board-core/src/test/java/com/waterfogsw/board/core/util/BaseRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.util; 2 | 3 | import javax.persistence.EntityManager; 4 | import javax.transaction.Transactional; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.test.context.ActiveProfiles; 9 | import org.testcontainers.containers.MySQLContainer; 10 | import org.testcontainers.utility.TestcontainersConfiguration; 11 | 12 | @SpringBootTest 13 | @Transactional 14 | @ActiveProfiles("test") 15 | public abstract class BaseRepositoryTest { 16 | 17 | @Autowired 18 | protected EntityManager entityManager; 19 | 20 | static final MySQLContainer MY_SQL_CONTAINER; 21 | 22 | static { 23 | TestcontainersConfiguration.getInstance() 24 | .updateUserConfig("testcontainers.reuse.enable", "true"); 25 | MY_SQL_CONTAINER = new MySQLContainer<>("mysql:8").withReuse(true); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /board-core/src/test/java/com/waterfogsw/board/core/util/TestDataGenerator.java: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.core.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.UUID; 6 | 7 | import com.waterfogsw.board.core.board.domain.Board; 8 | import com.waterfogsw.board.core.post.entity.Post; 9 | import com.waterfogsw.board.core.user.domain.Role; 10 | import com.waterfogsw.board.core.user.domain.User; 11 | 12 | public class TestDataGenerator { 13 | 14 | public static User getUser( 15 | String name, 16 | String email 17 | ) { 18 | return User.builder() 19 | .name(name) 20 | .email(email) 21 | .role(Role.USER) 22 | .build(); 23 | } 24 | 25 | public static Board getBoard( 26 | String title, 27 | String description, 28 | User creator 29 | ) { 30 | return Board.builder() 31 | .title(title) 32 | .description(description) 33 | .owner(creator) 34 | .build(); 35 | } 36 | 37 | public static Post getPost( 38 | String title, 39 | String content, 40 | User writer, 41 | Board board 42 | ) { 43 | return Post.builder() 44 | .title(title) 45 | .content(content) 46 | .writer(writer) 47 | .board(board) 48 | .build(); 49 | } 50 | 51 | public static List getRandomUsers(int num) { 52 | List users = new ArrayList<>(); 53 | for (int i = 0; i < num; i++) { 54 | String name = getRandomStringByUUID(10); 55 | String email = getRandomStringByUUID(10) + "@" + getRandomStringByUUID(10); 56 | users.add(getUser(name, email)); 57 | } 58 | 59 | return users; 60 | } 61 | 62 | public static List getRandomBoards( 63 | int num, 64 | User creator 65 | ) { 66 | List boards = new ArrayList<>(); 67 | for (int i = 0; i < num; i++) { 68 | String title = getRandomStringByUUID(10); 69 | String description = getRandomStringByUUID(30); 70 | boards.add(getBoard(title, description, creator)); 71 | } 72 | 73 | return boards; 74 | } 75 | 76 | public static List getRandomPosts( 77 | int num, 78 | User writer, 79 | Board board 80 | ) { 81 | List posts = new ArrayList<>(); 82 | for (int i = 0; i < num; i++) { 83 | String title = getRandomStringByUUID(10); 84 | String content = getRandomStringByUUID(30); 85 | posts.add(getPost(title, content, writer, board)); 86 | } 87 | return posts; 88 | } 89 | 90 | public static String getRandomStringByUUID(int length) { 91 | if (length > 36 || length <= 0) { 92 | throw new IllegalArgumentException(); 93 | } 94 | 95 | return UUID.randomUUID() 96 | .toString() 97 | .substring(0, length); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /board-core/src/test/kotlin/com/waterfogsw/board/util/restdoc/DocField.kt: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.util.restdoc 2 | 3 | import org.springframework.restdocs.payload.* 4 | 5 | class RestDocField( 6 | val descriptor: FieldDescriptor 7 | ) { 8 | 9 | infix fun isOptional(value: Boolean): RestDocField { 10 | if (value) descriptor.optional() 11 | return this 12 | } 13 | 14 | infix fun isIgnored(value: Boolean): RestDocField { 15 | if (value) descriptor.ignored() 16 | return this 17 | } 18 | 19 | infix fun means(value: String): RestDocField { 20 | descriptor.description(value) 21 | return this 22 | } 23 | 24 | infix fun attributes(block: RestDocField.() -> Unit): RestDocField { 25 | block() 26 | return this 27 | } 28 | } 29 | 30 | infix fun String.fieldType( 31 | docsFieldType: DocsFieldType 32 | ): RestDocField { 33 | return createField(this, docsFieldType.type) 34 | } 35 | 36 | private fun createField( 37 | value: String, 38 | type: JsonFieldType, 39 | optional: Boolean = true 40 | ): RestDocField { 41 | val descriptor = PayloadDocumentation 42 | .fieldWithPath(value) 43 | .type(type) 44 | .description("") 45 | 46 | if (optional) descriptor.optional() 47 | 48 | return RestDocField(descriptor) 49 | } 50 | 51 | fun requestBody(vararg fields: RestDocField): RequestFieldsSnippet = 52 | PayloadDocumentation.requestFields(fields.map { it.descriptor }) 53 | 54 | fun responseBody(vararg fields: RestDocField): ResponseFieldsSnippet = 55 | PayloadDocumentation.responseFields(fields.map { it.descriptor }) 56 | -------------------------------------------------------------------------------- /board-core/src/test/kotlin/com/waterfogsw/board/util/restdoc/DocFieldsType.kt: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.util.restdoc 2 | 3 | import org.springframework.restdocs.payload.JsonFieldType 4 | 5 | sealed class DocsFieldType( 6 | val type: JsonFieldType, 7 | ) 8 | 9 | object ARRAY : DocsFieldType(JsonFieldType.ARRAY) 10 | object BOOLEAN : DocsFieldType(JsonFieldType.BOOLEAN) 11 | object OBJECT : DocsFieldType(JsonFieldType.OBJECT) 12 | object NUMBER : DocsFieldType(JsonFieldType.NUMBER) 13 | object NULL : DocsFieldType(JsonFieldType.NULL) 14 | object STRING : DocsFieldType(JsonFieldType.STRING) 15 | object ANY : DocsFieldType(JsonFieldType.VARIES) 16 | object DATE : DocsFieldType(JsonFieldType.VARIES) 17 | object DATETIME : DocsFieldType(JsonFieldType.VARIES) 18 | -------------------------------------------------------------------------------- /board-core/src/test/kotlin/com/waterfogsw/board/util/restdoc/DocParam.kt: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.util.restdoc 2 | 3 | import org.springframework.restdocs.request.* 4 | 5 | class RestDocParam( 6 | val descriptor: ParameterDescriptor 7 | ) 8 | 9 | infix fun String.pathMeans( 10 | description: String 11 | ): RestDocParam { 12 | return createField(this, description) 13 | } 14 | 15 | private fun createField( 16 | value: String, 17 | description: String, 18 | optional: Boolean = true 19 | ): RestDocParam { 20 | val descriptor = RequestDocumentation 21 | .parameterWithName(value) 22 | .description(description) 23 | 24 | if (optional) descriptor.optional() 25 | 26 | return RestDocParam(descriptor) 27 | } 28 | 29 | fun pathParameters(vararg params: RestDocParam): PathParametersSnippet = 30 | RequestDocumentation.pathParameters(params.map { it.descriptor }) 31 | -------------------------------------------------------------------------------- /board-core/src/test/kotlin/com/waterfogsw/board/util/restdoc/DocUtil.kt: -------------------------------------------------------------------------------- 1 | package com.waterfogsw.board.util.restdoc 2 | 3 | import org.springframework.restdocs.RestDocumentationContextProvider 4 | import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation 5 | import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document 6 | import org.springframework.restdocs.operation.preprocess.Preprocessors 7 | import org.springframework.restdocs.snippet.Snippet 8 | import org.springframework.test.web.servlet.MockMvc 9 | import org.springframework.test.web.servlet.ResultActions 10 | import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder 11 | import org.springframework.test.web.servlet.setup.MockMvcBuilders 12 | import org.springframework.web.context.WebApplicationContext 13 | 14 | fun ResultActions.andDocument( 15 | identifier: String, 16 | vararg snippets: Snippet 17 | ): ResultActions { 18 | return andDo(document(identifier, *snippets)) 19 | } 20 | 21 | fun restDocMockMvcBuild( 22 | context: WebApplicationContext, 23 | restDocumentation: RestDocumentationContextProvider 24 | ): MockMvc { 25 | return MockMvcBuilders 26 | .webAppContextSetup(context) 27 | .apply( 28 | MockMvcRestDocumentation 29 | .documentationConfiguration(restDocumentation) 30 | .operationPreprocessors() 31 | .withRequestDefaults(Preprocessors.prettyPrint()) 32 | .withResponseDefaults(Preprocessors.prettyPrint()) 33 | ) 34 | .build() 35 | } 36 | -------------------------------------------------------------------------------- /board-core/src/test/resources/application-test.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver 4 | url: jdbc:tc:mysql:8:///TC_REUSABLE=true 5 | jpa: 6 | hibernate: 7 | ddl-auto: create-drop 8 | properties: 9 | hibernate: 10 | format_sql: true 11 | show_sql: true 12 | jdbc: 13 | lob: 14 | non_contextual_creation: true 15 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '2.7.5' 4 | id 'io.spring.dependency-management' version '1.0.15.RELEASE' 5 | id 'org.asciidoctor.jvm.convert' version '3.3.2' 6 | id 'org.jetbrains.kotlin.jvm' version '1.6.21' 7 | } 8 | 9 | allprojects { 10 | repositories { 11 | mavenCentral() 12 | } 13 | } 14 | 15 | subprojects { 16 | group 'org.waterfogsw' 17 | version '1.0-SNAPSHOT' 18 | sourceCompatibility = '17' 19 | 20 | apply plugin: 'java' 21 | apply plugin: 'idea' 22 | apply plugin: 'org.springframework.boot' 23 | apply plugin: 'io.spring.dependency-management' 24 | apply plugin: 'org.asciidoctor.jvm.convert' 25 | apply plugin: 'org.jetbrains.kotlin.jvm' 26 | 27 | configurations { 28 | compileOnly { 29 | extendsFrom annotationProcessor 30 | } 31 | asciidoctorExt 32 | } 33 | 34 | ext { 35 | set('snippetsDir', file("build/generated-snippets")) 36 | } 37 | 38 | dependencies { 39 | compileOnly('org.projectlombok:lombok') 40 | annotationProcessor('org.projectlombok:lombok') 41 | implementation('org.jetbrains.kotlin:kotlin-stdlib-jdk8') 42 | implementation('org.springframework.boot:spring-boot-starter-data-jpa') 43 | implementation('org.springframework.boot:spring-boot-starter-validation') 44 | implementation('com.google.code.findbugs:jsr305:3.0.2') 45 | testImplementation('org.springframework.boot:spring-boot-starter-test') 46 | 47 | //restdocs 48 | asciidoctorExt('org.springframework.restdocs:spring-restdocs-asciidoctor:2.0.6.RELEASE') 49 | testImplementation('org.springframework.restdocs:spring-restdocs-mockmvc:2.0.6.RELEASE') 50 | 51 | //kotlin test 52 | testImplementation("io.mockk:mockk:1.13.2") 53 | testImplementation("io.kotest:kotest-runner-junit5:5.5.4") 54 | testImplementation("io.kotest:kotest-assertions-core:5.5.4") 55 | testImplementation("io.kotest.extensions:kotest-extensions-spring:1.1.2") 56 | } 57 | 58 | tasks.named('test') { 59 | useJUnitPlatform() 60 | outputs.dir snippetsDir 61 | } 62 | 63 | tasks.named('asciidoctor') { 64 | inputs.dir snippetsDir 65 | configurations 'asciidoctorExt' 66 | dependsOn test 67 | } 68 | 69 | } 70 | 71 | bootJar { 72 | dependsOn asciidoctor 73 | from("${asciidoctor.outputDir}/html5") { 74 | into 'static/docs' 75 | } 76 | } 77 | 78 | compileKotlin { 79 | kotlinOptions { 80 | jvmTarget = "17" 81 | } 82 | } 83 | 84 | compileTestKotlin { 85 | kotlinOptions { 86 | jvmTarget = "17" 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | services: 3 | mysql-db: 4 | container_name: mysql-db 5 | image: mysql/mysql-server:8.0 6 | environment: 7 | MYSQL_ROOT_PASSWORD: ${datasource_password} 8 | MYSQL_ROOT_HOST: "%" 9 | MYSQL_DATABASE: "board" 10 | TZ: Asia/Seoul 11 | volumes: 12 | - ./mysql-init.d:/docker-entrypoint-initdb.d 13 | ports: 14 | - "3306:3306" 15 | command: 16 | - --character-set-server=utf8mb4 17 | - --collation-server=utf8mb4_unicode_ci 18 | 19 | token-redis-master: 20 | container_name: token-redis-master 21 | image: redis:latest 22 | ports: 23 | - "6379:6379" 24 | 25 | token-redis-slave: 26 | container_name: token-redis-slave 27 | image: redis:latest 28 | ports: 29 | - "6479:6379" 30 | command: redis-server --slaveof token-redis-master 6379 31 | depends_on: 32 | - token-redis-master 33 | 34 | board-api-server: 35 | container_name: board-api-server 36 | build: board-api-server/. 37 | environment: 38 | SPRING_DATASOURCE_URL: ${datasource_url} 39 | SPRING_DATASOURCE_USERNAME: ${datasource_username} 40 | SPRING_DATASOURCE_PASSWORD: ${datasource_password} 41 | JWT_CLIENT_SECRET: ${token_client_secret} 42 | ports: 43 | - "8081:8081" 44 | restart: always 45 | depends_on: 46 | - mysql-db 47 | 48 | board-chat-server: 49 | container_name: board-chat-server 50 | build: board-chat-server/. 51 | environment: 52 | SPRING_DATASOURCE_URL: ${datasource_url} 53 | SPRING_DATASOURCE_USERNAME: ${datasource_username} 54 | SPRING_DATASOURCE_PASSWORD: ${datasource_password} 55 | JWT_CLIENT_SECRET: ${token_client_secret} 56 | ports: 57 | - "8082:8082" 58 | restart: always 59 | depends_on: 60 | - mysql-db 61 | 62 | board-auth-server: 63 | container_name: board-auth-server 64 | build: board-auth-server/. 65 | environment: 66 | SPRING_DATASOURCE_URL: ${datasource_url} 67 | SPRING_DATASOURCE_USERNAME: ${datasource_username} 68 | SPRING_DATASOURCE_PASSWORD: ${datasource_password} 69 | JWT_CLIENT_SECRET: ${token_client_secret} 70 | OAUTH2_CLIENTS_GOOGLE_CLIENT-SECRET: ${google_client_secret} 71 | REDIS_MASTER_HOST: ${redis_master_host} 72 | REDIS_MASTER_PORT: ${redis_master_port} 73 | REDIS_SLAVE_HOST: ${redis_slave_host} 74 | REDIS_SLAVE_PORT: ${redis_slave_port} 75 | ports: 76 | - "8080:8080" 77 | restart: always 78 | depends_on: 79 | - token-redis-master 80 | - token-redis-slave 81 | - mysql-db 82 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/waterfogSW/Spring-Board/5a131c4d3eccd3b0a6d1a5468267f913c4472258/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /lombok.config: -------------------------------------------------------------------------------- 1 | lombok.nonNull.exceptionType = IllegalArgumentException 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'board' 2 | include 'board-core' 3 | include 'board-auth-server' 4 | include 'board-api-server' 5 | include 'board-chat-server' 6 | 7 | --------------------------------------------------------------------------------