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

Refactor/47 회원 API리팩토링 #50

Merged
merged 12 commits into from
Jun 29, 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: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ ARG JAR_FILE=/build/libs/gamegoo-0.0.1-SNAPSHOT.jar

COPY ${JAR_FILE} /gamegoo.jar

ENTRYPOINT ["java","-jar","-Dspring.profiles.active=prod", "/gamegoo.jar"]
ENTRYPOINT ["java","-jar","-Dspring.profiles.active=prod", "/gamegoo.jar"]
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public enum ErrorStatus implements BaseErrorCode {
// JWT 관련 에러
TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED, "JWT401", "jwt 토큰이 만료되었습니다."),
INVALID_TOKEN(HttpStatus.BAD_REQUEST, "JWT400", "유효하지 않은 jwt 토큰입니다."),
TOKEN_NULL(HttpStatus.NOT_FOUND, "JWT404", "JWT 토큰이 없습니다."),

// GameStyle 관련 에러
GAMESTYLE_NOT_FOUND(HttpStatus.NOT_FOUND, "GAMESTYLE404", "해당 게임 스타일을 찾을 수 없습니다."),
Expand All @@ -39,10 +40,16 @@ public enum ErrorStatus implements BaseErrorCode {
// Profile_Image 관련 에러
PROFILE_IMAGE_BAD_REQUEST(HttpStatus.BAD_REQUEST, "PROFILE_IMAGE_400", "profile_image가 30자를 초과했습니다."),

// Email 인증 관련 에러
EMAIL_SEND_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "EMAIL500", "이메일 전송 도중, 에러가 발생했습니다."),
EMAIL_NOT_FOUND(HttpStatus.NOT_FOUND, "EMAIL404", "해당 이메일을 찾을 수 없습니다."),
EMAIL_INVALID(HttpStatus.BAD_REQUEST, "EMAIL400", "인증 코드가 불일치합니다."),

// 차단 관련 에러
TARGET_MEMBER_NOT_FOUND(HttpStatus.NOT_FOUND, "BLOCK401", "차단 대상 회원을 찾을 수 없습니다."),
ALREADY_BLOCKED(HttpStatus.BAD_REQUEST, "BLOCK402", "이미 차단한 회원입니다.");
private final HttpStatus httpStatus;

private final HttpStatus httpStatus;
private final String code;
private final String message;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.gamegoo.apiPayload.exception.handler;

import org.springframework.security.core.AuthenticationException;

