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

[202201912 이서인] Level6 미션 제출합니다. #30

Open
wants to merge 8 commits into
base: level6-initial
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
# backend.likelion.todos.User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# AWS User-specific
# AWS backend.likelion.todos.User-specific
.idea/**/aws.xml

# Generated files
Expand Down
21 changes: 21 additions & 0 deletions src/main/java/backend/likelion/todos/Filter/FilterConfigure.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package backend.likelion.todos.Filter;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import jakarta.servlet.Filter;

// @Configuration
public class FilterConfigure {

@Bean
public FilterRegistrationBean<Filter> logFilter() {
FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new LogFilter());
filterRegistrationBean.setOrder(2);
filterRegistrationBean.addUrlPatterns("/*");

return filterRegistrationBean;
}
}
45 changes: 45 additions & 0 deletions src/main/java/backend/likelion/todos/Filter/LogFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package backend.likelion.todos.Filter;

import java.io.IOException;
import java.util.UUID;

import org.springframework.stereotype.Component;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.Order;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@WebFilter
@Component
@Order(1)
public class LogFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws
IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String requestURI = request.getRequestURI();
String uuid = UUID.randomUUID().toString();
log.info("logFilter1 requestURI : {}, uuid : {}", requestURI, uuid);
filterChain.doFilter(servletRequest,servletResponse);
}

@Override
public void destroy() {
Filter.super.destroy();
}
}
51 changes: 51 additions & 0 deletions src/main/java/backend/likelion/todos/Filter/LogIntercepter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package backend.likelion.todos.Filter;

import java.util.UUID;
import java.util.logging.Handler;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LogIntercepter implements HandlerInterceptor {
public static String LOG_ID = "logID";

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String requestURI = request.getRequestURI();
String uuid = UUID.randomUUID().toString();

request.setAttribute(LOG_ID, uuid);

if(handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
}

log.info("REQUEST [{}][{}][{}]", uuid, requestURI, handler);
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
log.info("postHandle [{}]", request.getAttribute(LOG_ID));
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
String requestURI = request.getRequestURI();
String logID = (String)request.getAttribute(LOG_ID);

log.info("RESPONSE [{}][{}][{}]", logID, requestURI, handler);
if(ex != null) {
log.error("afterCompletion error!!", ex);
}
}
}
17 changes: 17 additions & 0 deletions src/main/java/backend/likelion/todos/Filter/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package backend.likelion.todos.Filter;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

// @Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogIntercepter())
.order(1)
.addPathPatterns("/**")
.excludePathPatterns("/css/**", "/*.ico", "/error");
}
}
25 changes: 25 additions & 0 deletions src/main/java/backend/likelion/todos/UserArgumentResolver.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package backend.likelion.todos;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class UserArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(User.class);
}
@Override
public Object resolveArgument(
MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory
) {
String userId = webRequest.getHeader("userId");
String userName = webRequest.getHeader("userName");
return new User(userId, userName);
}
}
12 changes: 12 additions & 0 deletions src/main/java/backend/likelion/todos/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package backend.likelion.todos;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
@GetMapping("/user")
public String getUserInfo(User user) {
return "사용자 ID: " + user.getId() + ", 이름: " +user.getName();
}
}
17 changes: 17 additions & 0 deletions src/main/java/backend/likelion/todos/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package backend.likelion.todos;

import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers (
List<HandlerMethodArgumentResolver> argumentResolvers
) {
argumentResolvers.add(new UserArgumentResolver());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ public class AuthArgumentResolver implements HandlerMethodArgumentResolver {

@Override
public boolean supportsParameter(MethodParameter parameter) {
// TODO [6단계] parameter가 @Auth 어노테이션을 갖고 있고, 파라미터 타입이 Long.class인 경우 true를 반환하는 조건을 구현하세요.
return false;
return parameter.hasParameterAnnotation(Auth.class) && parameter.getParameterType().equals(Long.class);
}

@Override
Expand All @@ -30,13 +29,15 @@ public Object resolveArgument(
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory
) {
// TODO [6단계] webRequest로부터 accessToken을 추출하고, jwtService를 사용하여 memberId를 추출하여 반환하는 로직을 구현하세요.
return null;
String accessToken = extractAccessToken(webRequest);
return jwtService.extractMemberId(accessToken);
}

private static String extractAccessToken(NativeWebRequest request) {
// TODO [6단계] request 헤더에서 "Authorization" 헤더 값을 추출하여 "Bearer "로 시작하는 accessToken을 반환하세요. 유효하지 않을 경우 "로그인 후 접근할 수 있습니다." 메시지와 함께 UnAuthorizedException을 발생시키는 로직을 구현하세요.
return null;
String authorizationHeader = request.getHeader("Authorization");
if (StringUtils.hasText(authorizationHeader) && authorizationHeader.startsWith("Bearer ")) {
return authorizationHeader.substring(7);
}
throw new UnAuthorizedException("로그인 후 접근할 수 있습니다.");
}

}
3 changes: 1 addition & 2 deletions src/main/java/backend/likelion/todos/auth/AuthConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ public class AuthConfig implements WebMvcConfigurer {

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
// TODO [6단계] resolvers 리스트에 authArgumentResolver를 추가하세요.
resolvers.add(authArgumentResolver);
}

}