Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swagger 적용 #51

Merged
merged 5 commits into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,15 @@ repositories {
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.4'
implementation 'com.mysql:mysql-connector-j'
implementation 'io.jsonwebtoken:jjwt:0.9.1'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package com.powersupply.PES.answer.controller;

import com.powersupply.PES.answer.dto.AnswerDTO;
import com.powersupply.PES.answer.service.AnswerService;
import com.powersupply.PES.utils.ResponseUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@Tag(name = "Answer", description = "답변 관련 API")
public class AnswerController {

private final AnswerService answerService;

@Operation(summary = "답변 생성", description = "사용자가 답변을 생성합니다.")
@ApiResponses({
@ApiResponse(responseCode = "201", description = "답변 생성 성공"),
@ApiResponse(responseCode = "400", description = "잘못된 요청"),
@ApiResponse(responseCode = "500", description = "서버 오류")
})
@PostMapping("/api/answer")
public ResponseEntity<AnswerDTO.GetAnswerId> createAnswer(
@Parameter(description = "회원 이메일", example = "[email protected]") @RequestParam("memberEmail") String email,
@Parameter(description = "문제 ID", example = "1") @RequestParam("problemId") Long problemId) {
return ResponseEntity.status(HttpStatus.CREATED).body(answerService.createAnswer(email, problemId));
}

@Operation(summary = "질문 및 답변 조회", description = "특정 답변 ID에 대한 질문과 답변을 조회합니다.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "조회 성공(토큰에 문제가 없고 유저를 DB에서 찾을 수 있는 경우)"),
@ApiResponse(responseCode = "404", description = "해당 answerId를 찾을 수 없는 경우"),
@ApiResponse(responseCode = "500", description = "서버 오류")
})
@GetMapping("/api/answer/{answerId}")
public ResponseEntity<AnswerDTO.GetAnswer> getAnswer(
@Parameter(description = "답변 ID", example = "1") @PathVariable Long answerId) {
return ResponseEntity.ok().body(answerService.getAnswer(answerId));
}

@Operation(summary = "답변하기", description = "사용자가 특정 답변 ID에 대해 답변을 작성합니다.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "답변 작성 성공"),
@ApiResponse(responseCode = "400", description = "answer 내용이 null인 경우 or 이미 댓글이 있어 수정이 불가능 한 경우"),
@ApiResponse(responseCode = "404", description = "answer의 주인과 토큰이 다른 경우"),
@ApiResponse(responseCode = "500", description = "서버 오류")
})
@PostMapping("/api/answer/{answerId}")
public ResponseEntity<?> postAnswer(
@Parameter(description = "답변 ID", example = "1") @PathVariable Long answerId,
@RequestBody AnswerDTO.AnswerContent dto) {
answerService.postAnswer(answerId, dto);
return ResponseUtil.successResponse("");
}

@Operation(summary = "풀이 보기", description = "특정 문제 ID에 대한 풀이 목록을 조회합니다.")
@ApiResponses({
@ApiResponse(responseCode = "201", description = "토큰에 문제가 없고 유저를 DB에서 찾을 수 있는 경우"),
@ApiResponse(responseCode = "204", description = "아직 푼 사람이 없는 경우"),
@ApiResponse(responseCode = "404", description = "problemId가 잘못된 경우"),
@ApiResponse(responseCode = "500", description = "서버 오류")
})
@GetMapping("/api/answerlist/{problemId}")
public ResponseEntity<?> getAnswerList(
@Parameter(description = "문제 ID", example = "1") @PathVariable Long problemId) {
return answerService.getAnswerList(problemId);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.powersupply.PES.domain.dto;
package com.powersupply.PES.answer.dto;

import lombok.Builder;
import lombok.Getter;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package com.powersupply.PES.domain.entity;
package com.powersupply.PES.answer.entity;

import com.powersupply.PES.comment.entity.CommentEntity;
import com.powersupply.PES.entity.BaseEntity;
import com.powersupply.PES.problem.entity.ProblemEntity;
import com.powersupply.PES.question.entity.QuestionEntity;
import com.powersupply.PES.member.entity.MemberEntity;
import lombok.*;

import javax.persistence.*;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.powersupply.PES.repository;
package com.powersupply.PES.answer.repository;

import com.powersupply.PES.domain.entity.AnswerEntity;
import com.powersupply.PES.domain.entity.QuestionEntity;
import com.powersupply.PES.answer.entity.AnswerEntity;
import com.powersupply.PES.question.entity.QuestionEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
package com.powersupply.PES.service;
package com.powersupply.PES.answer.service;

import com.powersupply.PES.domain.dto.AnswerDTO;
import com.powersupply.PES.domain.entity.*;
import com.powersupply.PES.answer.entity.AnswerEntity;
import com.powersupply.PES.answer.repository.AnswerRepository;
import com.powersupply.PES.comment.entity.CommentEntity;
import com.powersupply.PES.comment.repository.CommentRepository;
import com.powersupply.PES.answer.dto.AnswerDTO;
import com.powersupply.PES.exception.AppException;
import com.powersupply.PES.exception.ErrorCode;
import com.powersupply.PES.repository.*;
import com.powersupply.PES.member.entity.MemberEntity;
import com.powersupply.PES.member.repository.MemberRepository;
import com.powersupply.PES.problem.entity.ProblemEntity;
import com.powersupply.PES.problem.repository.ProblemRepository;
import com.powersupply.PES.question.entity.QuestionEntity;
import com.powersupply.PES.question.repository.QuestionRepository;
import com.powersupply.PES.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.powersupply.PES.comment.controller;

import com.powersupply.PES.comment.dto.CommentDTO;
import com.powersupply.PES.comment.service.CommentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@Tag(name = "Comment", description = "댓글 관련 API")
public class CommentController {

private final CommentService commentService;

@Operation(summary = "댓글 조회", description = "특정 답변 ID에 대한 댓글을 조회합니다.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "조회 성공"),
@ApiResponse(responseCode = "204", description = "댓글이 없는 경우"),
@ApiResponse(responseCode = "500", description = "서버 오류")
})
@GetMapping("/api/comment/{answerId}")
public ResponseEntity<?> getComment(
@Parameter(description = "답변 ID", example = "1") @PathVariable Long answerId) {
return commentService.getComment(answerId);
}

@Operation(summary = "댓글 달기", description = "특정 답변 ID에 대해 댓글을 작성합니다.")
@ApiResponses({
@ApiResponse(responseCode = "201", description = "토큰에 문제가 없고 유저를 DB에서 찾아 정상적으로 댓글을 생성한 경우"),
@ApiResponse(responseCode = "400", description = "이미 자신의 댓글이 있는 경우"),
@ApiResponse(responseCode = "403", description = "재학생이 아닌 경우 / jwt 문제 / 자신의 답변에 댓글을 단 경우 / 최대 댓글 수 도달"),
@ApiResponse(responseCode = "404", description = "answerId가 잘못된 경우"),
@ApiResponse(responseCode = "500", description = "서버 오류")
})
@PostMapping("/api/comment/{answerId}")
public ResponseEntity<?> createComment(
@Parameter(description = "답변 ID", example = "1") @PathVariable Long answerId,
@RequestBody CommentDTO.CreateComment dto) {
return commentService.createComment(answerId, dto);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.powersupply.PES.domain.dto;
package com.powersupply.PES.comment.dto;

import lombok.Builder;
import lombok.Getter;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.powersupply.PES.domain.entity;
package com.powersupply.PES.comment.entity;

import com.powersupply.PES.answer.entity.AnswerEntity;
import com.powersupply.PES.entity.BaseEntity;
import com.powersupply.PES.member.entity.MemberEntity;
import lombok.*;

import javax.persistence.*;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.powersupply.PES.repository;
package com.powersupply.PES.comment.repository;

import com.powersupply.PES.domain.entity.CommentEntity;
import com.powersupply.PES.comment.entity.CommentEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package com.powersupply.PES.service;
package com.powersupply.PES.comment.service;

import com.powersupply.PES.domain.dto.CommentDTO;
import com.powersupply.PES.domain.entity.AnswerEntity;
import com.powersupply.PES.domain.entity.CommentEntity;
import com.powersupply.PES.domain.entity.MemberEntity;
import com.powersupply.PES.comment.dto.CommentDTO;
import com.powersupply.PES.answer.entity.AnswerEntity;
import com.powersupply.PES.comment.entity.CommentEntity;
import com.powersupply.PES.member.entity.MemberEntity;
import com.powersupply.PES.exception.AppException;
import com.powersupply.PES.exception.ErrorCode;
import com.powersupply.PES.repository.AnswerRepository;
import com.powersupply.PES.repository.CommentRepository;
import com.powersupply.PES.repository.MemberRepository;
import com.powersupply.PES.answer.repository.AnswerRepository;
import com.powersupply.PES.comment.repository.CommentRepository;
import com.powersupply.PES.member.repository.MemberRepository;
import com.powersupply.PES.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
Expand Down
21 changes: 18 additions & 3 deletions src/main/java/com/powersupply/PES/configuration/JwtFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,25 @@ public class JwtFilter extends OncePerRequestFilter {
private final String secretKey;

// 인증이 필요없는 경로 URL 목록
private final List<String> skipUrls = Arrays.asList("/api/signin", "/api/signup", "/api/finduser");
private final List<String> skipUrls = Arrays.asList(
"/api/signin",
"/api/signup",
"/api/finduser",
"/swagger-ui/**",
"/v3/api-docs/**",
"/swagger-resources/**",
"/webjars/**"
);

// 인증이 필요 없는 GET 요청의 URL 목록
private final List<String> skipGetUrls = Arrays.asList("/api/problemlist/" , "/api/answer/**", "/api/comment/**", "/api/answerlist/**", "/api/rank/**", "/api/admin/**");
private final List<String> skipGetUrls = Arrays.asList(
"/api/problemlist/",
"/api/answer/**",
"/api/comment/**",
"/api/answerlist/**",
"/api/rank/**",
"/api/admin/**"
);

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
Expand All @@ -46,7 +61,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
}

// 인증이 필요없는 경로는 바로 통과
if (skipUrls.contains(requestURI)) {
if (skipUrls.stream().anyMatch(uri -> pathMatcher.match(uri, requestURI))) {
log.info("인증 필요 없음 : {}", requestURI);
filterChain.doFilter(request, response);
return;
Expand Down
68 changes: 41 additions & 27 deletions src/main/java/com/powersupply/PES/configuration/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
Expand All @@ -28,18 +28,25 @@ public class SecurityConfig {
@Value("${jwt.secret}")
private String secretKey;

@Value("${admin.username}")
private String adminUsername;

@Value("${admin.password}")
private String adminPassword;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.httpBasic().disable() // UI쪽 들어오는거 disable
.csrf().disable() // cross site 기능
.cors().configurationSource(corsConfigurationSource()).and() // cross site 도메인 다른 경우 허용
.httpBasic().and() // 기본 인증 활성화
.csrf().disable() // CSRF 비활성화
.cors().configurationSource(corsConfigurationSource()).and() // CORS 설정
.authorizeRequests()
.antMatchers("/api/signin","/api/signup").permitAll() // 기본 요청 언제나 접근 가능
.antMatchers(HttpMethod.GET, "/api/problemlist" , "/api/answer/**", "/api/comment/**", "/api/answerlist/**", "/api/rank/**", "/api/notice/**", "/api/admin/**").permitAll()
.antMatchers(HttpMethod.POST,"/api/comment/**").hasRole("REGULAR_STUDENT")
.antMatchers(HttpMethod.POST,"/api/notice/**").hasRole("MANAGER")
.antMatchers(HttpMethod.PATCH,"/api/notice/**").hasRole("MANAGER")
.antMatchers("/api/signin", "/api/signup").permitAll() // 기본 요청 허용
.antMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**").authenticated() // Swagger 경로에 대한 접근 제한
.antMatchers(HttpMethod.GET, "/api/problemlist", "/api/answer/**", "/api/comment/**", "/api/answerlist/**", "/api/rank/**", "/api/notice/**", "/api/admin/**").permitAll()
.antMatchers(HttpMethod.POST, "/api/comment/**").hasRole("REGULAR_STUDENT")
.antMatchers(HttpMethod.POST, "/api/notice/**").hasRole("MANAGER")
.antMatchers(HttpMethod.PATCH, "/api/notice/**").hasRole("MANAGER")
.anyRequest().hasRole("USER")
.and()
.sessionManagement()
Expand All @@ -53,31 +60,38 @@ public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://www.pes23.com", "https://pes23.com")); // 여기에 IP 추가
configuration.setAllowedOrigins(Arrays.asList("https://www.pes23.com", "https://pes23.com", "http://localhost:8080"));
configuration.setAllowedMethods(Arrays.asList("POST", "GET", "OPTIONS", "PUT", "DELETE", "PATCH"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
configuration.setAllowCredentials(true); // 필요한 경우, 쿠키와 함께 요청을 보내는 것을 허용
configuration.setAllowCredentials(true);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration); // 모든 URL에 대해 설정 적용
source.registerCorsConfiguration("/**", configuration);

return source;
}

@Bean
public SecurityExpressionHandler customWebSecurityExpressionHandler() {
DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
defaultWebSecurityExpressionHandler.setRoleHierarchy(roleHierarchy());
return defaultWebSecurityExpressionHandler;
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername(adminUsername).password("{noop}" + adminPassword).roles("ADMIN").build());
return manager;
}

@Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
//roleHierarchy.setHierarchy("ROLE_MANAGER > ROLE_REGULAR_STUDENT > ROLE_USER and ROLE_NEW_STUDENT > ROLE_USER");
String hierarchy = "ROLE_ADMIN > ROLE_MANAGER > ROLE_REGULAR_STUDENT > ROLE_USER\n" +
"ROLE_NEW_STUDENT > ROLE_USER";
roleHierarchy.setHierarchy(hierarchy);
return roleHierarchy;
public PasswordEncoder passwordEncoder() {
return new NoOpPasswordEncoder();
}
}

class NoOpPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}

@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return rawPassword.toString().equals(encodedPassword);
}
}
Loading
Loading