public class CustomUserException extends AuthenticationException {
public CustomUserException(String msg) {
super(msg);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.gamegoo.apiPayload.exception.handler;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 filter는 apiPayload.exception.handler 패키지보다 그냥 com.gamegoo.filter 패키지에 있는게 찾기 편할 것 같아요!


import com.fasterxml.jackson.databind.ObjectMapper;
import com.gamegoo.apiPayload.ApiResponse;
import com.gamegoo.apiPayload.code.status.ErrorStatus;
import io.jsonwebtoken.JwtException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

public class JWTExceptionHandlerFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (JwtException e) {

if (Objects.equals(e.getMessage(), "Token expired")) {
setErrorResponse(response, ErrorStatus.TOKEN_EXPIRED);
} else if (Objects.equals(e.getMessage(), "Token null")) {
setErrorResponse(response, ErrorStatus.TOKEN_NULL);
} else if (Objects.equals(e.getMessage(), "No Member")) {
setErrorResponse(response, ErrorStatus.MEMBER_NOT_FOUND);
} else {
setErrorResponse(response, ErrorStatus.INVALID_TOKEN);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private void setErrorResponse(HttpServletResponse response, ErrorStatus errorStatus) throws IOException {
// 에러 응답 생성하기
ApiResponse<Object> apiResponse = ApiResponse.onFailure(errorStatus.getCode(), errorStatus.getMessage(), null);
response.setStatus(errorStatus.getHttpStatus().value());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
new ObjectMapper().writeValue(response.getWriter(), apiResponse);
}
}

This file was deleted.

This file was deleted.

27 changes: 15 additions & 12 deletions src/main/java/com/gamegoo/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package com.gamegoo.config;

import com.gamegoo.jwt.JWTFilter;
import com.gamegoo.jwt.JWTUtil;
import com.gamegoo.security.LoginFilter;
import com.gamegoo.apiPayload.exception.handler.JWTExceptionHandlerFilter;
import com.gamegoo.filter.JWTFilter;
import com.gamegoo.filter.LoginFilter;
import com.gamegoo.service.member.CustomUserDetailService;
import com.gamegoo.util.JWTUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
Expand All @@ -18,17 +21,14 @@
import java.util.Arrays;
import java.util.List;


@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final AuthenticationConfiguration authenticationConfiguration;
private final JWTUtil jwtUtil;
private final CustomUserDetailService customUserDetailService;

public SecurityConfig(AuthenticationConfiguration authenticationConfiguration, JWTUtil jwtUtil) {
this.authenticationConfiguration = authenticationConfiguration;
this.jwtUtil = jwtUtil;
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
Expand All @@ -37,8 +37,9 @@ public AuthenticationManager authenticationManager(AuthenticationConfiguration c

@Bean
public JWTFilter jwtFilter() {
List<String> excludedPaths = Arrays.asList("/swagger-ui/", "/v3/api-docs", "/api/member/join/local", "/api/member/login/local", "/api/member/email");
return new JWTFilter(jwtUtil, excludedPaths);
List<String> excludedPaths = Arrays.asList("/api/member/join", "/api/member/login", "/api/member/email");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"/swagger-ui/", "/v3/api-docs" 이 uri도 다시 추가 부탁드립니다..! dev랑 충돌 해결하면서 지워진 것 같아요

return new JWTFilter(jwtUtil, excludedPaths, customUserDetailService);

}

@Bean
Expand All @@ -49,13 +50,15 @@ public BCryptPasswordEncoder bCryptPasswordEncoder() {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http

.csrf(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)

.authorizeHttpRequests((auth) -> auth
.antMatchers("/api/member/join/local", "/api/member/login/local", "/api/member/email").permitAll()
.antMatchers("/", "/swagger-ui/**", "/v3/api-docs/**").permitAll()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분도 다시 추가 부탁드려요!

.antMatchers("/api/member/join", "/api/member/login", "/api/member/email/**").permitAll()
.anyRequest().authenticated())
.addFilterBefore(new JWTExceptionHandlerFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration), jwtUtil), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtFilter(), LoginFilter.class)
.sessionManagement((session) -> session
Expand Down
46 changes: 46 additions & 0 deletions src/main/java/com/gamegoo/controller/member/AuthController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.gamegoo.controller.member;

import com.gamegoo.apiPayload.ApiResponse;
import com.gamegoo.dto.member.EmailCodeDTO;
import com.gamegoo.dto.member.EmailDTO;
import com.gamegoo.dto.member.JoinDTO;
import com.gamegoo.service.member.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/member")
@Slf4j
public class AuthController {
private final AuthService authService;

@PostMapping("/join")
@Operation(summary = "회원가입 API 입니다.", description = "API for join")
public ApiResponse<Object> joinMember(@RequestBody JoinDTO joinDTO) {
authService.joinMember(joinDTO);
return ApiResponse.onSuccess("회원가입에 성공했습니다.");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기서 가입된 회원에 대한 정보(id, email)등을 응답으로 주는 것도 좋을 것 같아요..!

}

@PostMapping("/email/send")
@Operation(summary = "이메일 인증코드 전송 API 입니다.", description = "API for sending email")
public ApiResponse<Object> sendEmail(@RequestBody EmailDTO emailDTO) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

응답을 단순 string으로 줄 때는 여기도 ApiResponse으로 지정해주는 게 더 좋을 것 같아요!

String email = emailDTO.getEmail();
authService.sendEmail(email);
return ApiResponse.onSuccess("인증 이메일을 발송했습니다.");
}

@PostMapping("/email/verify")
@Operation(summary = "이메일 인증코드 검증 API 입니다.", description = "API for email verification")
public ApiResponse<Object> verifyEmail(@RequestBody EmailCodeDTO emailCodeDTO) {
String email = emailCodeDTO.getEmail();
String code = emailCodeDTO.getCode();
authService.verifyEmail(email, code);
return ApiResponse.onSuccess("인증코드 검증에 성공했습니다.");
}
}
39 changes: 0 additions & 39 deletions src/main/java/com/gamegoo/controller/member/DeleteController.java

This file was deleted.

30 changes: 0 additions & 30 deletions src/main/java/com/gamegoo/controller/member/EmailController.java

This file was deleted.

27 changes: 0 additions & 27 deletions src/main/java/com/gamegoo/controller/member/JoinController.java

This file was deleted.

This file was deleted.

Loading
Loading