Skip to content
Snippets Groups Projects
Commit 9662eda4 authored by 천 진강's avatar 천 진강
Browse files

feat: 인증 인터셉터에서 필터로 변경 및 로그에 사용자 정보 추가

parent 88e8e972
No related branches found
No related tags found
2 merge requests!15Feat/certificate,!14Feat/main 자잘한 변경 사항들
......@@ -4,74 +4,73 @@ import com.aolda.itda.dto.auth.IdAndNameDTO;
import com.aolda.itda.exception.CustomException;
import com.aolda.itda.exception.ErrorCode;
import com.aolda.itda.service.AuthService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.filter.OncePerRequestFilter;
import java.util.ArrayList;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@RequiredArgsConstructor
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
public class AuthFilter extends OncePerRequestFilter {
private final AuthService authService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (request.getRequestURI().contains("/api/auth")) {
filterChain.doFilter(request, response);
return;
}
String token = request.getHeader("X-Subject-Token");
/* 토큰 헤더 검증 */
// 토큰 헤더 검증
if (token == null || token.isEmpty()) {
throw new CustomException(ErrorCode.INVALID_TOKEN, request.getRequestURI());
}
/* 유효 토큰 검증 */
// 유효 토큰 검증
String userId = authService.validateTokenAndGetUserId(token);
if (userId == null) {
log.error("Token validation failed for URI {}: {}", request.getRequestURI(), request.getRemoteAddr());
throw new CustomException(ErrorCode.INVALID_TOKEN, request.getRequestURI());
}
/* 프로젝트 권한 검증 */
// 프로젝트 권한 검증
String projectId = request.getParameter("projectId");
if (projectId != null) {
try {
authService.getBestRoleWithinProject(token, projectId).get("role");
if (!request.getMethod().equals("GET") && !authService.getBestRoleWithinProject(token, projectId).get("role").equals("admin")) {
throw new CustomException(ErrorCode.UNAUTHORIZED_USER, request.getRequestURI());
}
} catch (Exception e) {
throw new CustomException(ErrorCode.UNAUTHORIZED_USER, request.getRequestURI());
}
}
/* 프로젝트 리스트 조회 */
// 프로젝트 리스트 조회
List<String> projects;
if (authService.isAdmin(Map.of("id", userId, "token", token))) {
projects = authService.getAllProjects(token).stream().map(IdAndNameDTO::getId)
.toList();
}
else {
projects = authService.getProjectsWithUser(Map.of("id", userId, "token", token))
.stream().map(IdAndNameDTO::getId)
.toList();
projects = authService.getAllProjects(token).stream().map(IdAndNameDTO::getId).toList();
} else {
projects = authService.getProjectsWithUser(Map.of("id", userId, "token", token)).stream().map(IdAndNameDTO::getId).toList();
}
request.setAttribute("projects", projects);
request.setAttribute("user", Map.of("id", userId, "token", token));
return true;
filterChain.doFilter(request, response);
}
}
\ No newline at end of file
package com.aolda.itda.config;
import com.aolda.itda.exception.CustomException;
import com.aolda.itda.exception.ErrorCode;
import com.aolda.itda.service.AuthService;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
......@@ -11,11 +16,14 @@ import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import java.io.IOException;
import java.util.Map;
@Component
@RequiredArgsConstructor
public class LoggingFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class);
private final AuthService authService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
......@@ -29,15 +37,16 @@ public class LoggingFilter extends OncePerRequestFilter {
logRequest(cachingRequest);
}
private void logRequest(ContentCachingRequestWrapper request) {
private void logRequest(ContentCachingRequestWrapper request) throws JsonProcessingException {
String ip = request.getRemoteAddr();
String method = request.getMethod();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
String body = getRequestBody(request);
Map<String, String> user = (Map<String, String>) request.getAttribute("user");
logger.info("IP: {}, Method: {}, URI: {}, Query Params: {}, Request Body: {}",
ip, method, uri, (queryString != null ? queryString : "None"),
logger.info("IP: {}, Method: {}, URI: {}, Query Params: {}, User: {}, Request Body: {}",
ip, method, uri, (queryString != null ? queryString : "None"), (user != null ? user.get("id") : "None"),
(!body.isEmpty() ? body : "None"));
}
......
......@@ -3,17 +3,18 @@ package com.aolda.itda.config;
import com.querydsl.jpa.impl.JPAQueryFactory;
import jakarta.persistence.EntityManager;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final AuthInterceptor authInterceptor;
private final AuthFilter authFilter;
private final LoggingFilter loggingFilter;
@Override
public void addCorsMappings(CorsRegistry registry) { // 스프링단에서 cors 설정
......@@ -26,13 +27,23 @@ public class WebConfig implements WebMvcConfigurer {
;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
String[] excludeAuth = {"/error", "/api/auth/*" };
registry.addInterceptor(authInterceptor)
.addPathPatterns("/**")
.excludePathPatterns(excludeAuth);
@Bean
public FilterRegistrationBean<AuthFilter> authFilterRegistration() {
FilterRegistrationBean<AuthFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(authFilter);
registrationBean.setOrder(1); // AuthFilter의 순서를 1로 설정
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
@Bean
public FilterRegistrationBean<LoggingFilter> loggingFilterRegistration() {
FilterRegistrationBean<LoggingFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(loggingFilter);
registrationBean.setOrder(2); // LoggingFilter의 순서를 2로 설정
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
@Bean
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment