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

merge : change swagger library & change memory add request param #1

Merged
merged 5 commits into from
Jan 13, 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
2 changes: 0 additions & 2 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ name: Java CI with Gradle
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

permissions:
contents: read
Expand Down
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
// Swagger 3.0.0
implementation 'org.springdoc:springdoc-openapi-ui:1.6.11'

// firebase
implementation 'com.google.firebase:firebase-admin:9.2.0'
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/com/exciting/vvue/auth/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
import com.exciting.vvue.auth.service.AuthService;
import com.exciting.vvue.user.model.User;
import com.exciting.vvue.user.service.UserService;
import io.swagger.annotations.ApiOperation;
import java.time.LocalDate;

import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand Down
8 changes: 7 additions & 1 deletion src/main/java/com/exciting/vvue/auth/jwt/util/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.security.Key;
import java.util.Date;
Expand Down Expand Up @@ -62,7 +63,12 @@ public Boolean validateToken(String jwt) throws JwtException { // JWT 유효성
log.debug("claims: {}", claims);
return !isTokenExpired(jwt);
}

public String removeBearer(String bearerToken){
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.replace("Bearer ", "");
}
return bearerToken;
}
private Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ public JwtDto createTokens(User user) {
}

@Override
public Long getUserIdFromToken(String token) {
public Long getUserIdFromToken(String bearerToken) {
String token = jwtUtil.removeBearer(bearerToken);
Map<String, Object> claims = jwtUtil.getClaims(token);
Long userId = Long.valueOf(claims.get("id").toString());
return userId;
Expand Down
66 changes: 31 additions & 35 deletions src/main/java/com/exciting/vvue/common/config/SwaggerConfig.java
Original file line number Diff line number Diff line change
@@ -1,51 +1,47 @@
package com.exciting.vvue.common.config;

import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.HashSet;
import java.util.Set;

import java.util.Arrays;


@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.consumes(getConsumeContentTypes())
.produces(getProduceContentTypes())
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.exciting.vvue"))
.paths(PathSelectors.any()).build().useDefaultResponseMessages(false);
public GroupedOpenApi group(){
return GroupedOpenApi.builder()
.group("vvue apis")
.packagesToScan("com.exciting.vvue")
.build();
}

private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("Vvue Spring Boot REST API")
.version("1.0.0")
.description("Vvue의 swagger api 입니다.")
@Bean
public GroupedOpenApi developGroup() {
return GroupedOpenApi.builder()
.group("develop apis")
.packagesToScan("com.exciting.vvue.develop") // package 필터 설정
.build();
}
@Bean
public OpenAPI springOpenApi(){
SecurityScheme securityScheme = new SecurityScheme()
.type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")
.in(SecurityScheme.In.HEADER).name("Authorization");
SecurityRequirement securityRequirement = new SecurityRequirement().addList("bearerAuth");

private Set<String> getConsumeContentTypes() {
Set<String> consumes = new HashSet<>();
consumes.add("application/json;charset=UTF-8");
consumes.add("application/x-www-form-urlencoded");
return consumes;
return new OpenAPI().components(new Components().addSecuritySchemes("bearerAuth",securityScheme)).security(Arrays.asList(securityRequirement))
.info(new Info()
.title("vvue REST API")
.version("1.0.0")
.description("vvue swagger api 입니다."));
}

private Set<String> getProduceContentTypes() {
Set<String> produces = new HashSet<>();
produces.add("application/json;charset=UTF-8");
return produces;
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
Expand All @@ -27,9 +30,11 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons

log.debug("request : " + request.getHeader(HEADER_AUTH));

final String token = request.getHeader(HEADER_AUTH);
final String header = request.getHeader(HEADER_AUTH);

log.debug("Interceptor token = " + token);
log.debug("Interceptor token = " + header);
String bearerToken = request.getHeader(HttpHeaders.AUTHORIZATION);
String token = jwtUtil.removeBearer(bearerToken);

if(token == null || token.isBlank()){
throw new InvalidTokenException("토큰 잘못됨");
Expand All @@ -46,5 +51,8 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
}

throw new InvalidTokenException("토큰 잘못됨");

}


}
19 changes: 12 additions & 7 deletions src/main/java/com/exciting/vvue/develop/DevelopController.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,13 @@
import com.exciting.vvue.user.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
Expand Down Expand Up @@ -64,7 +65,7 @@ public class DevelopController {
private final VvueNotificationRepository vvueNotificationRepository;
private final UserRepository userRepository;

@ApiOperation(value = "강제 결혼(코드인증까지만 완료/추가 정보 입력 필요함)")
@Operation(description ="강제 결혼(코드인증까지만 완료/추가 정보 입력 필요함)")
@PostMapping("/force-marry/{spouseId}")
public ResponseEntity<?> forceMarry(@RequestHeader("Authorization") String token,
@PathVariable Long spouseId) {
Expand All @@ -89,7 +90,7 @@ public ResponseEntity<?> forceMarry(@RequestHeader("Authorization") String token
"결혼 요청:userId " + userId + " " + spouseId + " 결혼 완료");
}

@ApiOperation(value = "강제 이혼 (스케줄/추억이 없는 경우만 가능)")
@Operation(description = "강제 이혼 (스케줄/추억이 없는 경우만 가능)")
@DeleteMapping("/divorce")
public ResponseEntity<?> divorce(@RequestHeader("Authorization") String token) {
Long userId = authService.getUserIdFromToken(token);
Expand All @@ -101,7 +102,7 @@ public ResponseEntity<?> divorce(@RequestHeader("Authorization") String token) {
}

@Deprecated
@ApiOperation(value = "데이터 입력 : 개발 테스트", notes = "[사진만 DB에 미리 업로드하기]유저(1-8),결혼 1~4, 결혼일정/일반달반복일정/반복없음(1-9, 각 유저마다3가지), 추억(스케줄에 대해 홀수번 유저만 작성), 알림(1-6 유저의 결혼/달반복/반복없음에 존재)")
@Operation(description ="데이터 입력 : 개발 테스트", summary = "[사진만 DB에 미리 업로드하기]유저(1-8),결혼 1~4, 결혼일정/일반달반복일정/반복없음(1-9, 각 유저마다3가지), 추억(스케줄에 대해 홀수번 유저만 작성), 알림(1-6 유저의 결혼/달반복/반복없음에 존재)")
@PostMapping("/for-test")
public ResponseEntity<?> testGenearte() {
//TODO
Expand Down Expand Up @@ -247,6 +248,8 @@ public ResponseEntity<?> testGenearte() {
for (int j = 0; j < schedule.size(); j++) {
MemoryAddReqDto memory2 = MemoryAddReqDto.builder()
.scheduleId(schedule.get(j).getId())
.scheduleDate(LocalDate.parse(schedule.get(j).getScheduleDate()))
.scheduleName(schedule.get(j).getScheduleName())
.comment("코멘트" + i)
.pictureId(pair[i] - 1)
.placeMemories(List.of(
Expand Down Expand Up @@ -289,7 +292,7 @@ public ResponseEntity<?> testGenearte() {
return ResponseEntity.ok().build();
}

@ApiOperation(value = "테스트 JWT 토큰 발급 (유저정보 확인하기): providerId = {providerId}")
@Operation(description = "테스트 JWT 토큰 발급 (유저정보 확인하기): providerId = {providerId}")
@GetMapping("/test-token-gen/{providerId}")
public ResponseEntity<JwtDto> testTokenGen(@PathVariable Long providerId) {
log.debug("[POST] /test-token-gen");
Expand Down Expand Up @@ -322,7 +325,7 @@ public ResponseEntity<JwtDto> testTokenGen(@PathVariable Long providerId) {
return new ResponseEntity<>(jwtDto, HttpStatus.OK);
}

@ApiOperation(value = "덤프 장소 데이터 추가")
@Operation(description ="덤프 장소 데이터 추가")
@PostMapping("/dump-place-data")
public ResponseEntity<?> dumpPlaceData(@RequestHeader("Authorization")String token) {
log.debug("[POST] /dump-place-data");
Expand Down Expand Up @@ -399,7 +402,7 @@ private String requestToKakaoMap(String code){
return responseEntity.getBody();
}

@ApiOperation(value = "덤프 장소 데이터 추가(param 추가)")
@Operation(description = "덤프 장소 데이터 추가(param 추가)")
@PostMapping("/dump-place-data-param")
public ResponseEntity<?> selectDumpPlaceData(@RequestHeader("Authorization")String token, @RequestParam("x") Double x, @RequestParam("y") Double y, @RequestParam("code") String categoryCode) {
log.debug("[POST] /dump-place-data-param");
Expand Down Expand Up @@ -431,6 +434,8 @@ public ResponseEntity<?> selectDumpPlaceData(@RequestHeader("Authorization")Stri
memoryService.add(MemoryAddReqDto.builder()
.pictureId(picture.getId())
.scheduleId(schedule.getId())
.scheduleName(schedule.getScheduleName())
.scheduleDate(schedule.getScheduleDate())
.comment("더미코멘트")
.placeMemories(placeMemoryReqDtoList)
.build(), user, married);
Expand Down
34 changes: 17 additions & 17 deletions src/main/java/com/exciting/vvue/married/MarriedCodeController.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.exciting.vvue.married;

import java.time.LocalDate;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -22,10 +26,6 @@
import com.exciting.vvue.married.service.MarriedService;
import com.exciting.vvue.user.service.UserService;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

Expand All @@ -42,10 +42,10 @@ public class MarriedCodeController {
private final int CODE_LENGTH = 8;
// 부부 인증 코드 발급
@GetMapping("/generate")
@ApiOperation(value="부부 인증 코드 발급 (자신 id로)",notes = "부부 인증 코드를 발급한다")
@Operation(summary="부부 인증 코드 발급 (자신 id로)",description = "부부 인증 코드를 발급한다")
@ApiResponses({
@ApiResponse(code = 200, message = "성공", response = MarriedCode.class),
@ApiResponse(code = 404, message = "인증코드 생성실패"),
@ApiResponse(responseCode = "200", description = "성공", content = {@Content(schema = @Schema(implementation = MarriedCode.class))}),
@ApiResponse(responseCode = "404", description = "인증코드 생성실패"),
})
public ResponseEntity<?> getMarriedAuthCode(@RequestHeader("Authorization") String token){
/**
Expand All @@ -70,11 +70,11 @@ public ResponseEntity<?> getMarriedAuthCode(@RequestHeader("Authorization") Stri
}

@GetMapping("/regenerate")
@ApiOperation(value="부부 인증 코드 재발급", notes="인증 코드 시간 만료 시 자동 호출 + 버튼 눌렀을 때 호출")
@ApiImplicitParam(name="marriedCode",value = "전에 발급된 부부인증코드", required = true)
@Operation(summary="부부 인증 코드 재발급", description="인증 코드 시간 만료 시 자동 호출 + 버튼 눌렀을 때 호출")
@Parameter(name="marriedCode",description = "전에 발급된 부부인증코드", required = true)
@ApiResponses({
@ApiResponse(code = 200, message = "성공", response = MarriedCode.class),
@ApiResponse(code = 404, message = "인증코드 생성실패"),
@ApiResponse(responseCode = "200", description = "성공", content = {@Content(schema = @Schema(implementation = MarriedCode.class))}),
@ApiResponse(responseCode = "404", description = "인증코드 생성실패"),
})
public ResponseEntity<?> regenerateAuthCode(@RequestHeader("Authorization") String token, @RequestParam String marriedCode){
/**
Expand All @@ -98,12 +98,12 @@ public ResponseEntity<?> regenerateAuthCode(@RequestHeader("Authorization") Stri
}

@PostMapping("/connect")
@ApiOperation(value = "인증 코드 일치 확인", notes = "인증 코드 발급한 유저와 부부 정보 생성")
@Operation(summary = "인증 코드 일치 확인", description = "인증 코드 발급한 유저와 부부 정보 생성")
// @ApiImplicitParam(name = "marriedCode", value = "입력한 인증코드", required = true)
@ApiResponses({
@ApiResponse(code = 200, message = "성공", response = Long.class ),
@ApiResponse(code = 400, message = "자신 인증코드 입력, 이미 부부 정보가 있는 사람과 연동 시도"),
@ApiResponse(code = 404, message = "redis에 인증 코드 없음"),
@ApiResponse(responseCode = "200", description = "성공", content = {@Content(schema = @Schema(implementation = Long.class))}),
@ApiResponse(responseCode = "400", description = "자신 인증코드 입력, 이미 부부 정보가 있는 사람과 연동 시도"),
@ApiResponse(responseCode = "404", description = "redis에 인증 코드 없음"),
})
public ResponseEntity<?> connectMarriedCode(@RequestHeader("Authorization") String token, @RequestBody MarriedCode marriedCode){

Expand Down
Loading