Skip to content

Commit

Permalink
Merge branch 'main' into feat/Spring-Rest-Docs-설정-#98
Browse files Browse the repository at this point in the history
  • Loading branch information
LeeJE20 committed May 10, 2023
2 parents 190e5e3 + b0c51ca commit f04578e
Show file tree
Hide file tree
Showing 44 changed files with 431 additions and 161 deletions.
13 changes: 12 additions & 1 deletion .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ on:
pull_request:
branches:
- main

workflow_dispatch:
inputs:
logLevel:
description: 'Log level'
required: true
default: 'warning'
tags:
description: 'Test scenario tags'
required: false

env:
S3_BUCKET_NAME: wingle-ci-bucket
CODE_DEPLOY_APPLICATION_NAME: wingle-codedeploy-app
Expand Down Expand Up @@ -79,7 +90,7 @@ jobs:
mkdir build
cd ./build
mkdir generated-snippets
- name: Grant execute permission for gradlew
run: chmod +x ./wingle/gradlew

Expand Down
2 changes: 2 additions & 0 deletions wingle/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ dependencies {
annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.3.Final'
testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.5.3.Final'

implementation group: 'ca.pjer', name: 'logback-awslogs-appender', version: '1.6.0'

// spring rest docs
asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
Expand Down
6 changes: 4 additions & 2 deletions wingle/src/main/java/kr/co/wingle/common/aop/LogAspect.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package kr.co.wingle.common.aop;

import kr.co.wingle.common.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;

import org.aspectj.lang.ProceedingJoinPoint;
Expand All @@ -15,7 +16,7 @@
@Aspect
@Component
public class LogAspect {
private static final String LOG_MESSAGE_FORMAT = "{} {} : {}.{}() took {}ms. (group by '{}', traceID: {})";
private static final String LOG_MESSAGE_FORMAT = "[{}] {} {} : {}.{}() took {}ms. (group by '{}', traceID: {})";

@Pointcut(
"(execution(* kr.co.wingle..*Controller.*(..)) || execution(* kr.co.wingle..*Service.*(..)) || execution(* kr.co.wingle..*Repository.*(..)))"
Expand All @@ -36,10 +37,11 @@ public Object apiLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();

try {
String user = SecurityUtil.getCurrentUserEmail();
String className = proceedingJoinPoint.getSignature().getDeclaringType().getName();
String methodName = proceedingJoinPoint.getSignature().getName();
long executionTime = end - start;
log.info(LOG_MESSAGE_FORMAT, request.getMethod(), request.getRequestURI(),
log.info(LOG_MESSAGE_FORMAT, user, request.getMethod(), request.getRequestURI(),
className, methodName, executionTime, group(className), traceId);
} catch (Exception e) {
log.error("LogAspect error", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ public PasswordEncoder passwordEncoder() {
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors()

.and()
.csrf().disable()

.exceptionHandling()
Expand Down
32 changes: 28 additions & 4 deletions wingle/src/main/java/kr/co/wingle/common/config/WebMvcConfig.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,41 @@
package kr.co.wingle.common.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
// CORS 오류 해결
private final String host = "https://wingle.kr";
private final String localhost = "http://localhost:";
private final int allowedMinPort = 3000;
private final int allowedMaxPort = 3010;
private List<String> allowedOrigins = new ArrayList<>();

// CORS
@Override
public void addCorsMappings(CorsRegistry registry) {
// 허용할 origin 목록
int allowedPort = allowedMinPort;
allowedOrigins.add(host);
while (allowedPort <= allowedMaxPort) {
allowedOrigins.add(localhost + allowedPort);
allowedPort += 1;
}

registry.addMapping("/**")
.allowedOrigins("http://localhost:3000", "https://wingle.kr")
.maxAge(3000) // pre-flight 리퀘스트를 캐싱
.allowCredentials(true); // 쿠키 요청을 허용
.allowedOrigins(allowedOrigins.toArray(new String[allowedOrigins.size()]))
.allowedMethods(
HttpMethod.GET.name(),
HttpMethod.HEAD.name(),
HttpMethod.POST.name(),
HttpMethod.PUT.name(),
HttpMethod.PATCH.name(),
HttpMethod.DELETE.name())
.maxAge(3000); // pre-flight 리퀘스트를 캐싱
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ public enum ErrorCode {
DUPLICATE_EMAIL(BAD_REQUEST, "이미 가입된 유저입니다."),
ALREADY_ACCEPTANCE(BAD_REQUEST, "이미 가입 승인한 유저입니다."),
ALREADY_DENY(BAD_REQUEST, "이미 가입 거절한 유저입니다."),
ALREADY_WITHDRAWN(BAD_REQUEST, "이미 탈퇴한 유저입니다."),
NOT_ACCEPTED(BAD_REQUEST, "승인되지 않은 유저입니다."),
// 메일
EMAIL_BAD_REQUEST(BAD_REQUEST, "이메일 형식이 유효하지 않습니다."),
EMAIL_SEND_FAIL(BAD_REQUEST, "이메일을 전송할 수 없습니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,19 @@ public enum SuccessCode {
NICKNAME_CHECK_SUCCESS(OK, "닉네임 확인 성공"),
EMAIL_SEND_SUCCESS(OK, "이메일 인증코드 전송 성공"),
EMAIL_CERTIFICATION_SUCCESS(OK, "이메일 인증 성공"),
// 어드민
ACCEPTANCE_SUCCESS(OK, "회원가입 수락 전송 성공"),
REJECTION_SUCCESS(OK, "회원가입 거절 전송 성공"),
MEMO_SAVE_SUCCESS(OK, "사용자 메모 저장 성공"),
WAITING_LIST_READ_SUCCESS(OK, "수락 대기 목록 조회 성공"),
WAITING_USER_READ_SUCCESS(OK, "수락 대기 사용자 조회 성공"),
REJECTION_LIST_READ_SUCCESS(OK, "수락 거절 목록 조회 성공"),
ACCEPTANCE_LIST_READ_SUCCESS(OK, "수락 완료 목록 조회 성공"),
REJECTION_REASON_SAVE_SUCCESS(OK, "거절 사유 저장 성공"),
// 프로필
PROFILE_SAVE_SUCCESS(OK, "프로필 저장 성공"),
PROFILE_READ_SUCCESS(OK,"프로필 조회 성공"),
PROFILE_REGISTER_READ_SUCCESS(OK,"프로필 등록 여부 조회 성공"),
PROFILE_READ_SUCCESS(OK, "프로필 조회 성공"),
PROFILE_REGISTER_READ_SUCCESS(OK, "프로필 등록 여부 조회 성공"),
LANGUAGES_SAVE_SUCCESS(OK, "사용 가능 언어 저장 성공"),
INTRODUCTION_SAVE_SUCCESS(OK, "자기소개 저장 성공"),
INTERESTS_SAVE_SUCCESS(OK, "관심사 저장 성공");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public ApiResponse<ArticleResponseDto> getOne(@PathVariable String forumId,
articleService.getOne(StringUtil.StringToLong(forumId), StringUtil.StringToLong(articleId)));
}

@GetMapping("/{forumId}/articles/")
@GetMapping("/{forumId}/articles")
public ApiResponse<List<ArticleResponseDto>> getList(@PathVariable String forumId,
@RequestParam String page, @RequestParam String size, @RequestParam(required = false) String my) {
if (my != null && !my.toLowerCase().equals("true") && !my.toLowerCase().equals("false"))
Expand All @@ -49,7 +49,7 @@ public ApiResponse<List<ArticleResponseDto>> getList(@PathVariable String forumI
boolean getMine = false;
if (my != null && my.toLowerCase().equals("true"))
getMine = true;

return ApiResponse.success(SuccessCode.GET_SUCCESS,
articleService.getList(StringUtil.StringToLong(forumId), StringUtil.StringToInt(page),
StringUtil.StringToInt(size), getMine));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@

import kr.co.wingle.community.util.CommunityUtil;
import kr.co.wingle.community.util.ProcessedPersonalInformation;
import kr.co.wingle.profile.ProfileService;
import lombok.RequiredArgsConstructor;

@Component
@RequiredArgsConstructor
public class ArticleMapper {
private final CommunityUtil communityUtil;
private final ProfileService profileService;

public ArticleResponseDto toResponseDto(Article article, List<String> images) {
if (article == null) {
Expand All @@ -36,6 +38,8 @@ public ArticleResponseDto toResponseDto(Article article, List<String> images) {
}
articleResponseDto.isMine(processedPersonalInformation.isMine());
articleResponseDto.userId(processedPersonalInformation.getProcessedMemberId());
articleResponseDto.userImage(profileService.getProfileByMemberId(article.getMember().getId()).getImageUrl());
articleResponseDto.userNation(profileService.getProfileByMemberId(article.getMember().getId()).getNation());
articleResponseDto.forumId(article.getForum().getId());

return articleResponseDto.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public class ArticleResponseDto {
private Long articleId;
private Long userId;
private String userNickname;
private String userImage;
private String userNation;
private LocalDateTime createdTime;
private LocalDateTime updatedTime;
private Long forumId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class ArticleService extends WritingService {

@Transactional
public ArticleResponseDto create(ArticleRequestDto request) {
Member member = authService.findMember();
Member member = authService.findAcceptedLoggedInMember();
Forum forum = forumService.getForumById(request.getForumId());

// 공지 작성 방지
Expand Down Expand Up @@ -65,7 +65,7 @@ public List<ArticleResponseDto> getList(Long forumId, int page, int size, boolea
Pageable pageable = PageRequest.of(page, size);
List<Article> pages;
if (getMine) {
Member member = authService.findMember();
Member member = authService.findAcceptedLoggedInMember();
pages = articleRepository.findByForumIdAndMemberIdAndIsDeleted(forumId, member.getId(), false, pageable);
} else {
pages = articleRepository.findByForumIdAndIsDeleted(forumId, false, pageable);
Expand All @@ -80,7 +80,7 @@ public List<ArticleResponseDto> getList(Long forumId, int page, int size, boolea

@Transactional
public Long delete(Long forumId, Long articleId) {
Member member = authService.findMember();
Member member = authService.findAcceptedLoggedInMember();
Article article = getArticleById(articleId);

if (isValidMember(article, member) && isExist(article) && isValidForum(article, forumId)) {
Expand All @@ -101,7 +101,7 @@ public Article getArticleById(Long articleId) {
@Transactional(readOnly = true)
public boolean isValidForum(Article article, Long forumId) {
// 게시판 안 맞으면 에러
if (article.getForum().getId() != forumId) {
if (!forumId.equals(article.getForum().getId())) {
throw new NotFoundException(ErrorCode.BAD_PARAMETER);
}
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
Expand All @@ -27,7 +27,7 @@ public class CommentController {
private final CommentService commentService;

@PostMapping("/articles/comments")
public ApiResponse<CommentResponseDto> create(@ModelAttribute @Valid CommentRequestDto request) {
public ApiResponse<CommentResponseDto> create(@RequestBody @Valid CommentRequestDto request) {
CommentResponseDto response = commentService.create(request);
return ApiResponse.success(SuccessCode.COMMENT_CREATE_SUCCESS, response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ public CommentResponseDto toResponseDto(Comment comment) {
commentResponseDto.id(comment.getId());
commentResponseDto.userId(processedPersonalInformation.getProcessedMemberId());
commentResponseDto.userNickname(processedPersonalInformation.getNickname());
// TODO: Profile 엔티티에 프로필 사진 컬럼 추가
// commentResponseDto.userImage(profileService.getProfileByMemberId(comment.getMember().getId()).getImageUrl());
commentResponseDto.userImage("");
commentResponseDto.userImage(profileService.getProfileByMemberId(comment.getMember().getId()).getImageUrl());
commentResponseDto.userNation(profileService.getProfileByMemberId(comment.getMember().getId()).getNation());
commentResponseDto.createdTime(comment.getCreatedTime());
commentResponseDto.updatedTime(comment.getUpdatedTime());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import javax.validation.constraints.Positive;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import reactor.util.annotation.Nullable;

@Getter
@Setter
Expand All @@ -21,8 +21,7 @@ public class CommentRequestDto {
@NotNull(message = "게시글 id가 없습니다.")
private Long articleId;

@Positive(message = "id는 양수만 가능합니다.")
@Null
@Nullable
private Long originCommentId;

@NotBlank(message = "내용이 없습니다.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class CommentService extends WritingService {

@Transactional
public CommentResponseDto create(CommentRequestDto request) {
Member loggedInMember = authService.findMember();
Member loggedInMember = authService.findAcceptedLoggedInMember();
Article article = articleService.getArticleById(request.getArticleId());
articleService.isValidForum(article, request.getForumId());

Expand All @@ -51,7 +51,7 @@ public List<CommentResponseDto> getList(Long forumId, Long articleId, int page,

@Transactional
public Long delete(Long forumId, Long articleId, Long commentId) {
Member member = authService.findMember();
Member member = authService.findAcceptedLoggedInMember();
Comment comment = getCommentById(commentId);

if (isValidMember(comment, member) && isExist(comment) && articleService.isValidForum(comment.getArticle(),
Expand All @@ -73,7 +73,7 @@ public Comment getCommentById(Long commentId) {
@Transactional(readOnly = true)
public boolean isValidArticle(Comment comment, Long articleId) {
// 게시글 안 맞으면 에러
if (comment.getArticle().getId() != articleId) {
if (!articleId.equals(comment.getArticle().getId())) {
throw new NotFoundException(ErrorCode.BAD_PARAMETER);
}
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public Forum getForumById(Long forumId) {
}

static public String getNicknameByForum(Forum forum, Profile profile) {
final String nationCodeKor = "kor";
final String nationCodeKor = "KR";
final String anonymousKor = "한국 윙그리";
final String anonymousNoneKor = "외국 윙그리";
final String admin = "관리자";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class CommunityUtil {

// 게시판, 작성자에 따라 개인정보 가공
public ProcessedPersonalInformation processPersonalInformation(Writing writing) {
Member loggedInMember = authService.findMember();
Member loggedInMember = authService.findAcceptedLoggedInMember();
Profile profile = profileService.getProfileByMemberId(writing.getMember().getId());

Forum forum;
Expand Down
5 changes: 4 additions & 1 deletion wingle/src/main/java/kr/co/wingle/member/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@
import kr.co.wingle.member.entity.Member;
import kr.co.wingle.member.service.AuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("api/v1/auth")
@RequiredArgsConstructor
Expand All @@ -44,12 +46,13 @@ public ApiResponse<SignupResponseDto> signup(@ModelAttribute @Valid SignupReques
@PostMapping("/login")
public ApiResponse<LoginResponseDto> login(@RequestBody @Valid LoginRequestDto loginRequestDto) {
LoginResponseDto response = authService.login(loginRequestDto);
log.info("[{}] login success", loginRequestDto.getEmail());
return ApiResponse.success(SuccessCode.LOGIN_SUCCESS, response);
}

@GetMapping("/me")
public ApiResponse<MemberResponseDto> getMyAccount() {
Member member = authService.findMember();
Member member = authService.findLoggedInMember();
MemberResponseDto response = MemberResponseDto.from(member);
return ApiResponse.success(SuccessCode.ACCOUNT_READ_SUCCESS, response);
}
Expand Down
Loading

0 comments on commit f04578e

Please sign in to comment.