Skip to content

Commit

Permalink
Merge pull request #3 from 28th-meetup/fix/common
Browse files Browse the repository at this point in the history
fix: CommonResponse 사용 수정
  • Loading branch information
eckrin committed Oct 17, 2023
2 parents c8f1363 + 399802f commit 7371e37
Show file tree
Hide file tree
Showing 10 changed files with 80 additions and 33 deletions.
6 changes: 5 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,15 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'
//javax validation
implementation 'javax.validation:validation-api:2.0.1.Final'
//websocket
implementation 'org.springframework.boot:spring-boot-starter-websocket'
//swagger (spring 3.x버전이라 springfox 적용불가, springdoc 중에서 호환되는 종속성 사용)
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'
//mysql (spring 3.x)
runtimeOnly 'com.mysql:mysql-connector-j'
//lombok
//redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
//lombok
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
Expand Down
16 changes: 9 additions & 7 deletions src/main/java/com/kusitms/jipbap/auth/AuthController.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.kusitms.jipbap.auth;

import com.kusitms.jipbap.auth.dto.*;
import com.kusitms.jipbap.common.response.CommonResponse;
import com.kusitms.jipbap.security.Auth;
import com.kusitms.jipbap.security.AuthInfo;
import io.swagger.v3.oas.annotations.Operation;
Expand All @@ -20,28 +21,29 @@ public class AuthController {
@Operation(summary = "일반 회원 가입")
@PostMapping("/signUp")
@ResponseStatus(HttpStatus.OK)
public void signUp(@Valid @RequestBody SignUpRequestDto dto) {
public CommonResponse<String> signUp(@Valid @RequestBody SignUpRequestDto dto) {
authService.signUp(dto);
return new CommonResponse<>("회원가입 성공");
}

@Operation(summary = "로그인")
@PostMapping("/signIn")
@ResponseStatus(HttpStatus.OK)
public SignInResponseDto signIn(@Valid @RequestBody SignInRequestDto dto) {
return authService.signIn(dto.getEmail(), dto.getPassword());
public CommonResponse<SignInResponseDto> signIn(@Valid @RequestBody SignInRequestDto dto) {
return new CommonResponse<>(authService.signIn(dto.getEmail(), dto.getPassword()));
}

@Operation(summary = "카카오 회원 가입(로그인)")
@PostMapping("/kakao")
@ResponseStatus(HttpStatus.OK)
public SignInResponseDto kakaoVerification(@RequestBody KakaoSignInRequestDto dto) {
return authService.kakaoAutoSignIn(authService.getKakaoProfile(dto.getToken()));
public CommonResponse<SignInResponseDto> kakaoVerification(@RequestBody KakaoSignInRequestDto dto) {
return new CommonResponse<>(authService.kakaoAutoSignIn(authService.getKakaoProfile(dto.getToken())));
}

@Operation(summary = "액세스 토큰 재발급 - 헤더에 refreshToken 정보 포함하여 요청")
@PostMapping("/reissue")
public ReissueResponseDto reissue(@Auth AuthInfo authInfo) {
return authService.reissue(authInfo.getEmail(), authInfo.getToken());
public CommonResponse<ReissueResponseDto> reissue(@Auth AuthInfo authInfo) {
return new CommonResponse<>(authService.reissue(authInfo.getEmail(), authInfo.getToken()));
}

}
22 changes: 11 additions & 11 deletions src/main/java/com/kusitms/jipbap/auth/AuthExceptionHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.kusitms.jipbap.auth.exception.*;
import com.kusitms.jipbap.common.response.ErrorCode;
import com.kusitms.jipbap.common.response.ErrorResponse;
import com.kusitms.jipbap.common.response.CommonResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
Expand All @@ -15,36 +15,36 @@
public class AuthExceptionHandler {
@ExceptionHandler(EmailExistsException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse<?> handleEmailExistsException(EmailExistsException e, HttpServletRequest request) {
public CommonResponse<?> handleEmailExistsException(EmailExistsException e, HttpServletRequest request) {
log.warn("Auth-001> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new ErrorResponse<>(ErrorCode.EMAIL_EXISTS_ERROR);
return new CommonResponse<>(ErrorCode.EMAIL_EXISTS_ERROR);
}

@ExceptionHandler(InvalidEmailException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse<?> handleInvalidEmailException(InvalidEmailException e, HttpServletRequest request) {
public CommonResponse<?> handleInvalidEmailException(InvalidEmailException e, HttpServletRequest request) {
log.warn("Auth-002> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new ErrorResponse<>(ErrorCode.INVALID_EMAIL_ERROR);
return new CommonResponse<>(ErrorCode.INVALID_EMAIL_ERROR);
}

@ExceptionHandler(InvalidPasswordException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse<?> handleInvalidPasswordException(InvalidPasswordException e, HttpServletRequest request) {
public CommonResponse<?> handleInvalidPasswordException(InvalidPasswordException e, HttpServletRequest request) {
log.warn("Auth-003> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new ErrorResponse<>(ErrorCode.INVALID_PASSWORD_ERROR);
return new CommonResponse<>(ErrorCode.INVALID_PASSWORD_ERROR);
}

@ExceptionHandler(RefreshTokenNotFoundException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse<?> handleRefreshTokenNotFoundException(RefreshTokenNotFoundException e, HttpServletRequest request) {
public CommonResponse<?> handleRefreshTokenNotFoundException(RefreshTokenNotFoundException e, HttpServletRequest request) {
log.warn("Auth-004> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new ErrorResponse<>(ErrorCode.INVALID_REFRESH_TOKEN_ERROR);
return new CommonResponse<>(ErrorCode.INVALID_REFRESH_TOKEN_ERROR);
}

@ExceptionHandler(JsonException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse<?> handleJsonException(JsonException e, HttpServletRequest request) {
public CommonResponse<?> handleJsonException(JsonException e, HttpServletRequest request) {
log.warn("Auth-005> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new ErrorResponse<>(ErrorCode.INTERNAL_SERVER_ERROR);
return new CommonResponse<>(ErrorCode.INTERNAL_SERVER_ERROR);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,29 @@

@Getter
@Setter
public class ErrorResponse<T> {
public class CommonResponse<T> {
private Boolean isSuccess;
private int code;
private String message;
@JsonInclude(JsonInclude.Include.NON_NULL)
private T result;

//성공
public CommonResponse(T result) {
this.isSuccess = ErrorCode.SUCCESS.getIsSuccess();
this.code = ErrorCode.SUCCESS.getCode();
this.message = ErrorCode.SUCCESS.getMessage();
this.result = result;
}

// 오류 발생
public ErrorResponse(ErrorCode errorCode) {
public CommonResponse(ErrorCode errorCode) {
this.isSuccess = errorCode.getIsSuccess();
this.code = errorCode.getCode();
this.message = errorCode.getMessage();
}

public ErrorResponse(ErrorCode errorCode, T result) {
public CommonResponse(ErrorCode errorCode, T result) {
this.isSuccess = errorCode.getIsSuccess();
this.code = errorCode.getCode();
this.message = errorCode.getMessage();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@

@Getter
public enum ErrorCode {
//success
SUCCESS(true, HttpStatus.OK.value(), "요청에 성공했습니다."),

//internal
INTERNAL_SERVER_ERROR(false,HttpStatus.INTERNAL_SERVER_ERROR.value(), "서버 내부에서 문제가 발생했습니다."),
NOT_FOUND(false, HttpStatus.NOT_FOUND.value(), "해당 로그인 정보는 존재하지 않습니다."),
UNAUTHORIZED(false, HttpStatus.UNAUTHORIZED.value(), "권한이 없습니다."),
Expand All @@ -17,7 +21,10 @@ public enum ErrorCode {
INVALID_REFRESH_TOKEN_ERROR(false, HttpStatus.BAD_REQUEST.value(), "RefreshToken 정보를 찾을 수 없습니다."),

//user
USER_NOT_EXISTS_ERROR(false, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 유저입니다."),
USER_NOT_FOUND_ERROR(false, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 유저입니다."),

//message
ROOM_NOT_FOUND_ERROR(false, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 채팅방입니다."),
;

private Boolean isSuccess;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,12 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
)
//인가(Authorize)
.authorizeHttpRequests(authorize ->
authorize
.requestMatchers(
"/auth/**"
).permitAll() //로그인, 회원가입,
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() //cors
.anyRequest().authenticated()
)
.addFilterBefore(new JwtAuthenticationFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class)
.addFilterAfter(new JwtAuthenticationFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(exceptionFilter, JwtAuthenticationFilter.class);

return http.build();
Expand All @@ -60,7 +56,6 @@ public PasswordEncoder passwordEncoder() {

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
//인증(Authentication)
return web -> web.ignoring().requestMatchers(
"/v3/api-docs/**",
"/favicon.ico",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kusitms.jipbap.common.response.ErrorCode;
import com.kusitms.jipbap.common.response.ErrorResponse;
import com.kusitms.jipbap.common.response.CommonResponse;
import com.kusitms.jipbap.security.jwt.exception.EmptyTokenException;
import com.kusitms.jipbap.security.jwt.exception.InvalidTokenException;
import jakarta.servlet.FilterChain;
Expand Down Expand Up @@ -56,15 +56,15 @@ private void setErrorResponse(HttpStatus status,
String errorCode) {
response.setStatus(status.value());
response.setContentType("application/json");
ErrorResponse<?> errorResponse = new ErrorResponse<>(code, exception.getMessage());
CommonResponse<?> commonResponse = new CommonResponse<>(code, exception.getMessage());
try {
log.error("에러코드 {}: {} [에러 종류: {}, 요청 url: {}]",
errorCode,
exception.getMessage(),
exception.getClass(),
request.getRequestURI());
response.setCharacterEncoding("UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(errorResponse));
response.getWriter().write(objectMapper.writeValueAsString(commonResponse));
} catch (IOException e) {
e.printStackTrace();
}
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/com/kusitms/jipbap/user/UserController.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.kusitms.jipbap.user;

import com.kusitms.jipbap.common.response.CommonResponse;
import com.kusitms.jipbap.security.Auth;
import com.kusitms.jipbap.security.AuthInfo;
import io.swagger.v3.oas.annotations.Operation;
Expand All @@ -17,8 +18,9 @@ public class UserController {

@Operation(summary = "로그아웃 - 리프레쉬 토큰 삭제")
@PostMapping("/logout")
public void logout(@Auth AuthInfo authInfo) {
public CommonResponse<String> logout(@Auth AuthInfo authInfo) {
userService.logout(authInfo.getEmail());
return new CommonResponse<>("로그아웃 성공");
}
}

22 changes: 22 additions & 0 deletions src/main/java/com/kusitms/jipbap/user/UserExceptionHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.kusitms.jipbap.user;

import com.kusitms.jipbap.common.response.ErrorCode;
import com.kusitms.jipbap.common.response.CommonResponse;
import com.kusitms.jipbap.user.exception.UserNotFoundException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class UserExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public CommonResponse<?> userNotFoundException(UserNotFoundException e, HttpServletRequest request) {
log.warn("User-001> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new CommonResponse<>(ErrorCode.USER_NOT_FOUND_ERROR);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.kusitms.jipbap.user.exception;

public class UserNotFoundException extends RuntimeException{
public UserNotFoundException(String message) {
super(message);
}
}

0 comments on commit 7371e37

Please sign in to comment.