Skip to content

Commit

Permalink
Merge pull request #55 from BOOK-TALK/#54-edit-api-format
Browse files Browse the repository at this point in the history
#54 edit api format
  • Loading branch information
chanwoo7 authored Aug 16, 2024
2 parents 839fc87 + a25a63e commit f369838
Show file tree
Hide file tree
Showing 6 changed files with 28 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
Expand All @@ -37,11 +39,11 @@ public class AuthController {
responses = {@ApiResponse(responseCode = "201", content = @Content(schema = @Schema(implementation = UserDto.class)),
description = UserDto.description)})
@PostMapping("/signup")
public ResponseEntity<UserDto> signup(@Valid @RequestBody SignupDto signupDto) {
public ResponseEntity<?> signup(@Valid @RequestBody SignupDto signupDto) {
RequestLogger.body(signupDto);

UserDto userDto = authService.signup(signupDto);
return ResponseEntity.ok(userDto);
return responseTemplate.success(userDto, HttpStatus.CREATED);
}

@Operation(summary = "로그인", description = "기본 로그인을 진행합니다.",
Expand All @@ -52,7 +54,7 @@ public ResponseEntity<?> login(@Valid @RequestBody LoginDto loginDto) {
RequestLogger.body(loginDto);

LoginSuccessResponseDto loginSuccessResponseDto = authService.login(loginDto);
return ResponseEntity.ok(loginSuccessResponseDto);
return responseTemplate.success(loginSuccessResponseDto, HttpStatus.OK);
}

// @PostMapping("/logout")
Expand All @@ -71,7 +73,7 @@ public ResponseEntity<?> deleteAccount() {
authService.deleteAccountByLoginId(loginId);
SecurityContextHolder.clearContext();

return new ResponseEntity<>(HttpStatus.NO_CONTENT);
return responseTemplate.success("회원 탈퇴가 완료되었습니다.", HttpStatus.NO_CONTENT);
}

@Operation(summary = "카카오 로그인", description = "사용자가 카카오 인증 서버에서 받은 인가 코드를 parameter로 받아 카카오계정으로 로그인을 진행하고, 완료된 유저 정보를 반환합니다.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.book.backend.exception.ErrorCode;
import com.book.backend.util.JwtUtil;
import com.book.backend.util.RequestWrapper;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
Expand Down Expand Up @@ -45,7 +46,12 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

if (authorization != null && authorization.startsWith("Bearer ")) { // Bearer 토큰 파싱
token = authorization.substring(7); // jwt token 파싱
username = jwtUtil.getUsernameFromToken(token); // username 가져옴
try {
username = jwtUtil.getUsernameFromToken(token); // username 가져옴
} catch (ExpiredJwtException e) {
filterChain.doFilter(wrappedRequest, response);
return;
}

// 현재 SecurityContextHolder에 인증객체가 있는지 확인
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/book/backend/exception/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ public enum ErrorCode {
INVALID_PAGE_NUM(HttpStatus.BAD_REQUEST, "400", "페이지 번호는 1 이상의 숫자로 입력해주세요."),

INVALID_CREDENTIALS(HttpStatus.UNAUTHORIZED, "401", "사용자 인증에 실패했습니다."),
LOGIN_REQUIRED(HttpStatus.FORBIDDEN, "403", "로그인이 필요합니다."),
LOGIN_REQUIRED(HttpStatus.UNAUTHORIZED, "401", "로그인이 필요합니다."),
JWT_EXPIRED(HttpStatus.UNAUTHORIZED, "401", "JWT 토큰이 만료되었습니다. 다시 로그인해주세요."),
USER_NOT_FOUND(HttpStatus.NOT_FOUND, "404", "해당하는 사용자를 찾을 수 없습니다."),
LOGIN_ID_DUPLICATED(HttpStatus.CONFLICT,"409", "사용자의 아이디가 중복됩니다."),
BAD_REQUEST(HttpStatus.BAD_REQUEST, "400", "요청이 잘못되었습니다."),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package com.book.backend.exception;

import com.book.backend.global.ResponseTemplate;
import java.util.HashMap;
import java.util.LinkedHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -15,13 +16,13 @@ public class ExceptionHandlerResponse {

// 유효성 검사 실패 시 BAD_REQUEST 로 반환
@ExceptionHandler(CustomException.class)
public ResponseEntity<HashMap<String, Object>> handleCustomException(CustomException e) {
public ResponseEntity<LinkedHashMap<String, Object>> handleCustomException(CustomException e) {
return responseTemplate.fail(e, HttpStatus.BAD_REQUEST);
}

// 다른 예외 발생 시 내부 서버 오류 반환
@ExceptionHandler(Exception.class)
public ResponseEntity<HashMap<String, Object>> handleException(Exception e) {
public ResponseEntity<LinkedHashMap<String, Object>> handleException(Exception e) {
return responseTemplate.fail(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ public void commence(HttpServletRequest request, HttpServletResponse response, A
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(
"{\"error\": \"" + customException.getCode().getMessage() + "\", " +
"\"code\": \"" + customException.getCode().getCode() + "\"}");
"{\"statusCode\": \"" + customException.getCode().getCode() + "\", " +
"\"message\": \"" + customException.getCode().getMessage() + "\"}");
response.getWriter().flush();
}
}
14 changes: 7 additions & 7 deletions src/main/java/com/book/backend/global/ResponseTemplate.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package com.book.backend.global;

import java.util.HashMap;
import lombok.AllArgsConstructor;
import java.util.LinkedHashMap;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Component
Expand All @@ -15,17 +15,17 @@
public class ResponseTemplate {

// 성공 response 템플릿
public ResponseEntity<HashMap<String, Object>> success(Object message, HttpStatus status) {
HashMap<String, Object> response = new HashMap<>();
public ResponseEntity<LinkedHashMap<String, Object>> success(Object message, HttpStatus status) {
LinkedHashMap<String, Object> response = new LinkedHashMap<>();
response.put("statusCode", status.value());
response.put("message", message);
response.put("data", message);

return new ResponseEntity<>(response, status);
}

// 예외 response 템플릿
public ResponseEntity<HashMap<String, Object>> fail(Exception e, HttpStatus status){
HashMap<String, Object> response = new HashMap<>();
public ResponseEntity<LinkedHashMap<String, Object>> fail(Exception e, HttpStatus status){
LinkedHashMap<String, Object> response = new LinkedHashMap<>();
response.put("statusCode", status.value());
response.put("message", e.getMessage());

Expand Down

0 comments on commit f369838

Please sign in to comment.