260212_01_DOC: 프로젝트 전체에 구글 java 스타일 적용
This commit is contained in:
@@ -10,4 +10,5 @@ import org.springframework.context.annotation.Import;
|
||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true")
|
||||
@Import(ApiKeyAdminController.class) // ✅ 컴포넌트 스캔 없이도 Bean 등록
|
||||
public class ApiKeyAdminAutoConfiguration {
|
||||
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package com.kri.common.auth.apikey;
|
||||
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.web.util.matcher.IpAddressMatcher;
|
||||
@@ -11,54 +13,67 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/internal/apikey")
|
||||
@ConditionalOnProperty(prefix="kri.auth.apikey", name="admin-api-enabled", havingValue="true")
|
||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true")
|
||||
public class ApiKeyAdminController {
|
||||
private final ApiKeyProperties props;
|
||||
private final PreloadedApiKeyUserClaimsProvider provider;
|
||||
private final List<IpAddressMatcher> allow;
|
||||
|
||||
public ApiKeyAdminController(ApiKeyProperties props, PreloadedApiKeyUserClaimsProvider provider) {
|
||||
this.props = props;
|
||||
this.provider = provider;
|
||||
this.allow = props.getAdminAllowIps().stream().map(IpAddressMatcher::new).toList();
|
||||
private final ApiKeyProperties props;
|
||||
private final PreloadedApiKeyUserClaimsProvider provider;
|
||||
private final List<IpAddressMatcher> allow;
|
||||
|
||||
public ApiKeyAdminController(ApiKeyProperties props, PreloadedApiKeyUserClaimsProvider provider) {
|
||||
this.props = props;
|
||||
this.provider = provider;
|
||||
this.allow = props.getAdminAllowIps().stream().map(IpAddressMatcher::new).toList();
|
||||
}
|
||||
|
||||
@PostMapping("/reload")
|
||||
public ReloadResult reload(HttpServletRequest req) {
|
||||
assertAllowed(req);
|
||||
int count = provider.reloadFromDb();
|
||||
return new ReloadResult(count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 캐시 상태(키는 마스킹)
|
||||
*/
|
||||
@GetMapping("/cache")
|
||||
public List<CachedKeyView> cache(HttpServletRequest req) {
|
||||
assertAllowed(req);
|
||||
Map<String, JwtUserClaimsDto> snap = provider.snapshot();
|
||||
return snap.entrySet().stream()
|
||||
.map(e -> new CachedKeyView(mask(e.getKey()), e.getValue()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private void assertAllowed(HttpServletRequest req) {
|
||||
if (!props.isAdminApiEnabled()) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@PostMapping("/reload")
|
||||
public ReloadResult reload(HttpServletRequest req) {
|
||||
assertAllowed(req);
|
||||
int count = provider.reloadFromDb();
|
||||
return new ReloadResult(count);
|
||||
String remote = req.getRemoteAddr();
|
||||
boolean ok = allow.stream().anyMatch(m -> m.matches(remote));
|
||||
if (!ok) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote);
|
||||
}
|
||||
}
|
||||
|
||||
/** 현재 캐시 상태(키는 마스킹) */
|
||||
@GetMapping("/cache")
|
||||
public List<CachedKeyView> cache(HttpServletRequest req) {
|
||||
assertAllowed(req);
|
||||
Map<String, JwtUserClaimsDto> snap = provider.snapshot();
|
||||
return snap.entrySet().stream()
|
||||
.map(e -> new CachedKeyView(mask(e.getKey()), e.getValue()))
|
||||
.toList();
|
||||
private String mask(String raw) {
|
||||
if (raw == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
private void assertAllowed(HttpServletRequest req) {
|
||||
if (!props.isAdminApiEnabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
String remote = req.getRemoteAddr();
|
||||
boolean ok = allow.stream().anyMatch(m -> m.matches(remote));
|
||||
if (!ok) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote);
|
||||
int n = raw.length();
|
||||
if (n <= 8) {
|
||||
return raw.charAt(0) + "****";
|
||||
}
|
||||
return raw.substring(0, 4) + "****" + raw.substring(n - 4);
|
||||
}
|
||||
|
||||
private String mask(String raw) {
|
||||
if (raw == null) return "";
|
||||
int n = raw.length();
|
||||
if (n <= 8) return raw.charAt(0) + "****";
|
||||
return raw.substring(0, 4) + "****" + raw.substring(n - 4);
|
||||
}
|
||||
public record ReloadResult(int cachedKeyCount) {
|
||||
|
||||
public record ReloadResult(int cachedKeyCount) {}
|
||||
public record CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) {}
|
||||
}
|
||||
|
||||
public record CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,54 +5,52 @@ import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터.
|
||||
* - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임.
|
||||
* - 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅.
|
||||
* X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터. - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임. -
|
||||
* 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅.
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
public class ApiKeyAuthFilter extends OncePerRequestFilter {
|
||||
|
||||
private final ApiKeyProperties apiKeyProperties;
|
||||
private final ApiKeyUserClaimsProvider apiKeyUserClaimsProvider;
|
||||
private final JwtService jwtService;
|
||||
private final ApiKeyProperties apiKeyProperties;
|
||||
private final ApiKeyUserClaimsProvider apiKeyUserClaimsProvider;
|
||||
private final JwtService jwtService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
// API Key 기능이 꺼져 있으면 아무 것도 안 함
|
||||
if (!apiKeyProperties.isEnabled()) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
// 이미 다른 방식(JWT 등)으로 인증되어 있으면 패스
|
||||
if (SecurityContextHolder.getContext().getAuthentication() != null) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
String headerName = apiKeyProperties.getHeaderName();
|
||||
String apiKey = request.getHeader(headerName);
|
||||
|
||||
if (StringUtils.hasText(apiKey)) {
|
||||
apiKeyUserClaimsProvider.findUserByApiKey(apiKey).ifPresent(dto -> {
|
||||
Authentication auth = jwtService.toAuthentication(dto);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
});
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
// API Key 기능이 꺼져 있으면 아무 것도 안 함
|
||||
if (!apiKeyProperties.isEnabled()) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
// 이미 다른 방식(JWT 등)으로 인증되어 있으면 패스
|
||||
if (SecurityContextHolder.getContext().getAuthentication() != null) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
String headerName = apiKeyProperties.getHeaderName();
|
||||
String apiKey = request.getHeader(headerName);
|
||||
|
||||
if (StringUtils.hasText(apiKey)) {
|
||||
apiKeyUserClaimsProvider.findUserByApiKey(apiKey).ifPresent(dto -> {
|
||||
Authentication auth = jwtService.toAuthentication(dto);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
});
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@ package com.kri.common.auth.apikey;
|
||||
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import javax.sql.DataSource;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
@@ -19,97 +22,93 @@ import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/*
|
||||
* @Primary 절대 금지
|
||||
* 메인 JPA와 완전히 분리
|
||||
*/
|
||||
@AutoConfiguration(
|
||||
afterName = {
|
||||
// 메인 JPA가 있는 서비스에서는 메인 auto-config 이후에 올라와도 되고,
|
||||
// 메인 JPA를 exclude한 서비스에서는 afterName이 무시되어도 동작해야 함.
|
||||
"org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration",
|
||||
"org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration"
|
||||
}
|
||||
afterName = {
|
||||
// 메인 JPA가 있는 서비스에서는 메인 auto-config 이후에 올라와도 되고,
|
||||
// 메인 JPA를 exclude한 서비스에서는 afterName이 무시되어도 동작해야 함.
|
||||
"org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration",
|
||||
"org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration"
|
||||
}
|
||||
)
|
||||
@ConditionalOnClass(name = {
|
||||
"org.springframework.data.jpa.repository.JpaRepository",
|
||||
"jakarta.persistence.EntityManagerFactory",
|
||||
"com.zaxxer.hikari.HikariDataSource"
|
||||
"org.springframework.data.jpa.repository.JpaRepository",
|
||||
"jakarta.persistence.EntityManagerFactory",
|
||||
"com.zaxxer.hikari.HikariDataSource"
|
||||
})
|
||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
|
||||
@EnableJpaRepositories(
|
||||
basePackages = "com.kri.common.auth.persistence.repository",
|
||||
entityManagerFactoryRef = "apiKeyEntityManagerFactory",
|
||||
transactionManagerRef = "apiKeyTransactionManager"
|
||||
basePackages = "com.kri.common.auth.persistence.repository",
|
||||
entityManagerFactoryRef = "apiKeyEntityManagerFactory",
|
||||
transactionManagerRef = "apiKeyTransactionManager"
|
||||
)
|
||||
@EnableConfigurationProperties(ApiKeyProperties.class)
|
||||
public class ApiKeyJpaAutoConfiguration {
|
||||
|
||||
@Bean(name = "apiKeyDataSource")
|
||||
public DataSource apiKeyDataSource(ApiKeyProperties props) {
|
||||
var db = props.getDb();
|
||||
HikariDataSource ds = new HikariDataSource();
|
||||
ds.setJdbcUrl(db.getUrl());
|
||||
ds.setUsername(db.getUsername());
|
||||
ds.setPassword(db.getPassword());
|
||||
ds.setDriverClassName(db.getDriverClassName());
|
||||
return ds;
|
||||
}
|
||||
/**
|
||||
* ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식
|
||||
* - intranet-extension처럼 HibernateJpaAutoConfiguration을 exclude 해도 동작
|
||||
*/
|
||||
@Bean(name = "apiKeyEntityManagerFactory")
|
||||
public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory(
|
||||
@Qualifier("apiKeyDataSource") DataSource ds,
|
||||
ObjectProvider<PersistenceUnitManager> pumProvider,
|
||||
ApiKeyProperties props
|
||||
) {
|
||||
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
vendorAdapter.setShowSql(props.getJpa().isShowSql());
|
||||
vendorAdapter.setGenerateDdl(false);
|
||||
@Bean(name = "apiKeyDataSource")
|
||||
public DataSource apiKeyDataSource(ApiKeyProperties props) {
|
||||
var db = props.getDb();
|
||||
HikariDataSource ds = new HikariDataSource();
|
||||
ds.setJdbcUrl(db.getUrl());
|
||||
ds.setUsername(db.getUsername());
|
||||
ds.setPassword(db.getPassword());
|
||||
ds.setDriverClassName(db.getDriverClassName());
|
||||
return ds;
|
||||
}
|
||||
|
||||
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
|
||||
emf.setDataSource(ds);
|
||||
emf.setJpaVendorAdapter(vendorAdapter);
|
||||
emf.setPackagesToScan("com.kri.common.auth.persistence.entity");
|
||||
emf.setPersistenceUnitName("apikey");
|
||||
/**
|
||||
* ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식 - intranet-extension처럼 HibernateJpaAutoConfiguration을
|
||||
* exclude 해도 동작
|
||||
*/
|
||||
@Bean(name = "apiKeyEntityManagerFactory")
|
||||
public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory(
|
||||
@Qualifier("apiKeyDataSource") DataSource ds,
|
||||
ObjectProvider<PersistenceUnitManager> pumProvider,
|
||||
ApiKeyProperties props
|
||||
) {
|
||||
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
vendorAdapter.setShowSql(props.getJpa().isShowSql());
|
||||
vendorAdapter.setGenerateDdl(false);
|
||||
|
||||
PersistenceUnitManager pum = pumProvider.getIfAvailable();
|
||||
if (pum != null) {
|
||||
emf.setPersistenceUnitManager(pum);
|
||||
}
|
||||
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
|
||||
emf.setDataSource(ds);
|
||||
emf.setJpaVendorAdapter(vendorAdapter);
|
||||
emf.setPackagesToScan("com.kri.common.auth.persistence.entity");
|
||||
emf.setPersistenceUnitName("apikey");
|
||||
|
||||
// 최소 JPA 속성들 (원하면 yml로 확장 가능)
|
||||
Map<String, Object> jpaProps = new HashMap<>();
|
||||
jpaProps.put("hibernate.show_sql", Boolean.toString(props.getJpa().isShowSql()));
|
||||
jpaProps.put("hibernate.format_sql", Boolean.toString(props.getJpa().isFormatSql()));
|
||||
|
||||
emf.setJpaPropertyMap(jpaProps);
|
||||
return emf;
|
||||
PersistenceUnitManager pum = pumProvider.getIfAvailable();
|
||||
if (pum != null) {
|
||||
emf.setPersistenceUnitManager(pum);
|
||||
}
|
||||
|
||||
@Bean(name = "apiKeyTransactionManager")
|
||||
public PlatformTransactionManager apiKeyTransactionManager(
|
||||
@Qualifier("apiKeyEntityManagerFactory") EntityManagerFactory emf
|
||||
) {
|
||||
return new JpaTransactionManager(emf);
|
||||
}
|
||||
// 최소 JPA 속성들 (원하면 yml로 확장 가능)
|
||||
Map<String, Object> jpaProps = new HashMap<>();
|
||||
jpaProps.put("hibernate.show_sql", Boolean.toString(props.getJpa().isShowSql()));
|
||||
jpaProps.put("hibernate.format_sql", Boolean.toString(props.getJpa().isFormatSql()));
|
||||
|
||||
/**
|
||||
* ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서
|
||||
* 'jpaMappingContext'가 없을 때만 보완해준다.
|
||||
*
|
||||
* 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다.
|
||||
*/
|
||||
@Bean(name = "jpaMappingContext")
|
||||
@ConditionalOnMissingBean(name = "jpaMappingContext")
|
||||
public JpaMetamodelMappingContextFactoryBean jpaMappingContext(ApplicationContext ctx) {
|
||||
// FactoryBean으로 등록하면 내부에서 EntityManagerFactory들을 찾아 Metamodel을 구성함
|
||||
return new JpaMetamodelMappingContextFactoryBean();
|
||||
}
|
||||
emf.setJpaPropertyMap(jpaProps);
|
||||
return emf;
|
||||
}
|
||||
|
||||
@Bean(name = "apiKeyTransactionManager")
|
||||
public PlatformTransactionManager apiKeyTransactionManager(
|
||||
@Qualifier("apiKeyEntityManagerFactory") EntityManagerFactory emf
|
||||
) {
|
||||
return new JpaTransactionManager(emf);
|
||||
}
|
||||
|
||||
/**
|
||||
* ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서 'jpaMappingContext'가 없을 때만 보완해준다.
|
||||
* <p>
|
||||
* 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다.
|
||||
*/
|
||||
@Bean(name = "jpaMappingContext")
|
||||
@ConditionalOnMissingBean(name = "jpaMappingContext")
|
||||
public JpaMetamodelMappingContextFactoryBean jpaMappingContext(ApplicationContext ctx) {
|
||||
// FactoryBean으로 등록하면 내부에서 EntityManagerFactory들을 찾아 Metamodel을 구성함
|
||||
return new JpaMetamodelMappingContextFactoryBean();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,13 +13,13 @@ import org.springframework.context.annotation.Bean;
|
||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
|
||||
public class ApiKeyPreloadAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(ApiKeyRepository.class) // ✅ apikey JPA 컨텍스트가 repo를 만들었을 때만
|
||||
@ConditionalOnMissingBean(ApiKeyUserClaimsProvider.class)
|
||||
public PreloadedApiKeyUserClaimsProvider apiKeyUserClaimsProvider(
|
||||
ApiKeyProperties props,
|
||||
ApiKeyRepository repo
|
||||
) {
|
||||
return new PreloadedApiKeyUserClaimsProvider(props, repo);
|
||||
}
|
||||
@Bean
|
||||
@ConditionalOnBean(ApiKeyRepository.class) // ✅ apikey JPA 컨텍스트가 repo를 만들었을 때만
|
||||
@ConditionalOnMissingBean(ApiKeyUserClaimsProvider.class)
|
||||
public PreloadedApiKeyUserClaimsProvider apiKeyUserClaimsProvider(
|
||||
ApiKeyProperties props,
|
||||
ApiKeyRepository repo
|
||||
) {
|
||||
return new PreloadedApiKeyUserClaimsProvider(props, repo);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +1,80 @@
|
||||
package com.kri.common.auth.apikey;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "kri.auth.apikey")
|
||||
public class ApiKeyProperties {
|
||||
|
||||
/**
|
||||
* API Key 인증 허용 여부
|
||||
*/
|
||||
private boolean enabled = false;
|
||||
/**
|
||||
* API Key 인증 허용 여부
|
||||
*/
|
||||
private boolean enabled = false;
|
||||
|
||||
/**
|
||||
* API Key 를 읽어올 헤더 이름 예: X-API-Key, X-EXTERNAL-KEY 등
|
||||
*/
|
||||
private String headerName = "X-API-Key";
|
||||
|
||||
/**
|
||||
* 이 서비스의 코드 (서비스별 preload 범위 결정)
|
||||
*/
|
||||
private String serviceCode;
|
||||
|
||||
/**
|
||||
* 기동 시 preload 할지
|
||||
*/
|
||||
private boolean preloadOnStartup = false;
|
||||
|
||||
/**
|
||||
* 내부 관리 API(리로드/조회) 노출 여부
|
||||
*/
|
||||
private boolean adminApiEnabled = false;
|
||||
|
||||
/**
|
||||
* 내부 관리 API 접근 허용 IP(CIDR)
|
||||
*/
|
||||
private List<String> adminAllowIps = List.of("127.0.0.1/32");
|
||||
|
||||
/**
|
||||
* apikey 전용 DB 설정(기본값 포함)
|
||||
*/
|
||||
private Db db = new Db();
|
||||
|
||||
/**
|
||||
* apikey 전용 JPA 옵션
|
||||
*/
|
||||
private Jpa jpa = new Jpa();
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Jpa {
|
||||
|
||||
/**
|
||||
* API Key 를 읽어올 헤더 이름
|
||||
* 예: X-API-Key, X-EXTERNAL-KEY 등
|
||||
* hibernate.show_sql
|
||||
*/
|
||||
private String headerName = "X-API-Key";
|
||||
private boolean showSql = false;
|
||||
|
||||
/** 이 서비스의 코드 (서비스별 preload 범위 결정) */
|
||||
private String serviceCode;
|
||||
|
||||
/** 기동 시 preload 할지 */
|
||||
private boolean preloadOnStartup = false;
|
||||
|
||||
/** 내부 관리 API(리로드/조회) 노출 여부 */
|
||||
private boolean adminApiEnabled = false;
|
||||
|
||||
/** 내부 관리 API 접근 허용 IP(CIDR) */
|
||||
private List<String> adminAllowIps = List.of("127.0.0.1/32");
|
||||
|
||||
/** apikey 전용 DB 설정(기본값 포함) */
|
||||
private Db db = new Db();
|
||||
|
||||
/** apikey 전용 JPA 옵션 */
|
||||
private Jpa jpa = new Jpa();
|
||||
|
||||
@Getter @Setter
|
||||
public static class Jpa {
|
||||
/** hibernate.show_sql */
|
||||
private boolean showSql = false;
|
||||
|
||||
/** hibernate.format_sql */
|
||||
private boolean formatSql = false;
|
||||
}
|
||||
/**
|
||||
* hibernate.format_sql
|
||||
*/
|
||||
private boolean formatSql = false;
|
||||
}
|
||||
|
||||
|
||||
@Getter @Setter
|
||||
public static class Db {
|
||||
//내부 통신용 url
|
||||
private String url =
|
||||
"jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8";
|
||||
private String username = "kriit";
|
||||
private String password = "it#51304";
|
||||
private String driverClassName = "com.mysql.cj.jdbc.Driver";
|
||||
}
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Db {
|
||||
|
||||
//내부 통신용 url
|
||||
private String url =
|
||||
"jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8";
|
||||
private String username = "kriit";
|
||||
private String password = "it#51304";
|
||||
private String driverClassName = "com.mysql.cj.jdbc.Driver";
|
||||
}
|
||||
}
|
||||
@@ -4,16 +4,16 @@ import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스.
|
||||
* 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면 된다.
|
||||
* 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스. 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면
|
||||
* 된다.
|
||||
*/
|
||||
public interface ApiKeyUserClaimsProvider {
|
||||
|
||||
/**
|
||||
* API Key 로 사용자 정보를 조회한다.
|
||||
*
|
||||
* @param apiKey 요청 헤더에서 받은 API Key
|
||||
* @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty()
|
||||
*/
|
||||
Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey);
|
||||
/**
|
||||
* API Key 로 사용자 정보를 조회한다.
|
||||
*
|
||||
* @param apiKey 요청 헤더에서 받은 API Key
|
||||
* @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty()
|
||||
*/
|
||||
Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey);
|
||||
}
|
||||
@@ -3,73 +3,89 @@ package com.kri.common.auth.apikey;
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import com.kri.common.auth.persistence.entity.TApiKeyEntity;
|
||||
import com.kri.common.auth.persistence.repository.ApiKeyRepository;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
|
||||
public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider, ApplicationRunner {
|
||||
public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider,
|
||||
ApplicationRunner {
|
||||
|
||||
private final ApiKeyProperties props;
|
||||
private final ApiKeyRepository repo;
|
||||
private final ApiKeyProperties props;
|
||||
private final ApiKeyRepository repo;
|
||||
|
||||
/** 캐시를 통째로 교체(swap)하기 위한 AtomicReference */
|
||||
private final AtomicReference<Map<String, JwtUserClaimsDto>> cacheRef =
|
||||
new AtomicReference<>(Collections.emptyMap());
|
||||
/**
|
||||
* 캐시를 통째로 교체(swap)하기 위한 AtomicReference
|
||||
*/
|
||||
private final AtomicReference<Map<String, JwtUserClaimsDto>> cacheRef =
|
||||
new AtomicReference<>(Collections.emptyMap());
|
||||
|
||||
public PreloadedApiKeyUserClaimsProvider(ApiKeyProperties props, ApiKeyRepository repo) {
|
||||
this.props = props;
|
||||
this.repo = repo;
|
||||
public PreloadedApiKeyUserClaimsProvider(ApiKeyProperties props, ApiKeyRepository repo) {
|
||||
this.props = props;
|
||||
this.repo = repo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 런타임에는 DB 조회 금지: 캐시만 조회
|
||||
*/
|
||||
@Override
|
||||
public Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey) {
|
||||
if (!StringUtils.hasText(apiKey)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(cacheRef.get().get(apiKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* 기동 시 preload
|
||||
*/
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
if (!props.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (!props.isPreloadOnStartup()) {
|
||||
return;
|
||||
}
|
||||
reloadFromDb();
|
||||
}
|
||||
|
||||
/**
|
||||
* 운영용: DB에서 다시 읽어 캐시 전체 교체
|
||||
*/
|
||||
public synchronized int reloadFromDb() {
|
||||
if (!StringUtils.hasText(props.getServiceCode())) {
|
||||
// serviceCode 없으면 preload 불가 → 안전하게 빈 캐시
|
||||
cacheRef.set(Collections.emptyMap());
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** 런타임에는 DB 조회 금지: 캐시만 조회 */
|
||||
@Override
|
||||
public Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey) {
|
||||
if (!StringUtils.hasText(apiKey)) return Optional.empty();
|
||||
return Optional.ofNullable(cacheRef.get().get(apiKey));
|
||||
var list = repo.findActiveKeysForService(props.getServiceCode());
|
||||
|
||||
Map<String, JwtUserClaimsDto> next = new ConcurrentHashMap<>(Math.max(16, list.size()));
|
||||
for (TApiKeyEntity e : list) {
|
||||
next.put(e.getApiKey(), JwtUserClaimsDto.builder()
|
||||
.userId(e.getUserId())
|
||||
.userCmpn(e.getUserCmpn())
|
||||
.userTeam(e.getUserTeam())
|
||||
.userName(e.getUserName())
|
||||
.userRole(e.getUserRole())
|
||||
.build());
|
||||
}
|
||||
|
||||
/** 기동 시 preload */
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
if (!props.isEnabled()) return;
|
||||
if (!props.isPreloadOnStartup()) return;
|
||||
reloadFromDb();
|
||||
}
|
||||
cacheRef.set(Collections.unmodifiableMap(next));
|
||||
return next.size();
|
||||
}
|
||||
|
||||
/** 운영용: DB에서 다시 읽어 캐시 전체 교체 */
|
||||
public synchronized int reloadFromDb() {
|
||||
if (!StringUtils.hasText(props.getServiceCode())) {
|
||||
// serviceCode 없으면 preload 불가 → 안전하게 빈 캐시
|
||||
cacheRef.set(Collections.emptyMap());
|
||||
return 0;
|
||||
}
|
||||
|
||||
var list = repo.findActiveKeysForService(props.getServiceCode());
|
||||
|
||||
Map<String, JwtUserClaimsDto> next = new ConcurrentHashMap<>(Math.max(16, list.size()));
|
||||
for (TApiKeyEntity e : list) {
|
||||
next.put(e.getApiKey(), JwtUserClaimsDto.builder()
|
||||
.userId(e.getUserId())
|
||||
.userCmpn(e.getUserCmpn())
|
||||
.userTeam(e.getUserTeam())
|
||||
.userName(e.getUserName())
|
||||
.userRole(e.getUserRole())
|
||||
.build());
|
||||
}
|
||||
|
||||
cacheRef.set(Collections.unmodifiableMap(next));
|
||||
return next.size();
|
||||
}
|
||||
|
||||
/** Admin 조회용(마스킹은 컨트롤러에서) */
|
||||
public Map<String, JwtUserClaimsDto> snapshot() {
|
||||
return cacheRef.get();
|
||||
}
|
||||
/**
|
||||
* Admin 조회용(마스킹은 컨트롤러에서)
|
||||
*/
|
||||
public Map<String, JwtUserClaimsDto> snapshot() {
|
||||
return cacheRef.get();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,25 +5,25 @@ import lombok.Builder;
|
||||
import lombok.Value;
|
||||
|
||||
@Schema(
|
||||
name = "JwtUserClaimsDto",
|
||||
description = "JWT에 포함되는 사용자 정보"
|
||||
name = "JwtUserClaimsDto",
|
||||
description = "JWT에 포함되는 사용자 정보"
|
||||
)
|
||||
@Value
|
||||
@Builder
|
||||
public class JwtUserClaimsDto {
|
||||
|
||||
@Schema(description = "사용자 ID")
|
||||
String userId;
|
||||
@Schema(description = "사용자 ID")
|
||||
String userId;
|
||||
|
||||
@Schema(description = "사용자 소속 회사")
|
||||
String userCmpn;
|
||||
@Schema(description = "사용자 소속 회사")
|
||||
String userCmpn;
|
||||
|
||||
@Schema(description = "팀 코드")
|
||||
String userTeam;
|
||||
@Schema(description = "팀 코드")
|
||||
String userTeam;
|
||||
|
||||
@Schema(description = "사용자 이름")
|
||||
String userName;
|
||||
@Schema(description = "사용자 이름")
|
||||
String userName;
|
||||
|
||||
@Schema(description = "권한 코드")
|
||||
Integer userRole;
|
||||
@Schema(description = "권한 코드")
|
||||
Integer userRole;
|
||||
}
|
||||
|
||||
@@ -13,22 +13,22 @@ import org.springframework.context.annotation.Configuration;
|
||||
@EnableConfigurationProperties({JwtProperties.class, ApiKeyProperties.class})
|
||||
public class JwtAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public JwtService jwtService(JwtProperties properties) {
|
||||
return new JwtService(properties);
|
||||
}
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public JwtService jwtService(JwtProperties properties) {
|
||||
return new JwtService(properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성.
|
||||
* (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서 addFilterBefore 로 수행)
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnBean(ApiKeyUserClaimsProvider.class)
|
||||
@ConditionalOnMissingBean
|
||||
public ApiKeyAuthFilter apiKeyAuthFilter(ApiKeyProperties apiKeyProperties,
|
||||
ApiKeyUserClaimsProvider provider,
|
||||
JwtService jwtService) {
|
||||
return new ApiKeyAuthFilter(apiKeyProperties, provider, jwtService);
|
||||
}
|
||||
/**
|
||||
* ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성. (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서
|
||||
* addFilterBefore 로 수행)
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnBean(ApiKeyUserClaimsProvider.class)
|
||||
@ConditionalOnMissingBean
|
||||
public ApiKeyAuthFilter apiKeyAuthFilter(ApiKeyProperties apiKeyProperties,
|
||||
ApiKeyUserClaimsProvider provider,
|
||||
JwtService jwtService) {
|
||||
return new ApiKeyAuthFilter(apiKeyProperties, provider, jwtService);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.kri.common.auth.jwt;
|
||||
|
||||
import lombok.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Getter
|
||||
@@ -10,23 +13,23 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
@ConfigurationProperties(prefix = "kri.auth.jwt")
|
||||
public class JwtProperties {
|
||||
|
||||
/**
|
||||
* HMAC 서명에 사용할 시크릿 키 (최소 32자 이상 권장)
|
||||
*/
|
||||
private String secret = "K0r2@#R2s2@rch#!nt2rn@t!0n@l#!T$T2@M";
|
||||
/**
|
||||
* HMAC 서명에 사용할 시크릿 키 (최소 32자 이상 권장)
|
||||
*/
|
||||
private String secret = "K0r2@#R2s2@rch#!nt2rn@t!0n@l#!T$T2@M";
|
||||
|
||||
/**
|
||||
* 토큰 발급자(issuer)
|
||||
*/
|
||||
private String issuer = "kri-it";
|
||||
/**
|
||||
* 토큰 발급자(issuer)
|
||||
*/
|
||||
private String issuer = "kri-it";
|
||||
|
||||
/**
|
||||
* Access Token 유효 시간(초 단위)
|
||||
*/
|
||||
private long accessTokenValiditySeconds = 24 * 3600; // 기본 24시간
|
||||
/**
|
||||
* Access Token 유효 시간(초 단위)
|
||||
*/
|
||||
private long accessTokenValiditySeconds = 24 * 3600; // 기본 24시간
|
||||
|
||||
/**
|
||||
* (선택) Refresh Token 유효 시간(초 단위)
|
||||
*/
|
||||
private long refreshTokenValiditySeconds = 7 * 24 * 3600; // 기본 7일
|
||||
/**
|
||||
* (선택) Refresh Token 유효 시간(초 단위)
|
||||
*/
|
||||
private long refreshTokenValiditySeconds = 7 * 24 * 3600; // 기본 7일
|
||||
}
|
||||
|
||||
@@ -1,189 +1,192 @@
|
||||
package com.kri.common.auth.jwt;
|
||||
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import io.jsonwebtoken.*;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jws;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.crypto.SecretKey;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 공통 JWT 유틸 서비스
|
||||
* - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱
|
||||
* - 일반 JWT + 내부 고정 토큰 둘 다 지원
|
||||
* 공통 JWT 유틸 서비스 - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱 - 일반 JWT + 내부 고정 토큰 둘 다 지원
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
public class JwtService {
|
||||
|
||||
private final JwtProperties properties;
|
||||
private final JwtProperties properties;
|
||||
|
||||
private SecretKey key;
|
||||
private SecretKey key;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
// 시크릿 검증: HS256 권장 최소 길이(32바이트 이상)
|
||||
String secret = properties.getSecret();
|
||||
if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) {
|
||||
throw new IllegalStateException("kri.auth.jwt.secret must be at least 32 bytes (UTF-8) for HS256");
|
||||
}
|
||||
// secret 문자열을 HMAC 키로 전환
|
||||
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
// 시크릿 검증: HS256 권장 최소 길이(32바이트 이상)
|
||||
String secret = properties.getSecret();
|
||||
if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) {
|
||||
throw new IllegalStateException(
|
||||
"kri.auth.jwt.secret must be at least 32 bytes (UTF-8) for HS256");
|
||||
}
|
||||
// secret 문자열을 HMAC 키로 전환
|
||||
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// 내부 공통 빌더
|
||||
// ======================================================
|
||||
|
||||
private String buildToken(Map<String, Object> claims, String subject, long validitySeconds) {
|
||||
Date now = new Date();
|
||||
Date expiry = new Date(now.getTime() + validitySeconds * 1000);
|
||||
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setSubject(subject)
|
||||
.setIssuer(properties.getIssuer())
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiry)
|
||||
.signWith(key, SignatureAlgorithm.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
private Map<String, Object> buildClaims(JwtUserClaimsDto dto) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
// 필요한 항목만 골라서 claim에 넣어줌
|
||||
claims.put("userId", dto.getUserId());
|
||||
claims.put("userCmpn", dto.getUserCmpn());
|
||||
claims.put("userTeam", dto.getUserTeam());
|
||||
claims.put("userName", dto.getUserName());
|
||||
claims.put("role", dto.getUserRole());
|
||||
return claims;
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// 토큰 생성 (DTO 기반)
|
||||
// ======================================================
|
||||
|
||||
/**
|
||||
* JwtUserClaimsDto 기반 Access Token 생성 - subject = userId - claims: userId, userCmpn, userTeam,
|
||||
* userName, role
|
||||
*/
|
||||
public String generateAccessToken(JwtUserClaimsDto userClaims) {
|
||||
Map<String, Object> claims = buildClaims(userClaims);
|
||||
return buildToken(
|
||||
claims,
|
||||
userClaims.getUserId(),
|
||||
properties.getAccessTokenValiditySeconds()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh Token은 보통 userId만 넣고 심플하게 사용
|
||||
*/
|
||||
public String generateRefreshToken(String userId) {
|
||||
return buildToken(
|
||||
Collections.emptyMap(),
|
||||
userId,
|
||||
properties.getRefreshTokenValiditySeconds()
|
||||
);
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// 토큰 파싱
|
||||
// ======================================================
|
||||
|
||||
/**
|
||||
* 토큰 파싱 + 서명/만료 검증
|
||||
*/
|
||||
public Jws<Claims> parseToken(String token) throws JwtException {
|
||||
return Jwts.parserBuilder()
|
||||
.requireIssuer(properties.getIssuer())
|
||||
.setSigningKey(key)
|
||||
.build()
|
||||
.parseClaimsJws(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰에서 Claims만 추출 (검증 포함)
|
||||
*/
|
||||
public Claims getClaims(String token) throws JwtException {
|
||||
return parseToken(token).getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* Claims → JwtUserClaimsDto 변환
|
||||
*/
|
||||
public JwtUserClaimsDto toUserClaimsDto(Claims claims) {
|
||||
// userId는 subject와 별도 claim 둘 다에서 시도
|
||||
String userId = claims.get("userId", String.class);
|
||||
if (userId == null) {
|
||||
userId = claims.getSubject();
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// 내부 공통 빌더
|
||||
// ======================================================
|
||||
String userCmpn = claims.get("userCmpn", String.class);
|
||||
String userTeam = claims.get("userTeam", String.class);
|
||||
String userName = claims.get("userName", String.class);
|
||||
|
||||
private String buildToken(Map<String, Object> claims, String subject, long validitySeconds) {
|
||||
Date now = new Date();
|
||||
Date expiry = new Date(now.getTime() + validitySeconds * 1000);
|
||||
// 숫자는 Integer / Long 등으로 들어올 수 있으니 Number로 받았다가 intValue()
|
||||
Number roleNumber = claims.get("role", Number.class);
|
||||
Integer userRole = roleNumber != null ? roleNumber.intValue() : null;
|
||||
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setSubject(subject)
|
||||
.setIssuer(properties.getIssuer())
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiry)
|
||||
.signWith(key, SignatureAlgorithm.HS256)
|
||||
.compact();
|
||||
return JwtUserClaimsDto.builder()
|
||||
.userId(userId)
|
||||
.userCmpn(userCmpn)
|
||||
.userTeam(userTeam)
|
||||
.userName(userName)
|
||||
.userRole(userRole)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰 → JwtUserClaimsDto 바로 추출
|
||||
*/
|
||||
public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException {
|
||||
Claims claims = getClaims(token);
|
||||
return toUserClaimsDto(claims);
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// Authentication 변환 (Spring Security 연동용)
|
||||
// ======================================================
|
||||
|
||||
/**
|
||||
* DTO → Spring Security Authentication 변환 여기서는 간단하게 "ROLE_{role값}" 형태로 Authority를 구성. ex) role =
|
||||
* 1 → "ROLE_1" 실제 프로젝트에서 0/1/2 같은 값에 대한 의미 매핑이 명확하다면, 이 메서드 안의 매핑 로직만 교체해서 쓰면 됨.
|
||||
*/
|
||||
public Authentication toAuthentication(JwtUserClaimsDto dto) {
|
||||
String principal = dto.getUserId();
|
||||
|
||||
List<GrantedAuthority> authorities = new ArrayList<>();
|
||||
if (dto.getUserRole() != null) {
|
||||
String authority = "ROLE_" + dto.getUserRole();
|
||||
authorities.add(new SimpleGrantedAuthority(authority));
|
||||
}
|
||||
|
||||
private Map<String, Object> buildClaims(JwtUserClaimsDto dto) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
// 필요한 항목만 골라서 claim에 넣어줌
|
||||
claims.put("userId", dto.getUserId());
|
||||
claims.put("userCmpn", dto.getUserCmpn());
|
||||
claims.put("userTeam", dto.getUserTeam());
|
||||
claims.put("userName", dto.getUserName());
|
||||
claims.put("role", dto.getUserRole());
|
||||
return claims;
|
||||
}
|
||||
return new UsernamePasswordAuthenticationToken(
|
||||
principal,
|
||||
null,
|
||||
authorities
|
||||
);
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// 토큰 생성 (DTO 기반)
|
||||
// ======================================================
|
||||
/**
|
||||
* JwtUserClaimsDto 기반 Access Token 생성
|
||||
* - subject = userId
|
||||
* - claims:
|
||||
* userId, userCmpn, userTeam, userName, role
|
||||
*/
|
||||
public String generateAccessToken(JwtUserClaimsDto userClaims) {
|
||||
Map<String, Object> claims = buildClaims(userClaims);
|
||||
return buildToken(
|
||||
claims,
|
||||
userClaims.getUserId(),
|
||||
properties.getAccessTokenValiditySeconds()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh Token은 보통 userId만 넣고 심플하게 사용
|
||||
*/
|
||||
public String generateRefreshToken(String userId) {
|
||||
return buildToken(
|
||||
Collections.emptyMap(),
|
||||
userId,
|
||||
properties.getRefreshTokenValiditySeconds()
|
||||
);
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// 토큰 파싱
|
||||
// ======================================================
|
||||
|
||||
/**
|
||||
* 토큰 파싱 + 서명/만료 검증
|
||||
*/
|
||||
public Jws<Claims> parseToken(String token) throws JwtException {
|
||||
return Jwts.parserBuilder()
|
||||
.requireIssuer(properties.getIssuer())
|
||||
.setSigningKey(key)
|
||||
.build()
|
||||
.parseClaimsJws(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰에서 Claims만 추출 (검증 포함)
|
||||
*/
|
||||
public Claims getClaims(String token) throws JwtException {
|
||||
return parseToken(token).getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* Claims → JwtUserClaimsDto 변환
|
||||
*/
|
||||
public JwtUserClaimsDto toUserClaimsDto(Claims claims) {
|
||||
// userId는 subject와 별도 claim 둘 다에서 시도
|
||||
String userId = claims.get("userId", String.class);
|
||||
if (userId == null) {
|
||||
userId = claims.getSubject();
|
||||
}
|
||||
|
||||
String userCmpn = claims.get("userCmpn", String.class);
|
||||
String userTeam = claims.get("userTeam", String.class);
|
||||
String userName = claims.get("userName", String.class);
|
||||
|
||||
// 숫자는 Integer / Long 등으로 들어올 수 있으니 Number로 받았다가 intValue()
|
||||
Number roleNumber = claims.get("role", Number.class);
|
||||
Integer userRole = roleNumber != null ? roleNumber.intValue() : null;
|
||||
|
||||
return JwtUserClaimsDto.builder()
|
||||
.userId(userId)
|
||||
.userCmpn(userCmpn)
|
||||
.userTeam(userTeam)
|
||||
.userName(userName)
|
||||
.userRole(userRole)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰 → JwtUserClaimsDto 바로 추출
|
||||
*/
|
||||
public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException {
|
||||
Claims claims = getClaims(token);
|
||||
return toUserClaimsDto(claims);
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// Authentication 변환 (Spring Security 연동용)
|
||||
// ======================================================
|
||||
|
||||
/**
|
||||
* DTO → Spring Security Authentication 변환
|
||||
* 여기서는 간단하게 "ROLE_{role값}" 형태로 Authority를 구성.
|
||||
* ex) role = 1 → "ROLE_1"
|
||||
* 실제 프로젝트에서 0/1/2 같은 값에 대한 의미 매핑이 명확하다면,
|
||||
* 이 메서드 안의 매핑 로직만 교체해서 쓰면 됨.
|
||||
*/
|
||||
public Authentication toAuthentication(JwtUserClaimsDto dto) {
|
||||
String principal = dto.getUserId();
|
||||
|
||||
List<GrantedAuthority> authorities = new ArrayList<>();
|
||||
if (dto.getUserRole() != null) {
|
||||
String authority = "ROLE_" + dto.getUserRole();
|
||||
authorities.add(new SimpleGrantedAuthority(authority));
|
||||
}
|
||||
|
||||
return new UsernamePasswordAuthenticationToken(
|
||||
principal,
|
||||
null,
|
||||
authorities
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰 → Authentication 변환 (JWT 파싱 + DTO 변환까지 한 번에)
|
||||
*/
|
||||
public Authentication toAuthentication(String token) throws JwtException {
|
||||
JwtUserClaimsDto dto = toUserClaimsDto(token);
|
||||
return toAuthentication(dto);
|
||||
}
|
||||
/**
|
||||
* 토큰 → Authentication 변환 (JWT 파싱 + DTO 변환까지 한 번에)
|
||||
*/
|
||||
public Authentication toAuthentication(String token) throws JwtException {
|
||||
JwtUserClaimsDto dto = toUserClaimsDto(token);
|
||||
return toAuthentication(dto);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +1,59 @@
|
||||
package com.kri.common.auth.persistence.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import org.hibernate.annotations.JdbcTypeCode;
|
||||
import org.hibernate.type.SqlTypes;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "t_api_key")
|
||||
public class TApiKeyEntity {
|
||||
@Id
|
||||
@Column(name = "api_key", nullable = false, length = 256)
|
||||
private String apiKey;
|
||||
|
||||
/** 1=ACTIVE, 0=REVOKED */
|
||||
@Column(name = "status", nullable = false)
|
||||
@ColumnDefault("1")
|
||||
private Short status;
|
||||
@Id
|
||||
@Column(name = "api_key", nullable = false, length = 256)
|
||||
private String apiKey;
|
||||
|
||||
@Column(name = "user_id", nullable = false, length = 32)
|
||||
private String userId;
|
||||
/**
|
||||
* 1=ACTIVE, 0=REVOKED
|
||||
*/
|
||||
@Column(name = "status", nullable = false)
|
||||
@ColumnDefault("1")
|
||||
private Short status;
|
||||
|
||||
@Column(name = "user_cmpn", length = 64)
|
||||
private String userCmpn;
|
||||
@Column(name = "user_id", nullable = false, length = 32)
|
||||
private String userId;
|
||||
|
||||
@Column(name = "user_team", length = 64)
|
||||
private String userTeam;
|
||||
@Column(name = "user_cmpn", length = 64)
|
||||
private String userCmpn;
|
||||
|
||||
@Column(name = "user_name", length = 64)
|
||||
private String userName;
|
||||
@Column(name = "user_team", length = 64)
|
||||
private String userTeam;
|
||||
|
||||
@Column(name = "user_role", nullable = false)
|
||||
private Integer userRole;
|
||||
@Column(name = "user_name", length = 64)
|
||||
private String userName;
|
||||
|
||||
/*기본 정보 외*/
|
||||
@Column(name = "user_json")
|
||||
@JdbcTypeCode(SqlTypes.JSON)
|
||||
private Map<String, Object> userJson;
|
||||
@Column(name = "user_role", nullable = false)
|
||||
private Integer userRole;
|
||||
|
||||
@Column(name = "reg_user", nullable = false, length = 32)
|
||||
private String regUser;
|
||||
/*기본 정보 외*/
|
||||
@Column(name = "user_json")
|
||||
@JdbcTypeCode(SqlTypes.JSON)
|
||||
private Map<String, Object> userJson;
|
||||
|
||||
@Column(name = "reg_dt", nullable = false)
|
||||
@ColumnDefault("CURRENT_TIMESTAMP")
|
||||
private LocalDateTime regDt;
|
||||
@Column(name = "reg_user", nullable = false, length = 32)
|
||||
private String regUser;
|
||||
|
||||
@Column(name = "reg_dt", nullable = false)
|
||||
@ColumnDefault("CURRENT_TIMESTAMP")
|
||||
private LocalDateTime regDt;
|
||||
|
||||
}
|
||||
|
||||
@@ -11,10 +11,15 @@ import lombok.Setter;
|
||||
@Entity
|
||||
@Table(name = "t_api_key_service_map")
|
||||
public class TApiKeyServiceMapEntity {
|
||||
@EmbeddedId
|
||||
private TApiKeyServiceMapEntityId id;
|
||||
|
||||
public String getApiKey() { return id.getApiKey(); }
|
||||
@EmbeddedId
|
||||
private TApiKeyServiceMapEntityId id;
|
||||
|
||||
public String getServiceCode() { return id.getServiceCode(); }
|
||||
public String getApiKey() {
|
||||
return id.getApiKey();
|
||||
}
|
||||
|
||||
public String getServiceCode() {
|
||||
return id.getServiceCode();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,36 +3,40 @@ package com.kri.common.auth.persistence.entity;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Embeddable;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.Hibernate;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Embeddable
|
||||
public class TApiKeyServiceMapEntityId implements Serializable {
|
||||
@NotNull
|
||||
@Column(name = "api_key", nullable = false, length = 256)
|
||||
private String apiKey;
|
||||
|
||||
@NotNull
|
||||
@Column(name = "service_code", nullable = false, length = 64)
|
||||
private String serviceCode;
|
||||
@NotNull
|
||||
@Column(name = "api_key", nullable = false, length = 256)
|
||||
private String apiKey;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
|
||||
TApiKeyServiceMapEntityId entity = (TApiKeyServiceMapEntityId) o;
|
||||
return Objects.equals(this.apiKey, entity.apiKey) &&
|
||||
Objects.equals(this.serviceCode, entity.serviceCode);
|
||||
@NotNull
|
||||
@Column(name = "service_code", nullable = false, length = 64)
|
||||
private String serviceCode;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(apiKey, serviceCode);
|
||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) {
|
||||
return false;
|
||||
}
|
||||
TApiKeyServiceMapEntityId entity = (TApiKeyServiceMapEntityId) o;
|
||||
return Objects.equals(this.apiKey, entity.apiKey) &&
|
||||
Objects.equals(this.serviceCode, entity.serviceCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(apiKey, serviceCode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
package com.kri.common.auth.persistence.repository;
|
||||
|
||||
import com.kri.common.auth.persistence.entity.TApiKeyEntity;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ApiKeyRepository extends JpaRepository<TApiKeyEntity, String> {
|
||||
/** ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에 */
|
||||
@Query("""
|
||||
select a
|
||||
from TApiKeyEntity a
|
||||
join TApiKeyServiceMapEntity m on m.id.apiKey = a.apiKey
|
||||
where a.status = 1 and m.id.serviceCode = :serviceCode
|
||||
""")
|
||||
List<TApiKeyEntity> findActiveKeysForService(@Param("serviceCode")String serviceCode);
|
||||
|
||||
/**
|
||||
* ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에
|
||||
*/
|
||||
@Query("""
|
||||
select a
|
||||
from TApiKeyEntity a
|
||||
join TApiKeyServiceMapEntity m on m.id.apiKey = a.apiKey
|
||||
where a.status = 1 and m.id.serviceCode = :serviceCode
|
||||
""")
|
||||
List<TApiKeyEntity> findActiveKeysForService(@Param("serviceCode") String serviceCode);
|
||||
}
|
||||
|
||||
@@ -1,115 +1,120 @@
|
||||
package com.kri.common.cache;
|
||||
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
public abstract class AbstractListCache<T> {
|
||||
|
||||
private List<T> list = List.of();
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private List<T> list = List.of();
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Transactional(readOnly = true)
|
||||
public void loadOnStartup() {
|
||||
List<T> tempList = loadFromDb();
|
||||
if(tempList != null) setList(tempList);
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Transactional(readOnly = true)
|
||||
public void loadOnStartup() {
|
||||
List<T> tempList = loadFromDb();
|
||||
if (tempList != null) {
|
||||
setList(tempList);
|
||||
}
|
||||
}
|
||||
|
||||
public List<T> getList() {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return list;
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void setList(List<T> next) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
this.list = List.copyOf(next == null ? List.of() : next);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> reload() {
|
||||
List<T> tempList = loadFromDb();
|
||||
if (tempList == null) {
|
||||
throw new UnsupportedOperationException("This cache does not support reload().");
|
||||
}
|
||||
setList(tempList);
|
||||
return getList();
|
||||
}
|
||||
|
||||
public List<T> clear() {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
return list = List.of();
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void addAll(List<T> items) {
|
||||
if (items == null || items.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
List<T> merged = new java.util.ArrayList<>(this.list);
|
||||
merged.addAll(items);
|
||||
this.list = List.copyOf(merged);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void addAll(int index, Collection<? extends T> items) {
|
||||
if (items == null || items.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
public List<T> getList() {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return list;
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
ArrayList<T> next = new ArrayList<>(this.list);
|
||||
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size로 보정
|
||||
next.addAll(i, new ArrayList<>(items));
|
||||
this.list = List.copyOf(next);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> reload() {
|
||||
List<T> tempList = loadFromDb();
|
||||
if(tempList == null) {
|
||||
throw new UnsupportedOperationException("This cache does not support reload().");
|
||||
}
|
||||
setList(tempList);
|
||||
return getList();
|
||||
public void add(T item) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
List<T> merged = new java.util.ArrayList<>(this.list);
|
||||
merged.add(item);
|
||||
this.list = List.copyOf(merged);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public List<T> clear() {
|
||||
lock.writeLock().lock();
|
||||
try{
|
||||
return list = List.of();
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
public void add(int index, T item) {
|
||||
lock.writeLock().lock();
|
||||
|
||||
try {
|
||||
ArrayList<T> next = new ArrayList<>(this.list);
|
||||
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size로 보정
|
||||
next.add(i, item);
|
||||
this.list = List.copyOf(next);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void setList(List<T> next) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
this.list = List.copyOf(next == null ? List.of() : next);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void addAll(List<T> items) {
|
||||
if (items == null || items.isEmpty()) return;
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
List<T> merged = new java.util.ArrayList<>(this.list);
|
||||
merged.addAll(items);
|
||||
this.list = List.copyOf(merged);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void addAll(int index, Collection<? extends T> items) {
|
||||
if (items == null || items.isEmpty()) return;
|
||||
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
ArrayList<T> next = new ArrayList<>(this.list);
|
||||
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size로 보정
|
||||
next.addAll(i, new ArrayList<>(items));
|
||||
this.list = List.copyOf(next);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void add(T item) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
List<T> merged = new java.util.ArrayList<>(this.list);
|
||||
merged.add(item);
|
||||
this.list = List.copyOf(merged);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void add(int index, T item){
|
||||
lock.writeLock().lock();
|
||||
|
||||
try{
|
||||
ArrayList<T> next = new ArrayList<>(this.list);
|
||||
int i = Math.max(0, Math.min(index, next.size())); // 0 ~ size로 보정
|
||||
next.add(i, item);
|
||||
this.list = List.copyOf(next);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
protected List<T> loadFromDb() {
|
||||
return null;
|
||||
}
|
||||
protected List<T> loadFromDb() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,110 +1,119 @@
|
||||
package com.kri.common.cache;
|
||||
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
public abstract class AbstractMapCache<K, V> {
|
||||
|
||||
private Map<K, V> map = Map.of();
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private Map<K, V> map = Map.of();
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Transactional(readOnly = true)
|
||||
public void loadOnStartup() {
|
||||
Map<K, V> tempMap = loadFromDb();
|
||||
if(tempMap != null) setMap(tempMap);
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Transactional(readOnly = true)
|
||||
public void loadOnStartup() {
|
||||
Map<K, V> tempMap = loadFromDb();
|
||||
if (tempMap != null) {
|
||||
setMap(tempMap);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<K, V> getMap() {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return map;
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 수동: 전체 교체(불변 스냅샷으로 보관)
|
||||
*/
|
||||
public void setMap(Map<K, V> next) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
this.map = Map.copyOf(next == null ? Map.of() : next);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public V get(K key) {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return map.get(key);
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean containsKey(K key) {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return map.containsKey(key);
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Map<K, V> reload() {
|
||||
Map<K, V> tempMap = loadFromDb();
|
||||
if (tempMap == null) {
|
||||
throw new UnsupportedOperationException("This cache does not support reload().");
|
||||
}
|
||||
setMap(tempMap);
|
||||
return getMap();
|
||||
}
|
||||
|
||||
public void put(K key, V value) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
Map<K, V> merged = new HashMap<>(this.map);
|
||||
merged.put(key, value);
|
||||
this.map = Map.copyOf(merged);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체)
|
||||
*/
|
||||
public void putAll(Map<K, V> entries) {
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
public Map<K, V> getMap() {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return map;
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
Map<K, V> merged = new HashMap<>(this.map);
|
||||
merged.putAll(entries);
|
||||
this.map = Map.copyOf(merged);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public V get(K key) {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return map.get(key);
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
/**
|
||||
* clear: 완전 비우기
|
||||
*/
|
||||
public void clear() {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
this.map = Map.of();
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean containsKey(K key) {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
return map.containsKey(key);
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Map<K, V> reload() {
|
||||
Map<K, V> tempMap = loadFromDb();
|
||||
if(tempMap == null) {
|
||||
throw new UnsupportedOperationException("This cache does not support reload().");
|
||||
}
|
||||
setMap(tempMap);
|
||||
return getMap();
|
||||
}
|
||||
|
||||
/** 수동: 전체 교체(불변 스냅샷으로 보관) */
|
||||
public void setMap(Map<K, V> next) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
this.map = Map.copyOf(next == null ? Map.of() : next);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void put(K key, V value) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
Map<K, V> merged = new HashMap<>(this.map);
|
||||
merged.put(key, value);
|
||||
this.map = Map.copyOf(merged);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/** 수동: 부분 적재(기존 + entries 합쳐서 스냅샷 교체) */
|
||||
public void putAll(Map<K, V> entries) {
|
||||
if (entries == null || entries.isEmpty()) return;
|
||||
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
Map<K, V> merged = new HashMap<>(this.map);
|
||||
merged.putAll(entries);
|
||||
this.map = Map.copyOf(merged);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/** clear: 완전 비우기 */
|
||||
public void clear() {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
this.map = Map.of();
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
// 서브클래스가 "DB에서 어떤 Map을 만들지"만 구현
|
||||
protected Map<K, V> loadFromDb() {
|
||||
return null;
|
||||
}
|
||||
// 서브클래스가 "DB에서 어떤 Map을 만들지"만 구현
|
||||
protected Map<K, V> loadFromDb() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,186 +1,273 @@
|
||||
package com.kri.common.datetime;
|
||||
|
||||
import java.time.*;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DateTimeUtil {
|
||||
|
||||
private DateTimeUtil() {}
|
||||
public static final ZoneId KST = ZoneId.of("Asia/Seoul");
|
||||
public static final ZoneId UTC = ZoneOffset.UTC;
|
||||
/**
|
||||
* 날짜+시간: 2025-11-28 15:00:14
|
||||
*/
|
||||
public static final DateTimeFormatter DATETIME_FMT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
/**
|
||||
* 날짜: 2025-11-28
|
||||
*/
|
||||
public static final DateTimeFormatter DATE_FMT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
public static final ZoneId KST = ZoneId.of("Asia/Seoul");
|
||||
public static final ZoneId UTC = ZoneOffset.UTC;
|
||||
private DateTimeUtil() {
|
||||
}
|
||||
|
||||
/** 날짜+시간: 2025-11-28 15:00:14 */
|
||||
public static final DateTimeFormatter DATETIME_FMT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
/* =======================
|
||||
* Now (KST)
|
||||
* ======================= */
|
||||
|
||||
/** 날짜: 2025-11-28 */
|
||||
public static final DateTimeFormatter DATE_FMT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
/**
|
||||
* 현재 KST 날짜+시간 문자열
|
||||
*/
|
||||
public static String nowKstDateTime() {
|
||||
return formatKst(Instant.now(), DATETIME_FMT);
|
||||
}
|
||||
|
||||
/* =======================
|
||||
* Now (KST)
|
||||
* ======================= */
|
||||
/**
|
||||
* 현재 KST 날짜 문자열
|
||||
*/
|
||||
public static String nowKstDate() {
|
||||
return nowKstZoned().format(DATE_FMT);
|
||||
}
|
||||
|
||||
/** 현재 KST 날짜+시간 문자열 */
|
||||
public static String nowKstDateTime() {
|
||||
return formatKst(Instant.now(), DATETIME_FMT);
|
||||
/**
|
||||
* 현재 KST ZonedDateTime
|
||||
*/
|
||||
public static ZonedDateTime nowKstZoned() {
|
||||
return Instant.now().atZone(KST);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 KST LocalDateTime
|
||||
*/
|
||||
public static LocalDateTime nowKstLocalDateTime() {
|
||||
return nowKstZoned().toLocalDateTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 KST LocalDate
|
||||
*/
|
||||
public static LocalDate nowKstLocalDate() {
|
||||
return nowKstZoned().toLocalDate();
|
||||
}
|
||||
|
||||
/* =======================
|
||||
* Format (Instant -> String)
|
||||
* ======================= */
|
||||
|
||||
/**
|
||||
* Instant -> KST 날짜+시간 문자열
|
||||
*/
|
||||
public static String formatKstDateTime(Instant instant) {
|
||||
return formatKst(instant, DATETIME_FMT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instant -> KST 날짜 문자열
|
||||
*/
|
||||
public static String formatKstDate(Instant instant) {
|
||||
return formatKst(instant, DATE_FMT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instant -> KST 문자열 (커스텀 포맷)
|
||||
*/
|
||||
public static String formatKst(Instant instant, DateTimeFormatter formatter) {
|
||||
if (instant == null) {
|
||||
return null;
|
||||
}
|
||||
final DateTimeFormatter fmt = (formatter != null) ? formatter : DATETIME_FMT;
|
||||
return instant.atZone(KST).format(fmt);
|
||||
}
|
||||
|
||||
/* =======================
|
||||
* Validate
|
||||
* ======================= */
|
||||
|
||||
/**
|
||||
* "yyyy-MM-dd" 형태인지
|
||||
*/
|
||||
public static boolean isDate(String text) {
|
||||
return tryParseLocalDate(text, DATE_FMT) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* "yyyy-MM-dd HH:mm:ss" 형태인지
|
||||
*/
|
||||
public static boolean isDateTime(String text) {
|
||||
return tryParseLocalDateTime(text, DATETIME_FMT) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* ISO Instant / ISO OffsetDateTime / ISO ZonedDateTime 중 하나인지
|
||||
*/
|
||||
public static boolean isIsoDateTime(String text) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 현재 KST 날짜 문자열 */
|
||||
public static String nowKstDate() {
|
||||
return nowKstZoned().format(DATE_FMT);
|
||||
final String s = text.trim();
|
||||
try {
|
||||
Instant.parse(s);
|
||||
return true;
|
||||
} catch (DateTimeParseException ignored) {
|
||||
}
|
||||
try {
|
||||
OffsetDateTime.parse(s);
|
||||
return true;
|
||||
} catch (DateTimeParseException ignored) {
|
||||
}
|
||||
try {
|
||||
ZonedDateTime.parse(s);
|
||||
return true;
|
||||
} catch (DateTimeParseException ignored) {
|
||||
}
|
||||
|
||||
/** 현재 KST ZonedDateTime */
|
||||
public static ZonedDateTime nowKstZoned() {
|
||||
return Instant.now().atZone(KST);
|
||||
return false;
|
||||
}
|
||||
|
||||
/* =======================
|
||||
* Parse (String -> Instant)
|
||||
* ======================= */
|
||||
|
||||
/**
|
||||
* ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도)
|
||||
*/
|
||||
public static Instant parseToInstant(String text) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 현재 KST LocalDateTime */
|
||||
public static LocalDateTime nowKstLocalDateTime() {
|
||||
return nowKstZoned().toLocalDateTime();
|
||||
final String s = text.trim();
|
||||
try {
|
||||
return Instant.parse(s);
|
||||
} catch (DateTimeParseException ignored) {
|
||||
}
|
||||
try {
|
||||
return OffsetDateTime.parse(s).toInstant();
|
||||
} catch (DateTimeParseException ignored) {
|
||||
}
|
||||
try {
|
||||
return ZonedDateTime.parse(s).toInstant();
|
||||
} catch (DateTimeParseException ignored) {
|
||||
}
|
||||
|
||||
/** 현재 KST LocalDate */
|
||||
public static LocalDate nowKstLocalDate() {
|
||||
return nowKstZoned().toLocalDate();
|
||||
throw new DateTimeParseException("Unsupported datetime format", s, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 포맷 문자열을 KST 기준으로 해석해서 Instant로 변환 예) "2025-11-28 15:00:14", formatter=DATETIME_FMT
|
||||
*/
|
||||
public static Instant parseKstToInstant(String text, DateTimeFormatter formatter) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
Objects.requireNonNull(formatter, "formatter");
|
||||
|
||||
/* =======================
|
||||
* Format (Instant -> String)
|
||||
* ======================= */
|
||||
LocalDateTime ldt = LocalDateTime.parse(text.trim(), formatter);
|
||||
return ldt.atZone(KST).toInstant();
|
||||
}
|
||||
|
||||
/** Instant -> KST 날짜+시간 문자열 */
|
||||
public static String formatKstDateTime(Instant instant) {
|
||||
return formatKst(instant, DATETIME_FMT);
|
||||
/**
|
||||
* "yyyy-MM-dd HH:mm:ss" 포맷을 KST로 해석
|
||||
*/
|
||||
public static Instant parseKstDateTimeToInstant(String text) {
|
||||
return parseKstToInstant(text, DATETIME_FMT);
|
||||
}
|
||||
|
||||
/**
|
||||
* "yyyy-MM-dd" 포맷을 KST 자정(00:00:00)으로 해석
|
||||
*/
|
||||
public static Instant parseKstDateToInstant(String text) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
LocalDate ld = LocalDate.parse(text.trim(), DATE_FMT);
|
||||
return ld.atStartOfDay(KST).toInstant();
|
||||
}
|
||||
|
||||
/** Instant -> KST 날짜 문자열 */
|
||||
public static String formatKstDate(Instant instant) {
|
||||
return formatKst(instant, DATE_FMT);
|
||||
/* =======================
|
||||
* Convert / Helpers
|
||||
* ======================= */
|
||||
|
||||
/**
|
||||
* Instant -> KST ZonedDateTime
|
||||
*/
|
||||
public static ZonedDateTime toKstZoned(Instant instant) {
|
||||
return instant == null ? null : instant.atZone(KST);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instant -> KST LocalDateTime
|
||||
*/
|
||||
public static LocalDateTime toKstLocalDateTime(Instant instant) {
|
||||
ZonedDateTime zdt = toKstZoned(instant);
|
||||
return zdt == null ? null : zdt.toLocalDateTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Instant -> KST LocalDate
|
||||
*/
|
||||
public static LocalDate toKstLocalDate(Instant instant) {
|
||||
ZonedDateTime zdt = toKstZoned(instant);
|
||||
return zdt == null ? null : zdt.toLocalDate();
|
||||
}
|
||||
|
||||
/**
|
||||
* null/blank 안전 trim
|
||||
*/
|
||||
public static String trimToNull(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
String t = s.trim();
|
||||
return t.isEmpty() ? null : t;
|
||||
}
|
||||
|
||||
/** Instant -> KST 문자열 (커스텀 포맷) */
|
||||
public static String formatKst(Instant instant, DateTimeFormatter formatter) {
|
||||
if (instant == null) return null;
|
||||
final DateTimeFormatter fmt = (formatter != null) ? formatter : DATETIME_FMT;
|
||||
return instant.atZone(KST).format(fmt);
|
||||
public static LocalDate parseLocalDate(String text) {
|
||||
return tryParseLocalDate(text, DATE_FMT);
|
||||
}
|
||||
|
||||
public static LocalDateTime parseLocalDateTime(String text) {
|
||||
return tryParseLocalDateTime(text, DATETIME_FMT);
|
||||
}
|
||||
|
||||
private static LocalDate tryParseLocalDate(String text, DateTimeFormatter fmt) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/* =======================
|
||||
* Validate
|
||||
* ======================= */
|
||||
|
||||
/** "yyyy-MM-dd" 형태인지 */
|
||||
public static boolean isDate(String text) {
|
||||
return tryParseLocalDate(text, DATE_FMT) != null;
|
||||
try {
|
||||
return LocalDate.parse(text.trim(), fmt);
|
||||
} catch (DateTimeParseException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** "yyyy-MM-dd HH:mm:ss" 형태인지 */
|
||||
public static boolean isDateTime(String text) {
|
||||
return tryParseLocalDateTime(text, DATETIME_FMT) != null;
|
||||
private static LocalDateTime tryParseLocalDateTime(String text, DateTimeFormatter fmt) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** ISO Instant / ISO OffsetDateTime / ISO ZonedDateTime 중 하나인지 */
|
||||
public static boolean isIsoDateTime(String text) {
|
||||
if (text == null || text.isBlank()) return false;
|
||||
|
||||
final String s = text.trim();
|
||||
try { Instant.parse(s); return true; } catch (DateTimeParseException ignored) {}
|
||||
try { OffsetDateTime.parse(s); return true; } catch (DateTimeParseException ignored) {}
|
||||
try { ZonedDateTime.parse(s); return true; } catch (DateTimeParseException ignored) {}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/* =======================
|
||||
* Parse (String -> Instant)
|
||||
* ======================= */
|
||||
|
||||
/** ISO 계열 문자열을 Instant로 파싱 (Instant/OffsetDateTime/ZonedDateTime 순으로 시도) */
|
||||
public static Instant parseToInstant(String text) {
|
||||
if (text == null || text.isBlank()) return null;
|
||||
|
||||
final String s = text.trim();
|
||||
try { return Instant.parse(s); } catch (DateTimeParseException ignored) {}
|
||||
try { return OffsetDateTime.parse(s).toInstant(); } catch (DateTimeParseException ignored) {}
|
||||
try { return ZonedDateTime.parse(s).toInstant(); } catch (DateTimeParseException ignored) {}
|
||||
|
||||
throw new DateTimeParseException("Unsupported datetime format", s, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 커스텀 포맷 문자열을 KST 기준으로 해석해서 Instant로 변환
|
||||
* 예) "2025-11-28 15:00:14", formatter=DATETIME_FMT
|
||||
*/
|
||||
public static Instant parseKstToInstant(String text, DateTimeFormatter formatter) {
|
||||
if (text == null || text.isBlank()) return null;
|
||||
Objects.requireNonNull(formatter, "formatter");
|
||||
|
||||
LocalDateTime ldt = LocalDateTime.parse(text.trim(), formatter);
|
||||
return ldt.atZone(KST).toInstant();
|
||||
}
|
||||
|
||||
/** "yyyy-MM-dd HH:mm:ss" 포맷을 KST로 해석 */
|
||||
public static Instant parseKstDateTimeToInstant(String text) {
|
||||
return parseKstToInstant(text, DATETIME_FMT);
|
||||
}
|
||||
|
||||
/** "yyyy-MM-dd" 포맷을 KST 자정(00:00:00)으로 해석 */
|
||||
public static Instant parseKstDateToInstant(String text) {
|
||||
if (text == null || text.isBlank()) return null;
|
||||
LocalDate ld = LocalDate.parse(text.trim(), DATE_FMT);
|
||||
return ld.atStartOfDay(KST).toInstant();
|
||||
}
|
||||
|
||||
/* =======================
|
||||
* Convert / Helpers
|
||||
* ======================= */
|
||||
|
||||
/** Instant -> KST ZonedDateTime */
|
||||
public static ZonedDateTime toKstZoned(Instant instant) {
|
||||
return instant == null ? null : instant.atZone(KST);
|
||||
}
|
||||
|
||||
/** Instant -> KST LocalDateTime */
|
||||
public static LocalDateTime toKstLocalDateTime(Instant instant) {
|
||||
ZonedDateTime zdt = toKstZoned(instant);
|
||||
return zdt == null ? null : zdt.toLocalDateTime();
|
||||
}
|
||||
|
||||
/** Instant -> KST LocalDate */
|
||||
public static LocalDate toKstLocalDate(Instant instant) {
|
||||
ZonedDateTime zdt = toKstZoned(instant);
|
||||
return zdt == null ? null : zdt.toLocalDate();
|
||||
}
|
||||
|
||||
/** null/blank 안전 trim */
|
||||
public static String trimToNull(String s) {
|
||||
if (s == null) return null;
|
||||
String t = s.trim();
|
||||
return t.isEmpty() ? null : t;
|
||||
}
|
||||
|
||||
public static LocalDate parseLocalDate(String text) {
|
||||
return tryParseLocalDate(text, DATE_FMT);
|
||||
}
|
||||
|
||||
public static LocalDateTime parseLocalDateTime(String text) {
|
||||
return tryParseLocalDateTime(text, DATETIME_FMT);
|
||||
}
|
||||
|
||||
private static LocalDate tryParseLocalDate(String text, DateTimeFormatter fmt) {
|
||||
if (text == null || text.isBlank()) return null;
|
||||
try { return LocalDate.parse(text.trim(), fmt); }
|
||||
catch (DateTimeParseException e) { return null; }
|
||||
}
|
||||
|
||||
private static LocalDateTime tryParseLocalDateTime(String text, DateTimeFormatter fmt) {
|
||||
if (text == null || text.isBlank()) return null;
|
||||
try { return LocalDateTime.parse(text.trim(), fmt); }
|
||||
catch (DateTimeParseException e) { return null; }
|
||||
try {
|
||||
return LocalDateTime.parse(text.trim(), fmt);
|
||||
} catch (DateTimeParseException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,11 @@ package com.kri.common.datetime;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@@ -12,12 +15,12 @@ import java.lang.annotation.*;
|
||||
@JsonDeserialize(using = LenientLocalDateTimeDeserializer.class)
|
||||
public @interface LenientLocalDateTime {
|
||||
|
||||
String[] patterns() default {
|
||||
"yyyy-MM-dd",
|
||||
"yyyy-MM-dd HH",
|
||||
"yyyy-MM-dd HH:mm",
|
||||
"yyyy-MM-dd HH:mm:ss",
|
||||
"yyyy-MM-dd'T'HH:mm",
|
||||
"yyyy-MM-dd'T'HH:mm:ss"
|
||||
};
|
||||
String[] patterns() default {
|
||||
"yyyy-MM-dd",
|
||||
"yyyy-MM-dd HH",
|
||||
"yyyy-MM-dd HH:mm",
|
||||
"yyyy-MM-dd HH:mm:ss",
|
||||
"yyyy-MM-dd'T'HH:mm",
|
||||
"yyyy-MM-dd'T'HH:mm:ss"
|
||||
};
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -16,72 +15,79 @@ import java.time.temporal.ChronoField;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class LenientLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime>
|
||||
implements ContextualDeserializer {
|
||||
implements ContextualDeserializer {
|
||||
|
||||
private final DateTimeFormatter[] formatters;
|
||||
private final DateTimeFormatter[] formatters;
|
||||
|
||||
public LenientLocalDateTimeDeserializer() {
|
||||
this(new String[]{
|
||||
"yyyy-MM-dd",
|
||||
"yyyy-MM-dd HH",
|
||||
"yyyy-MM-dd HH:mm",
|
||||
"yyyy-MM-dd HH:mm:ss",
|
||||
"yyyy-MM-dd'T'HH:mm",
|
||||
"yyyy-MM-dd'T'HH:mm:ss"
|
||||
});
|
||||
public LenientLocalDateTimeDeserializer() {
|
||||
this(new String[]{
|
||||
"yyyy-MM-dd",
|
||||
"yyyy-MM-dd HH",
|
||||
"yyyy-MM-dd HH:mm",
|
||||
"yyyy-MM-dd HH:mm:ss",
|
||||
"yyyy-MM-dd'T'HH:mm",
|
||||
"yyyy-MM-dd'T'HH:mm:ss"
|
||||
});
|
||||
}
|
||||
|
||||
private LenientLocalDateTimeDeserializer(String[] patterns) {
|
||||
this.formatters = Arrays.stream(patterns)
|
||||
.map(LenientLocalDateTimeDeserializer::withDefaultTimeParts)
|
||||
.toArray(DateTimeFormatter[]::new);
|
||||
}
|
||||
|
||||
private static DateTimeFormatter withDefaultTimeParts(String pattern) {
|
||||
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder()
|
||||
.appendPattern(pattern);
|
||||
|
||||
// 초(ss)가 있는 패턴이면 ".밀리초(1~3자리)"를 옵션으로 허용
|
||||
// 예: 2025-12-19T14:50:12.1 / .12 / .123
|
||||
// (pattern 자체에 S가 들어간 경우는 중복 추가 방지)
|
||||
if (pattern.contains("ss") && !pattern.contains("S")) {
|
||||
b.optionalStart()
|
||||
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 3, true) // true => '.' 포함
|
||||
.optionalEnd();
|
||||
}
|
||||
|
||||
private LenientLocalDateTimeDeserializer(String[] patterns) {
|
||||
this.formatters = Arrays.stream(patterns)
|
||||
.map(LenientLocalDateTimeDeserializer::withDefaultTimeParts)
|
||||
.toArray(DateTimeFormatter[]::new);
|
||||
// 패턴에 분/초가 없으면 0으로 채움 (날짜만 와도 LocalDateTime으로 만들 수 있게)
|
||||
return b
|
||||
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
|
||||
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
|
||||
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
|
||||
.parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
|
||||
.toFormatter();
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||
String s = DateTimeUtil.trimToNull(p.getText());
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
private static DateTimeFormatter withDefaultTimeParts(String pattern) {
|
||||
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder()
|
||||
.appendPattern(pattern);
|
||||
|
||||
// 초(ss)가 있는 패턴이면 ".밀리초(1~3자리)"를 옵션으로 허용
|
||||
// 예: 2025-12-19T14:50:12.1 / .12 / .123
|
||||
// (pattern 자체에 S가 들어간 경우는 중복 추가 방지)
|
||||
if (pattern.contains("ss") && !pattern.contains("S")) {
|
||||
b.optionalStart()
|
||||
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 3, true) // true => '.' 포함
|
||||
.optionalEnd();
|
||||
}
|
||||
|
||||
// 패턴에 분/초가 없으면 0으로 채움 (날짜만 와도 LocalDateTime으로 만들 수 있게)
|
||||
return b
|
||||
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
|
||||
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
|
||||
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
|
||||
.parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
|
||||
.toFormatter();
|
||||
for (DateTimeFormatter f : formatters) {
|
||||
try {
|
||||
return LocalDateTime.parse(s, f);
|
||||
} catch (DateTimeParseException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||
String s = DateTimeUtil.trimToNull(p.getText());
|
||||
if (s == null) return null;
|
||||
throw ctxt.weirdStringException(s, LocalDateTime.class,
|
||||
"Unsupported datetime format. Expected one of patterns defined in @LenientLocalDateTime");
|
||||
}
|
||||
|
||||
for (DateTimeFormatter f : formatters) {
|
||||
try {
|
||||
return LocalDateTime.parse(s, f);
|
||||
} catch (DateTimeParseException ignored) {}
|
||||
}
|
||||
|
||||
throw ctxt.weirdStringException(s, LocalDateTime.class,
|
||||
"Unsupported datetime format. Expected one of patterns defined in @LenientLocalDateTime");
|
||||
@Override
|
||||
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
|
||||
throws JsonMappingException {
|
||||
if (property == null) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
|
||||
throws JsonMappingException {
|
||||
if (property == null) return this;
|
||||
|
||||
LenientLocalDateTime ann = property.getAnnotation(LenientLocalDateTime.class);
|
||||
if (ann == null) ann = property.getContextAnnotation(LenientLocalDateTime.class);
|
||||
|
||||
return (ann == null) ? this : new LenientLocalDateTimeDeserializer(ann.patterns());
|
||||
LenientLocalDateTime ann = property.getAnnotation(LenientLocalDateTime.class);
|
||||
if (ann == null) {
|
||||
ann = property.getContextAnnotation(LenientLocalDateTime.class);
|
||||
}
|
||||
|
||||
return (ann == null) ? this : new LenientLocalDateTimeDeserializer(ann.patterns());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.kri.common.enums;
|
||||
|
||||
public interface CodeEnum<T> {
|
||||
T getCode();
|
||||
|
||||
T getCode();
|
||||
}
|
||||
@@ -2,19 +2,22 @@ package com.kri.common.enums;
|
||||
|
||||
public final class CodeEnumUtils {
|
||||
|
||||
private CodeEnumUtils() {}
|
||||
private CodeEnumUtils() {
|
||||
}
|
||||
|
||||
public static <E extends Enum<E> & CodeEnum<V>, V> E fromCode(Class<E> enumClass, V code) {
|
||||
if (code == null) return null;
|
||||
|
||||
for (E e : enumClass.getEnumConstants()) {
|
||||
if (e.getCode().equals(code)) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException(
|
||||
"Unknown code [" + code + "] for enum class " + enumClass.getName()
|
||||
);
|
||||
public static <E extends Enum<E> & CodeEnum<V>, V> E fromCode(Class<E> enumClass, V code) {
|
||||
if (code == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (E e : enumClass.getEnumConstants()) {
|
||||
if (e.getCode().equals(code)) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException(
|
||||
"Unknown code [" + code + "] for enum class " + enumClass.getName()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,17 @@
|
||||
package com.kri.common.excel;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.FIELD)
|
||||
public @interface ExcelColumn {
|
||||
String header(); // 엑셀 헤더 이름
|
||||
int order() default 0; // 컬럼 순서
|
||||
int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로
|
||||
|
||||
String header(); // 엑셀 헤더 이름
|
||||
|
||||
int order() default 0; // 컬럼 순서
|
||||
|
||||
int width() default -1; // 문자 수 기준, -1이면 autoSize 그대로
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,37 +1,35 @@
|
||||
package com.kri.common.excel;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
|
||||
public final class ExcelUtil {
|
||||
|
||||
private ExcelUtil() {}
|
||||
private ExcelUtil() {
|
||||
}
|
||||
|
||||
public static String getStringCell(Cell cell) {
|
||||
if (cell == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return switch (cell.getCellType()) {
|
||||
case STRING -> cell.getStringCellValue();
|
||||
case NUMERIC -> {
|
||||
if (DateUtil.isCellDateFormatted(cell)) {
|
||||
yield cell.getDateCellValue().toString();
|
||||
} else {
|
||||
double d = cell.getNumericCellValue();
|
||||
if (d == Math.rint(d)) {
|
||||
yield String.valueOf((long) d);
|
||||
}
|
||||
yield String.valueOf(d);
|
||||
}
|
||||
}
|
||||
case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
|
||||
case FORMULA -> cell.getCellFormula();
|
||||
case BLANK -> null;
|
||||
default -> null; // ERROR, _NONE 등 나머지 타입
|
||||
};
|
||||
public static String getStringCell(Cell cell) {
|
||||
if (cell == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return switch (cell.getCellType()) {
|
||||
case STRING -> cell.getStringCellValue();
|
||||
case NUMERIC -> {
|
||||
if (DateUtil.isCellDateFormatted(cell)) {
|
||||
yield cell.getDateCellValue().toString();
|
||||
} else {
|
||||
double d = cell.getNumericCellValue();
|
||||
if (d == Math.rint(d)) {
|
||||
yield String.valueOf((long) d);
|
||||
}
|
||||
yield String.valueOf(d);
|
||||
}
|
||||
}
|
||||
case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
|
||||
case FORMULA -> cell.getCellFormula();
|
||||
case BLANK -> null;
|
||||
default -> null; // ERROR, _NONE 등 나머지 타입
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,52 +3,57 @@ package com.kri.common.file;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class FileUtil {
|
||||
private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-zA-Z0-9._-]");
|
||||
|
||||
/**
|
||||
* 파일명에서 위험한 문자 제거
|
||||
*/
|
||||
public static String sanitizeFileName(String original) {
|
||||
if (original == null || original.isBlank()) {
|
||||
return "file";
|
||||
}
|
||||
String name = original.trim().replace("\\", "/");
|
||||
int idx = name.lastIndexOf('/');
|
||||
if (idx >= 0 && idx < name.length() - 1) {
|
||||
name = name.substring(idx + 1);
|
||||
}
|
||||
name = FILENAME_SANITIZE.matcher(name).replaceAll("_");
|
||||
// 너무 짧으면 기본값
|
||||
if (name.isBlank()) {
|
||||
return "file";
|
||||
}
|
||||
return name;
|
||||
}
|
||||
private static final Pattern FILENAME_SANITIZE = Pattern.compile("[^a-zA-Z0-9._-]");
|
||||
|
||||
public static String getExtension(String fileName) {
|
||||
if (fileName == null) return "";
|
||||
int dot = fileName.lastIndexOf('.');
|
||||
if (dot < 0 || dot == fileName.length() - 1) {
|
||||
return "";
|
||||
}
|
||||
return fileName.substring(dot + 1);
|
||||
/**
|
||||
* 파일명에서 위험한 문자 제거
|
||||
*/
|
||||
public static String sanitizeFileName(String original) {
|
||||
if (original == null || original.isBlank()) {
|
||||
return "file";
|
||||
}
|
||||
String name = original.trim().replace("\\", "/");
|
||||
int idx = name.lastIndexOf('/');
|
||||
if (idx >= 0 && idx < name.length() - 1) {
|
||||
name = name.substring(idx + 1);
|
||||
}
|
||||
name = FILENAME_SANITIZE.matcher(name).replaceAll("_");
|
||||
// 너무 짧으면 기본값
|
||||
if (name.isBlank()) {
|
||||
return "file";
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
public static String extractFileNameFromPath(String pathLike) {
|
||||
if (pathLike == null || pathLike.isBlank()) return "";
|
||||
String s = pathLike;
|
||||
int q = s.indexOf('?');
|
||||
if (q >= 0) {
|
||||
s = s.substring(0, q);
|
||||
}
|
||||
int hash = s.indexOf('#');
|
||||
if (hash >= 0) {
|
||||
s = s.substring(0, hash);
|
||||
}
|
||||
int slash = s.lastIndexOf('/');
|
||||
if (slash >= 0 && slash < s.length() - 1) {
|
||||
return s.substring(slash + 1);
|
||||
}
|
||||
return s;
|
||||
public static String getExtension(String fileName) {
|
||||
if (fileName == null) {
|
||||
return "";
|
||||
}
|
||||
int dot = fileName.lastIndexOf('.');
|
||||
if (dot < 0 || dot == fileName.length() - 1) {
|
||||
return "";
|
||||
}
|
||||
return fileName.substring(dot + 1);
|
||||
}
|
||||
|
||||
public static String extractFileNameFromPath(String pathLike) {
|
||||
if (pathLike == null || pathLike.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
String s = pathLike;
|
||||
int q = s.indexOf('?');
|
||||
if (q >= 0) {
|
||||
s = s.substring(0, q);
|
||||
}
|
||||
int hash = s.indexOf('#');
|
||||
if (hash >= 0) {
|
||||
s = s.substring(0, hash);
|
||||
}
|
||||
int slash = s.lastIndexOf('/');
|
||||
if (slash >= 0 && slash < s.length() - 1) {
|
||||
return s.substring(slash + 1);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,91 +9,94 @@ import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 간단한 외부 API 통신 모듈.
|
||||
* - url, 추가 헤더, body를 받아 호출합니다.
|
||||
* - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다.
|
||||
* - body는 문자열(JSON 등) 기준입니다.
|
||||
* 간단한 외부 API 통신 모듈. - url, 추가 헤더, body를 받아 호출합니다. - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다. -
|
||||
* body는 문자열(JSON 등) 기준입니다.
|
||||
*/
|
||||
public class ExternalApiClient {
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final Duration requestTimeout;
|
||||
private final HttpClient httpClient;
|
||||
private final Duration requestTimeout;
|
||||
|
||||
/**
|
||||
* 기본 생성자 (커넥션 풀/타임아웃 기본값 세팅)
|
||||
*/
|
||||
public ExternalApiClient() {
|
||||
this(HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.build(), Duration.ofSeconds(30));
|
||||
/**
|
||||
* 기본 생성자 (커넥션 풀/타임아웃 기본값 세팅)
|
||||
*/
|
||||
public ExternalApiClient() {
|
||||
this(HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.build(), Duration.ofSeconds(30));
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 지정 HttpClient/요청 타임아웃으로 생성
|
||||
*/
|
||||
public ExternalApiClient(HttpClient httpClient, Duration requestTimeout) {
|
||||
this.httpClient = httpClient;
|
||||
this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout;
|
||||
}
|
||||
|
||||
private static HttpRequest.BodyPublisher buildBodyPublisher(String method, String body) {
|
||||
// GET/DELETE 등 body 없는 메서드는 noBody 사용
|
||||
if (body == null || body.isEmpty()) {
|
||||
return switch (method) {
|
||||
case "POST", "PUT", "PATCH" -> HttpRequest.BodyPublishers.ofString("");
|
||||
default -> HttpRequest.BodyPublishers.noBody();
|
||||
};
|
||||
}
|
||||
return HttpRequest.BodyPublishers.ofString(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자 지정 HttpClient/요청 타임아웃으로 생성
|
||||
*/
|
||||
public ExternalApiClient(HttpClient httpClient, Duration requestTimeout) {
|
||||
this.httpClient = httpClient;
|
||||
this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout;
|
||||
}
|
||||
|
||||
public ExternalApiResponse get(String url, Map<String, String> headers) {
|
||||
return send("GET", url, headers, null);
|
||||
}
|
||||
|
||||
public ExternalApiResponse delete(String url, Map<String, String> headers) {
|
||||
return send("DELETE", url, headers, null);
|
||||
}
|
||||
|
||||
public ExternalApiResponse post(String url, Map<String, String> headers, String body) {
|
||||
return send("POST", url, headers, body);
|
||||
}
|
||||
|
||||
public ExternalApiResponse put(String url, Map<String, String> headers, String body) {
|
||||
return send("PUT", url, headers, body);
|
||||
}
|
||||
|
||||
public ExternalApiResponse patch(String url, Map<String, String> headers, String body) {
|
||||
return send("PATCH", url, headers, body);
|
||||
}
|
||||
|
||||
private ExternalApiResponse send(String method, String url, Map<String, String> headers, String body) {
|
||||
try {
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder()
|
||||
.uri(URI.create(url))
|
||||
.timeout(requestTimeout)
|
||||
.method(method, buildBodyPublisher(method, body));
|
||||
|
||||
// 추가 헤더 설정
|
||||
if (headers != null) {
|
||||
headers.forEach((k, v) -> {
|
||||
if (k != null && v != null) builder.header(k, v);
|
||||
});
|
||||
}
|
||||
|
||||
// body가 있고 Content-Type이 없다면 기본 application/json
|
||||
if (body != null && (headers == null || !headers.keySet().stream()
|
||||
.map(String::toLowerCase).anyMatch("content-type"::equals))) {
|
||||
builder.header("Content-Type", "application/json; charset=utf-8");
|
||||
}
|
||||
|
||||
HttpRequest request = builder.build();
|
||||
HttpResponse<String> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
|
||||
} catch (IOException | InterruptedException e) {
|
||||
// 인터럽트 복원
|
||||
if (e instanceof InterruptedException) Thread.currentThread().interrupt();
|
||||
throw new RuntimeException("External API 호출 중 오류가 발생했습니다: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpRequest.BodyPublisher buildBodyPublisher(String method, String body) {
|
||||
// GET/DELETE 등 body 없는 메서드는 noBody 사용
|
||||
if (body == null || body.isEmpty()) {
|
||||
return switch (method) {
|
||||
case "POST", "PUT", "PATCH" -> HttpRequest.BodyPublishers.ofString("");
|
||||
default -> HttpRequest.BodyPublishers.noBody();
|
||||
};
|
||||
}
|
||||
return HttpRequest.BodyPublishers.ofString(body);
|
||||
public ExternalApiResponse get(String url, Map<String, String> headers) {
|
||||
return send("GET", url, headers, null);
|
||||
}
|
||||
|
||||
public ExternalApiResponse delete(String url, Map<String, String> headers) {
|
||||
return send("DELETE", url, headers, null);
|
||||
}
|
||||
|
||||
public ExternalApiResponse post(String url, Map<String, String> headers, String body) {
|
||||
return send("POST", url, headers, body);
|
||||
}
|
||||
|
||||
public ExternalApiResponse put(String url, Map<String, String> headers, String body) {
|
||||
return send("PUT", url, headers, body);
|
||||
}
|
||||
|
||||
public ExternalApiResponse patch(String url, Map<String, String> headers, String body) {
|
||||
return send("PATCH", url, headers, body);
|
||||
}
|
||||
|
||||
private ExternalApiResponse send(String method, String url, Map<String, String> headers,
|
||||
String body) {
|
||||
try {
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder()
|
||||
.uri(URI.create(url))
|
||||
.timeout(requestTimeout)
|
||||
.method(method, buildBodyPublisher(method, body));
|
||||
|
||||
// 추가 헤더 설정
|
||||
if (headers != null) {
|
||||
headers.forEach((k, v) -> {
|
||||
if (k != null && v != null) {
|
||||
builder.header(k, v);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// body가 있고 Content-Type이 없다면 기본 application/json
|
||||
if (body != null && (headers == null || !headers.keySet().stream()
|
||||
.map(String::toLowerCase).anyMatch("content-type"::equals))) {
|
||||
builder.header("Content-Type", "application/json; charset=utf-8");
|
||||
}
|
||||
|
||||
HttpRequest request = builder.build();
|
||||
HttpResponse<String> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
|
||||
} catch (IOException | InterruptedException e) {
|
||||
// 인터럽트 복원
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
throw new RuntimeException("External API 호출 중 오류가 발생했습니다: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,29 +8,30 @@ import java.util.Map;
|
||||
* 외부 API 호출 결과를 단순하게 담는 DTO.
|
||||
*/
|
||||
public class ExternalApiResponse {
|
||||
private final int statusCode;
|
||||
private final Map<String, List<String>> headers;
|
||||
private final String body;
|
||||
|
||||
public ExternalApiResponse(int statusCode, Map<String, List<String>> headers, String body) {
|
||||
this.statusCode = statusCode;
|
||||
this.headers = headers;
|
||||
this.body = body;
|
||||
}
|
||||
private final int statusCode;
|
||||
private final Map<String, List<String>> headers;
|
||||
private final String body;
|
||||
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
public ExternalApiResponse(int statusCode, Map<String, List<String>> headers, String body) {
|
||||
this.statusCode = statusCode;
|
||||
this.headers = headers;
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public Map<String, List<String>> getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
|
||||
return new ExternalApiResponse(status, headers.map(), body);
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
|
||||
return new ExternalApiResponse(status, headers.map(), body);
|
||||
}
|
||||
public Map<String, List<String>> getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,23 +5,23 @@ import com.kri.common.enums.CodeEnumUtils;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
|
||||
public abstract class AbstractCodeEnumConverter<
|
||||
E extends Enum<E> & CodeEnum<V>,
|
||||
V
|
||||
> implements AttributeConverter<E, V> {
|
||||
E extends Enum<E> & CodeEnum<V>,
|
||||
V
|
||||
> implements AttributeConverter<E, V> {
|
||||
|
||||
private final Class<E> enumClass;
|
||||
private final Class<E> enumClass;
|
||||
|
||||
protected AbstractCodeEnumConverter(Class<E> enumClass) {
|
||||
this.enumClass = enumClass;
|
||||
}
|
||||
protected AbstractCodeEnumConverter(Class<E> enumClass) {
|
||||
this.enumClass = enumClass;
|
||||
}
|
||||
|
||||
@Override
|
||||
public V convertToDatabaseColumn(E attribute) {
|
||||
return attribute == null ? null : attribute.getCode();
|
||||
}
|
||||
@Override
|
||||
public V convertToDatabaseColumn(E attribute) {
|
||||
return attribute == null ? null : attribute.getCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public E convertToEntityAttribute(V dbData) {
|
||||
return CodeEnumUtils.fromCode(enumClass, dbData);
|
||||
}
|
||||
@Override
|
||||
public E convertToEntityAttribute(V dbData) {
|
||||
return CodeEnumUtils.fromCode(enumClass, dbData);
|
||||
}
|
||||
}
|
||||
@@ -2,36 +2,41 @@ package com.kri.common.jpa;
|
||||
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.PrePersist;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@MappedSuperclass
|
||||
public abstract class BaseUuidEntity {
|
||||
protected abstract String getId();
|
||||
protected abstract void setId(String id);
|
||||
|
||||
/** 엔티티마다 컬럼 길이에 맞춰 오버라이드 */
|
||||
protected int idLength() { return 32; }
|
||||
private static String generateId(int length) {
|
||||
String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars
|
||||
|
||||
@PrePersist
|
||||
protected void prePersistId() {
|
||||
if (getId() == null || getId().isBlank()) {
|
||||
setId(generateId(idLength()));
|
||||
}
|
||||
if (length <= 32) {
|
||||
return base.substring(0, length);
|
||||
}
|
||||
|
||||
private static String generateId(int length) {
|
||||
String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars
|
||||
|
||||
if (length <= 32) {
|
||||
return base.substring(0, length);
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder(length);
|
||||
sb.append(base);
|
||||
while (sb.length() < length) {
|
||||
sb.append(UUID.randomUUID().toString().replace("-", ""));
|
||||
}
|
||||
return sb.substring(0, length);
|
||||
StringBuilder sb = new StringBuilder(length);
|
||||
sb.append(base);
|
||||
while (sb.length() < length) {
|
||||
sb.append(UUID.randomUUID().toString().replace("-", ""));
|
||||
}
|
||||
return sb.substring(0, length);
|
||||
}
|
||||
|
||||
protected abstract String getId();
|
||||
|
||||
protected abstract void setId(String id);
|
||||
|
||||
/**
|
||||
* 엔티티마다 컬럼 길이에 맞춰 오버라이드
|
||||
*/
|
||||
protected int idLength() {
|
||||
return 32;
|
||||
}
|
||||
|
||||
@PrePersist
|
||||
protected void prePersistId() {
|
||||
if (getId() == null || getId().isBlank()) {
|
||||
setId(generateId(idLength()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,122 +3,120 @@ package com.kri.common.json;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
public final class JsonUtil {
|
||||
|
||||
private JsonUtil() {
|
||||
// 유틸 클래스 - 인스턴스 생성 방지
|
||||
}
|
||||
private JsonUtil() {
|
||||
// 유틸 클래스 - 인스턴스 생성 방지
|
||||
}
|
||||
|
||||
/**
|
||||
* 임의의 자바 객체를 Map으로 변환한다.
|
||||
* 주의: JSON 문자열(String)을 파싱하는 용도가 아니라,
|
||||
* 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는 용도이다.
|
||||
*/
|
||||
public static <T> Map<String, Object> toMap(ObjectMapper objectMapper, T source) {
|
||||
if (source == null) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(source, Map.class);
|
||||
return map;
|
||||
/**
|
||||
* 임의의 자바 객체를 Map으로 변환한다. 주의: JSON 문자열(String)을 파싱하는 용도가 아니라, 이미 객체로 있는 DTO/Entity 등을 Map으로 바꾸는
|
||||
* 용도이다.
|
||||
*/
|
||||
public static <T> Map<String, Object> toMap(ObjectMapper objectMapper, T source) {
|
||||
if (source == null) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(source, Map.class);
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 문자열을 Map으로 파싱한다.
|
||||
*
|
||||
* @param json JSON 텍스트 (null 또는 blank면 빈 Map 반환)
|
||||
*/
|
||||
public static Map<String, Object> parseJsonToMap(ObjectMapper objectMapper, String json) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("JSON을 Map으로 파싱하는 중 오류가 발생했습니다.", e);
|
||||
}
|
||||
/**
|
||||
* JSON 문자열을 Map으로 파싱한다.
|
||||
*
|
||||
* @param json JSON 텍스트 (null 또는 blank면 빈 Map 반환)
|
||||
*/
|
||||
public static Map<String, Object> parseJsonToMap(ObjectMapper objectMapper, String json) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("JSON을 Map으로 파싱하는 중 오류가 발생했습니다.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 객체를 JSON 문자열로 직렬화한다.
|
||||
*/
|
||||
public static String toJson(ObjectMapper objectMapper, Object value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException("객체를 JSON 문자열로 변환하는 중 오류가 발생했습니다.", e);
|
||||
}
|
||||
/**
|
||||
* 객체를 JSON 문자열로 직렬화한다.
|
||||
*/
|
||||
public static String toJson(ObjectMapper objectMapper, Object value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException("객체를 JSON 문자열로 변환하는 중 오류가 발생했습니다.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 객체를 사람이 읽기 좋은 pretty JSON 문자열로 직렬화한다.
|
||||
*/
|
||||
public static String toPrettyJson(ObjectMapper objectMapper, Object value) {
|
||||
try {
|
||||
return objectMapper.writerWithDefaultPrettyPrinter()
|
||||
.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException("객체를 pretty JSON 문자열로 변환하는 중 오류가 발생했습니다.", e);
|
||||
}
|
||||
/**
|
||||
* 객체를 사람이 읽기 좋은 pretty JSON 문자열로 직렬화한다.
|
||||
*/
|
||||
public static String toPrettyJson(ObjectMapper objectMapper, Object value) {
|
||||
try {
|
||||
return objectMapper.writerWithDefaultPrettyPrinter()
|
||||
.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalArgumentException("객체를 pretty JSON 문자열로 변환하는 중 오류가 발생했습니다.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 문자열을 주어진 타입으로 역직렬화한다.
|
||||
* ex) fromJson(mapper, json, UserInfoDto.class)
|
||||
*/
|
||||
public static <T> T fromJson(ObjectMapper objectMapper, String json, Class<T> type) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, type);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("JSON을 " + type.getSimpleName() + " 으로 파싱하는 중 오류가 발생했습니다.", e);
|
||||
}
|
||||
/**
|
||||
* JSON 문자열을 주어진 타입으로 역직렬화한다. ex) fromJson(mapper, json, UserInfoDto.class)
|
||||
*/
|
||||
public static <T> T fromJson(ObjectMapper objectMapper, String json, Class<T> type) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, type);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("JSON을 " + type.getSimpleName() + " 으로 파싱하는 중 오류가 발생했습니다.",
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 문자열을 제네릭 타입으로 역직렬화한다.
|
||||
* ex) fromJson(mapper, json, new TypeReference<List<UserInfoDto>>() {})
|
||||
*/
|
||||
public static <T> T fromJson(ObjectMapper objectMapper, String json, TypeReference<T> typeRef) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, typeRef);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("JSON을 제네릭 타입으로 파싱하는 중 오류가 발생했습니다.", e);
|
||||
}
|
||||
/**
|
||||
* JSON 문자열을 제네릭 타입으로 역직렬화한다. ex) fromJson(mapper, json, new TypeReference<List<UserInfoDto>>()
|
||||
* {})
|
||||
*/
|
||||
public static <T> T fromJson(ObjectMapper objectMapper, String json, TypeReference<T> typeRef) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, typeRef);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("JSON을 제네릭 타입으로 파싱하는 중 오류가 발생했습니다.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 기반 deep copy (또는 타입 변환).
|
||||
* 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다.
|
||||
*
|
||||
* ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class);
|
||||
*/
|
||||
public static <T> T deepCopy(ObjectMapper objectMapper, T source, Class<T> targetType) {
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
return objectMapper.convertValue(source, targetType);
|
||||
/**
|
||||
* JSON 기반 deep copy (또는 타입 변환). 내부적으로 convertValue를 사용하므로, source를 targetType 형태로 깊은 복사/매핑한다.
|
||||
* <p>
|
||||
* ex) UserInfoDto dto2 = deepCopy(mapper, dto1, UserInfoDto.class);
|
||||
*/
|
||||
public static <T> T deepCopy(ObjectMapper objectMapper, T source, Class<T> targetType) {
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
return objectMapper.convertValue(source, targetType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용.
|
||||
*
|
||||
* ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class);
|
||||
*/
|
||||
public static <S, T> T convert(ObjectMapper objectMapper, S source, Class<T> targetType) {
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
return objectMapper.convertValue(source, targetType);
|
||||
/**
|
||||
* 서로 다른 타입 간에 JSON 기반 매핑을 할 때 사용.
|
||||
* <p>
|
||||
* ex) UserInfoDto dto = convert(mapper, entity, UserInfoDto.class);
|
||||
*/
|
||||
public static <S, T> T convert(ObjectMapper objectMapper, S source, Class<T> targetType) {
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
return objectMapper.convertValue(source, targetType);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
package com.kri.common.redis;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.*;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.*;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
|
||||
@AutoConfiguration
|
||||
@ConditionalOnClass(RedisTemplate.class)
|
||||
@@ -12,11 +16,16 @@ import org.springframework.data.redis.core.*;
|
||||
@ConditionalOnBean(RedisConnectionFactory.class)
|
||||
public class CommonRedisAutoConfiguration {
|
||||
|
||||
@Bean @ConditionalOnMissingBean
|
||||
public StringRedisTemplate stringRedisTemplate(org.springframework.data.redis.connection.RedisConnectionFactory cf) {
|
||||
return new StringRedisTemplate(cf);
|
||||
}
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public StringRedisTemplate stringRedisTemplate(
|
||||
org.springframework.data.redis.connection.RedisConnectionFactory cf) {
|
||||
return new StringRedisTemplate(cf);
|
||||
}
|
||||
|
||||
@Bean @ConditionalOnMissingBean
|
||||
public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) { return new RedisQueueHelper(rt); }
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) {
|
||||
return new RedisQueueHelper(rt);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
package com.kri.common.redis;
|
||||
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import java.time.Duration;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
|
||||
public class RedisQueueHelper {
|
||||
private final StringRedisTemplate rt;
|
||||
public RedisQueueHelper(StringRedisTemplate rt) { this.rt = rt; }
|
||||
public void enqueue(String key, String value) { rt.opsForList().rightPush(key, value); }
|
||||
public String blockingDequeue(String key, Duration timeout) { return rt.opsForList().leftPop(key, timeout); }
|
||||
|
||||
private final StringRedisTemplate rt;
|
||||
|
||||
public RedisQueueHelper(StringRedisTemplate rt) {
|
||||
this.rt = rt;
|
||||
}
|
||||
|
||||
public void enqueue(String key, String value) {
|
||||
rt.opsForList().rightPush(key, value);
|
||||
}
|
||||
|
||||
public String blockingDequeue(String key, Duration timeout) {
|
||||
return rt.opsForList().leftPop(key, timeout);
|
||||
}
|
||||
}
|
||||
@@ -7,4 +7,6 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
@AutoConfiguration
|
||||
@EnableScheduling
|
||||
@ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true", matchIfMissing = false)
|
||||
public class CommonSchedulingAutoConfiguration { }
|
||||
public class CommonSchedulingAutoConfiguration {
|
||||
|
||||
}
|
||||
@@ -6,43 +6,42 @@ import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtService jwtService;
|
||||
private final JwtService jwtService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
// 이미 인증이 있다면 건너뜀 (API-Key 필터 등에서 먼저 세팅했을 수 있음)
|
||||
if (SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header != null && header.startsWith("Bearer ")) {
|
||||
String token = header.substring("Bearer ".length());
|
||||
try {
|
||||
// ★ 오직 "정상 JWT" 만 처리
|
||||
Authentication auth = jwtService.toAuthentication(token);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
} catch (JwtException ex) {
|
||||
// 여기서 바로 401 내고 끊고 싶으면 이렇게 할 수도 있고:
|
||||
// response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
// return;
|
||||
//
|
||||
// 기본값은 "인증 세팅 안 함" + 나머지 필터 → 결국 anyRequest().authenticated()에서 401 떨어짐
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
// 이미 인증이 있다면 건너뜀 (API-Key 필터 등에서 먼저 세팅했을 수 있음)
|
||||
if (SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header != null && header.startsWith("Bearer ")) {
|
||||
String token = header.substring("Bearer ".length());
|
||||
try {
|
||||
// ★ 오직 "정상 JWT" 만 처리
|
||||
Authentication auth = jwtService.toAuthentication(token);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
} catch (JwtException ex) {
|
||||
// 여기서 바로 401 내고 끊고 싶으면 이렇게 할 수도 있고:
|
||||
// response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
// return;
|
||||
//
|
||||
// 기본값은 "인증 세팅 안 함" + 나머지 필터 → 결국 anyRequest().authenticated()에서 401 떨어짐
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
package com.kri.common.security;
|
||||
|
||||
import com.kri.common.auth.apikey.ApiKeyAuthFilter;
|
||||
import com.kri.common.auth.apikey.ApiKeyProperties;
|
||||
import com.kri.common.auth.apikey.ApiKeyUserClaimsProvider;
|
||||
import com.kri.common.auth.jwt.JwtProperties;
|
||||
import com.kri.common.auth.jwt.JwtService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -15,73 +13,74 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@AutoConfiguration(before = SecurityAutoConfiguration.class)
|
||||
@EnableConfigurationProperties({KriSecurityProperties.class, JwtProperties.class})
|
||||
@ConditionalOnProperty(prefix = "kri.security", name = "enabled", havingValue = "true", matchIfMissing = true)
|
||||
@EnableMethodSecurity(
|
||||
jsr250Enabled = true,
|
||||
prePostEnabled = true
|
||||
jsr250Enabled = true,
|
||||
prePostEnabled = true
|
||||
)
|
||||
@RequiredArgsConstructor
|
||||
public class KriSecurityAutoConfiguration {
|
||||
|
||||
private final KriSecurityProperties securityProperties;
|
||||
private final JwtProperties jwtProperties;
|
||||
private final KriSecurityProperties securityProperties;
|
||||
private final JwtProperties jwtProperties;
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public JwtService jwtService(JwtProperties properties) {
|
||||
return new JwtService(properties);
|
||||
}
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public JwtService jwtService(JwtProperties properties) {
|
||||
return new JwtService(properties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public JwtAuthenticationFilter jwtAuthenticationFilter(JwtService jwtService) {
|
||||
return new JwtAuthenticationFilter(jwtService);
|
||||
}
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public JwtAuthenticationFilter jwtAuthenticationFilter(JwtService jwtService) {
|
||||
return new JwtAuthenticationFilter(jwtService);
|
||||
}
|
||||
|
||||
/**
|
||||
* 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면
|
||||
* 이 기본 Security 구성이 적용된다.
|
||||
*/
|
||||
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(SecurityFilterChain.class)
|
||||
public SecurityFilterChain kriSecurityFilterChain(
|
||||
HttpSecurity http,
|
||||
ObjectProvider<ApiKeyAuthFilter> apiKeyAuthFilterProvider,
|
||||
JwtAuthenticationFilter jwtAuthenticationFilter
|
||||
) throws Exception {
|
||||
/**
|
||||
* 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면 이 기본 Security 구성이 적용된다.
|
||||
*/
|
||||
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(SecurityFilterChain.class)
|
||||
public SecurityFilterChain kriSecurityFilterChain(
|
||||
HttpSecurity http,
|
||||
ObjectProvider<ApiKeyAuthFilter> apiKeyAuthFilterProvider,
|
||||
JwtAuthenticationFilter jwtAuthenticationFilter
|
||||
) throws Exception {
|
||||
|
||||
http
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.cors(Customizer.withDefaults())
|
||||
.sessionManagement(session ->
|
||||
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
)
|
||||
.authorizeHttpRequests(auth -> {
|
||||
// ✅ yaml에서 정의한 public-paths 전부 permitAll
|
||||
if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths().isEmpty()) {
|
||||
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new)).permitAll();
|
||||
}
|
||||
// ✅ 나머지는 전부 인증 필요
|
||||
auth.anyRequest().authenticated();
|
||||
});
|
||||
http
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.cors(Customizer.withDefaults())
|
||||
.sessionManagement(session ->
|
||||
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
)
|
||||
.authorizeHttpRequests(auth -> {
|
||||
// ✅ yaml에서 정의한 public-paths 전부 permitAll
|
||||
if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths()
|
||||
.isEmpty()) {
|
||||
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new))
|
||||
.permitAll();
|
||||
}
|
||||
// ✅ 나머지는 전부 인증 필요
|
||||
auth.anyRequest().authenticated();
|
||||
});
|
||||
|
||||
// ✅ API Key 필터가 존재하면 먼저 태움
|
||||
apiKeyAuthFilterProvider.ifAvailable(filter ->
|
||||
http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class)
|
||||
);
|
||||
// ✅ 그 다음 JWT 필터
|
||||
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
// ✅ API Key 필터가 존재하면 먼저 태움
|
||||
apiKeyAuthFilterProvider.ifAvailable(filter ->
|
||||
http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class)
|
||||
);
|
||||
// ✅ 그 다음 JWT 필터
|
||||
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,26 @@
|
||||
package com.kri.common.security;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "kri.security")
|
||||
public class KriSecurityProperties {
|
||||
|
||||
/**
|
||||
* 이 자동구성 사용 여부
|
||||
*/
|
||||
private boolean enabled = true;
|
||||
/**
|
||||
* 이 자동구성 사용 여부
|
||||
*/
|
||||
private boolean enabled = true;
|
||||
|
||||
/**
|
||||
* 인증 없이 허용할 URL 패턴들
|
||||
* 서비스에서 application.yml로 오버라이드
|
||||
*/
|
||||
private List<String> publicPaths = List.of(
|
||||
"/v3/api-docs/**",
|
||||
"/swagger-ui.html",
|
||||
"/swagger-ui/**"
|
||||
);
|
||||
/**
|
||||
* 인증 없이 허용할 URL 패턴들 서비스에서 application.yml로 오버라이드
|
||||
*/
|
||||
private List<String> publicPaths = List.of(
|
||||
"/v3/api-docs/**",
|
||||
"/swagger-ui.html",
|
||||
"/swagger-ui/**"
|
||||
);
|
||||
}
|
||||
@@ -22,56 +22,56 @@ import org.springframework.context.annotation.Bean;
|
||||
@RequiredArgsConstructor
|
||||
public class KriSwaggerAutoConfiguration {
|
||||
|
||||
private final KriSwaggerProperties properties;
|
||||
private final ApiKeyProperties apiKeyProperties; // apikey.header-name 읽어오기 위해
|
||||
private final KriSwaggerProperties properties;
|
||||
private final ApiKeyProperties apiKeyProperties; // apikey.header-name 읽어오기 위해
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public OpenAPI kriOpenAPI() {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public OpenAPI kriOpenAPI() {
|
||||
|
||||
// 🔐 JWT Bearer + API-Key 스키마 정의
|
||||
Components components = new Components()
|
||||
.addSecuritySchemes("BearerAuth",
|
||||
new SecurityScheme()
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT"))
|
||||
.addSecuritySchemes("ApiKeyAuth",
|
||||
new SecurityScheme()
|
||||
.type(SecurityScheme.Type.APIKEY)
|
||||
.in(SecurityScheme.In.HEADER)
|
||||
.name(apiKeyProperties.getHeaderName())); // 예: X-API-Key
|
||||
// 🔐 JWT Bearer + API-Key 스키마 정의
|
||||
Components components = new Components()
|
||||
.addSecuritySchemes("BearerAuth",
|
||||
new SecurityScheme()
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT"))
|
||||
.addSecuritySchemes("ApiKeyAuth",
|
||||
new SecurityScheme()
|
||||
.type(SecurityScheme.Type.APIKEY)
|
||||
.in(SecurityScheme.In.HEADER)
|
||||
.name(apiKeyProperties.getHeaderName())); // 예: X-API-Key
|
||||
|
||||
// 🔐 기본적으로 두 보안 스키마를 전역에 적용
|
||||
SecurityRequirement securityRequirement = new SecurityRequirement()
|
||||
.addList("BearerAuth")
|
||||
.addList("ApiKeyAuth");
|
||||
// 🔐 기본적으로 두 보안 스키마를 전역에 적용
|
||||
SecurityRequirement securityRequirement = new SecurityRequirement()
|
||||
.addList("BearerAuth")
|
||||
.addList("ApiKeyAuth");
|
||||
|
||||
return new OpenAPI()
|
||||
.components(components)
|
||||
.addSecurityItem(securityRequirement)
|
||||
.info(new Info()
|
||||
.title(properties.getTitle())
|
||||
.description(properties.getDescription())
|
||||
.version(properties.getVersion())
|
||||
);
|
||||
return new OpenAPI()
|
||||
.components(components)
|
||||
.addSecurityItem(securityRequirement)
|
||||
.info(new Info()
|
||||
.title(properties.getTitle())
|
||||
.description(properties.getDescription())
|
||||
.version(properties.getVersion())
|
||||
);
|
||||
}
|
||||
|
||||
@Bean(name = "kriGroupedOpenApi")
|
||||
@ConditionalOnMissingBean(name = "kriGroupedOpenApi")
|
||||
public GroupedOpenApi kriGroupedOpenApi() {
|
||||
GroupedOpenApi.Builder builder = GroupedOpenApi.builder()
|
||||
.group("kri-api")
|
||||
.pathsToMatch("/api/**", "/internal/**");
|
||||
|
||||
String base = properties.getBasePackage();
|
||||
if (base != null && !base.isBlank()) {
|
||||
builder.packagesToScan(
|
||||
base,
|
||||
"com.kri.common.auth.apikey"
|
||||
);
|
||||
}
|
||||
|
||||
@Bean(name = "kriGroupedOpenApi")
|
||||
@ConditionalOnMissingBean(name = "kriGroupedOpenApi")
|
||||
public GroupedOpenApi kriGroupedOpenApi() {
|
||||
GroupedOpenApi.Builder builder = GroupedOpenApi.builder()
|
||||
.group("kri-api")
|
||||
.pathsToMatch("/api/**", "/internal/**");
|
||||
|
||||
String base = properties.getBasePackage();
|
||||
if (base != null && !base.isBlank()) {
|
||||
builder.packagesToScan(
|
||||
base,
|
||||
"com.kri.common.auth.apikey"
|
||||
);
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
@@ -9,14 +9,14 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
@ConfigurationProperties(prefix = "kri.swagger")
|
||||
public class KriSwaggerProperties {
|
||||
|
||||
private boolean enabled = true;
|
||||
private boolean enabled = true;
|
||||
|
||||
private String title = "KRI API";
|
||||
private String description = "KRI Common API Docs";
|
||||
private String version = "v1";
|
||||
private String title = "KRI API";
|
||||
private String description = "KRI Common API Docs";
|
||||
private String version = "v1";
|
||||
|
||||
/**
|
||||
* 문서화할 base package (null 이면 전체)
|
||||
*/
|
||||
private String basePackage;
|
||||
/**
|
||||
* 문서화할 base package (null 이면 전체)
|
||||
*/
|
||||
private String basePackage;
|
||||
}
|
||||
|
||||
@@ -4,40 +4,44 @@ import java.util.UUID;
|
||||
|
||||
public final class CommonUtil {
|
||||
|
||||
public static String uuid32() {
|
||||
return UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
public static String uuid32() {
|
||||
return UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
public static boolean isNumeric(String s) {
|
||||
if (s == null || s.isBlank()) return false;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
if (c < '0' || c > '9') return false;
|
||||
}
|
||||
return true;
|
||||
public static boolean isNumeric(String s) {
|
||||
if (s == null || s.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
if (c < '0' || c > '9') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static short safeParseShort(String s, short def) {
|
||||
try {
|
||||
return Short.parseShort(s);
|
||||
} catch (Exception e) {
|
||||
return def;
|
||||
}
|
||||
public static short safeParseShort(String s, short def) {
|
||||
try {
|
||||
return Short.parseShort(s);
|
||||
} catch (Exception e) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
|
||||
public static int safeParseInt(String s, short def) {
|
||||
try {
|
||||
return Integer.parseInt(s);
|
||||
} catch (Exception e) {
|
||||
return def;
|
||||
}
|
||||
public static int safeParseInt(String s, short def) {
|
||||
try {
|
||||
return Integer.parseInt(s);
|
||||
} catch (Exception e) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
|
||||
public static long safeParseLong(String s, short def) {
|
||||
try {
|
||||
return Long.parseLong(s);
|
||||
} catch (Exception e) {
|
||||
return def;
|
||||
}
|
||||
public static long safeParseLong(String s, short def) {
|
||||
try {
|
||||
return Long.parseLong(s);
|
||||
} catch (Exception e) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,105 +1,120 @@
|
||||
package com.kri.common.web;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public class BusinessException extends RuntimeException {
|
||||
private final HttpStatus status;
|
||||
private final String code;
|
||||
private final Map<String, Object> extras;
|
||||
|
||||
private static String defaultCode(HttpStatus status) { return status.name(); } // 예: NOT_FOUND, CONFLICT …
|
||||
private final HttpStatus status;
|
||||
private final String code;
|
||||
private final Map<String, Object> extras;
|
||||
|
||||
private BusinessException(HttpStatus status, String code, String message,
|
||||
Map<String, Object> extras, Throwable cause) {
|
||||
super(message != null && !message.isBlank() ? message : status.getReasonPhrase(), cause);
|
||||
this.status = status;
|
||||
this.code = (code != null && !code.isBlank()) ? code : defaultCode(status); // 코드가 없으면 상태명으로 대체
|
||||
this.extras = extras == null ? Collections.emptyMap()
|
||||
: Collections.unmodifiableMap(new HashMap<>(extras));
|
||||
}
|
||||
private BusinessException(HttpStatus status, String code, String message,
|
||||
Map<String, Object> extras, Throwable cause) {
|
||||
super(message != null && !message.isBlank() ? message : status.getReasonPhrase(), cause);
|
||||
this.status = status;
|
||||
this.code = (code != null && !code.isBlank()) ? code : defaultCode(status); // 코드가 없으면 상태명으로 대체
|
||||
this.extras = extras == null ? Collections.emptyMap()
|
||||
: Collections.unmodifiableMap(new HashMap<>(extras));
|
||||
}
|
||||
|
||||
public static BusinessException of(HttpStatus status, String code, String message) {
|
||||
return new BusinessException(status, code, message, null, null);
|
||||
}
|
||||
public static BusinessException of(HttpStatus status, String code, String message, Map<String,Object> extras) {
|
||||
return new BusinessException(status, code, message, extras, null);
|
||||
}
|
||||
private static String defaultCode(HttpStatus status) {
|
||||
return status.name();
|
||||
} // 예: NOT_FOUND, CONFLICT …
|
||||
|
||||
// 편의 생성자들
|
||||
// 400 Bad Request
|
||||
public static BusinessException badRequest(String code, String message) {
|
||||
return of(HttpStatus.BAD_REQUEST, code, message);
|
||||
}
|
||||
public static BusinessException of(HttpStatus status, String code, String message) {
|
||||
return new BusinessException(status, code, message, null, null);
|
||||
}
|
||||
|
||||
public static BusinessException badRequest(String message) {
|
||||
return badRequest("BAD_REQUEST", message);
|
||||
}
|
||||
public static BusinessException of(HttpStatus status, String code, String message,
|
||||
Map<String, Object> extras) {
|
||||
return new BusinessException(status, code, message, extras, null);
|
||||
}
|
||||
|
||||
// 401 Unauthorized
|
||||
public static BusinessException unauthorized(String code, String message) {
|
||||
return of(HttpStatus.UNAUTHORIZED, code, message);
|
||||
}
|
||||
// 편의 생성자들
|
||||
// 400 Bad Request
|
||||
public static BusinessException badRequest(String code, String message) {
|
||||
return of(HttpStatus.BAD_REQUEST, code, message);
|
||||
}
|
||||
|
||||
public static BusinessException unauthorized(String message) {
|
||||
return unauthorized("UNAUTHORIZED", message);
|
||||
}
|
||||
public static BusinessException badRequest(String message) {
|
||||
return badRequest("BAD_REQUEST", message);
|
||||
}
|
||||
|
||||
// 403 Forbidden
|
||||
public static BusinessException forbidden(String code, String message) {
|
||||
return of(HttpStatus.FORBIDDEN, code, message);
|
||||
}
|
||||
// 401 Unauthorized
|
||||
public static BusinessException unauthorized(String code, String message) {
|
||||
return of(HttpStatus.UNAUTHORIZED, code, message);
|
||||
}
|
||||
|
||||
public static BusinessException forbidden(String message) {
|
||||
return forbidden("FORBIDDEN", message);
|
||||
}
|
||||
public static BusinessException unauthorized(String message) {
|
||||
return unauthorized("UNAUTHORIZED", message);
|
||||
}
|
||||
|
||||
// 404 Not Found
|
||||
public static BusinessException notFound(String code, String message) {
|
||||
return of(HttpStatus.NOT_FOUND, code, message);
|
||||
}
|
||||
// 403 Forbidden
|
||||
public static BusinessException forbidden(String code, String message) {
|
||||
return of(HttpStatus.FORBIDDEN, code, message);
|
||||
}
|
||||
|
||||
public static BusinessException notFound(String message) {
|
||||
return notFound("NOT_FOUND", message);
|
||||
}
|
||||
public static BusinessException forbidden(String message) {
|
||||
return forbidden("FORBIDDEN", message);
|
||||
}
|
||||
|
||||
// 409 Conflict
|
||||
public static BusinessException conflict(String code, String message) {
|
||||
return of(HttpStatus.CONFLICT, code, message);
|
||||
}
|
||||
// 404 Not Found
|
||||
public static BusinessException notFound(String code, String message) {
|
||||
return of(HttpStatus.NOT_FOUND, code, message);
|
||||
}
|
||||
|
||||
public static BusinessException conflict(String message) {
|
||||
return conflict("CONFLICT", message);
|
||||
}
|
||||
public static BusinessException notFound(String message) {
|
||||
return notFound("NOT_FOUND", message);
|
||||
}
|
||||
|
||||
// 422 Unprocessable Entity (검증 에러 등에 자주 사용)
|
||||
public static BusinessException validationError(String code, String message) {
|
||||
return of(HttpStatus.UNPROCESSABLE_ENTITY, code, message);
|
||||
}
|
||||
// 409 Conflict
|
||||
public static BusinessException conflict(String code, String message) {
|
||||
return of(HttpStatus.CONFLICT, code, message);
|
||||
}
|
||||
|
||||
public static BusinessException validationError(String message) {
|
||||
return validationError("VALIDATION_ERROR", message);
|
||||
}
|
||||
public static BusinessException conflict(String message) {
|
||||
return conflict("CONFLICT", message);
|
||||
}
|
||||
|
||||
// 500 Internal Server Error
|
||||
public static BusinessException internalError(String code, String message) {
|
||||
return of(HttpStatus.INTERNAL_SERVER_ERROR, code, message);
|
||||
}
|
||||
// 422 Unprocessable Entity (검증 에러 등에 자주 사용)
|
||||
public static BusinessException validationError(String code, String message) {
|
||||
return of(HttpStatus.UNPROCESSABLE_ENTITY, code, message);
|
||||
}
|
||||
|
||||
public static BusinessException internalError(String message) {
|
||||
return internalError("INTERNAL_SERVER_ERROR", message);
|
||||
}
|
||||
public static BusinessException validationError(String message) {
|
||||
return validationError("VALIDATION_ERROR", message);
|
||||
}
|
||||
|
||||
public HttpStatus getStatus() { return status; }
|
||||
public String getCode() { return code; }
|
||||
public Map<String, Object> getExtras() { return extras; }
|
||||
// 500 Internal Server Error
|
||||
public static BusinessException internalError(String code, String message) {
|
||||
return of(HttpStatus.INTERNAL_SERVER_ERROR, code, message);
|
||||
}
|
||||
|
||||
/** 편의: 체이닝으로 extras 추가 */
|
||||
public BusinessException with(String key, Object value) {
|
||||
var map = new HashMap<>(this.extras);
|
||||
map.put(key, value);
|
||||
return new BusinessException(this.status, this.code, this.getMessage(), map, this.getCause());
|
||||
}
|
||||
public static BusinessException internalError(String message) {
|
||||
return internalError("INTERNAL_SERVER_ERROR", message);
|
||||
}
|
||||
|
||||
public HttpStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public Map<String, Object> getExtras() {
|
||||
return extras;
|
||||
}
|
||||
|
||||
/**
|
||||
* 편의: 체이닝으로 extras 추가
|
||||
*/
|
||||
public BusinessException with(String key, Object value) {
|
||||
var map = new HashMap<>(this.extras);
|
||||
map.put(key, value);
|
||||
return new BusinessException(this.status, this.code, this.getMessage(), map, this.getCause());
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,23 @@ package com.kri.common.web;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.Ordered;
|
||||
|
||||
@AutoConfiguration
|
||||
@ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true)
|
||||
public class CommonWebAutoConfiguration {
|
||||
@Bean public ErrorAdvice errorAdvice() { return new ErrorAdvice(); }
|
||||
@Bean public FilterRegistrationBean<TraceFilter> traceFilter() {
|
||||
var reg = new FilterRegistrationBean<>(new TraceFilter());
|
||||
reg.setOrder(Ordered.HIGHEST_PRECEDENCE);
|
||||
return reg;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ErrorAdvice errorAdvice() {
|
||||
return new ErrorAdvice();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<TraceFilter> traceFilter() {
|
||||
var reg = new FilterRegistrationBean<>(new TraceFilter());
|
||||
reg.setOrder(Ordered.HIGHEST_PRECEDENCE);
|
||||
return reg;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,11 @@ package com.kri.common.web;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.slf4j.MDC;
|
||||
@@ -11,6 +16,8 @@ import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ProblemDetail;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.ErrorResponseException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
@@ -18,190 +25,201 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class ErrorAdvice {
|
||||
private static final Logger log = LoggerFactory.getLogger(ErrorAdvice.class);
|
||||
|
||||
// 기본값은 모두 false → 외부 응답엔 노출 안 함
|
||||
@Value("${common.error.expose.handler:false}")
|
||||
private boolean exposeHandler;
|
||||
@Value("${common.error.expose.service:false}")
|
||||
private boolean exposeService;
|
||||
private static final Logger log = LoggerFactory.getLogger(ErrorAdvice.class);
|
||||
|
||||
/* ---------- 공통 ProblemDetail 빌더 ---------- */
|
||||
protected ProblemDetail pd(HttpStatus status, String code, String message,
|
||||
HttpServletRequest req, Map<String, Object> extras) {
|
||||
ProblemDetail p = ProblemDetail.forStatusAndDetail(status, message);
|
||||
p.setTitle(status.getReasonPhrase());
|
||||
p.setProperty("code", code);
|
||||
p.setProperty("timestamp", Instant.now().toString());
|
||||
p.setProperty("path", req.getRequestURI());
|
||||
// 기본값은 모두 false → 외부 응답엔 노출 안 함
|
||||
@Value("${common.error.expose.handler:false}")
|
||||
private boolean exposeHandler;
|
||||
@Value("${common.error.expose.service:false}")
|
||||
private boolean exposeService;
|
||||
|
||||
String traceId = MDC.get("traceId");
|
||||
if (traceId != null) p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적
|
||||
private static String resolveSupportedMethods(HttpRequestMethodNotSupportedException e) {
|
||||
Set<HttpMethod> httpMethods = e.getSupportedHttpMethods();
|
||||
if (httpMethods != null && !httpMethods.isEmpty()) {
|
||||
// ✅ 핵심 수정: Enum::name 대신 HttpMethod::name
|
||||
return httpMethods.stream()
|
||||
.map(HttpMethod::name)
|
||||
.collect(Collectors.joining(", "));
|
||||
}
|
||||
String[] methods = e.getSupportedMethods(); // 구버전 호환용
|
||||
if (methods != null && methods.length > 0) {
|
||||
return String.join(", ", methods);
|
||||
}
|
||||
return "N/A";
|
||||
}
|
||||
|
||||
// ↓↓↓ 외부로 숨기고 싶으면 기본 false
|
||||
if (exposeHandler) {
|
||||
String handler = MDC.get("handler"); // Controller#method
|
||||
if (handler != null) p.setProperty("handler", handler);
|
||||
}
|
||||
if (exposeService) {
|
||||
String service = MDC.get("service"); // Service#method (최초 진입)
|
||||
if (service != null) p.setProperty("service", service);
|
||||
}
|
||||
/* ---------- 공통 ProblemDetail 빌더 ---------- */
|
||||
protected ProblemDetail pd(HttpStatus status, String code, String message,
|
||||
HttpServletRequest req, Map<String, Object> extras) {
|
||||
ProblemDetail p = ProblemDetail.forStatusAndDetail(status, message);
|
||||
p.setTitle(status.getReasonPhrase());
|
||||
p.setProperty("code", code);
|
||||
p.setProperty("timestamp", Instant.now().toString());
|
||||
p.setProperty("path", req.getRequestURI());
|
||||
|
||||
if (extras != null) extras.forEach(p::setProperty);
|
||||
return p;
|
||||
String traceId = MDC.get("traceId");
|
||||
if (traceId != null) {
|
||||
p.setProperty("traceId", traceId); // traceId는 외부에 주는 게 일반적
|
||||
}
|
||||
|
||||
/* ---------- Custom Exception ---------- */
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ProblemDetail handleBusiness(BusinessException e, HttpServletRequest req) {
|
||||
logBusiness(e, req); // ← 로그 먼저
|
||||
return pd(
|
||||
e.getStatus(),
|
||||
e.getCode(), // 문자열 코드(없으면 상태명으로 이미 대체됨)
|
||||
e.getMessage(),
|
||||
req,
|
||||
e.getExtras().isEmpty() ? null : e.getExtras()
|
||||
);
|
||||
// ↓↓↓ 외부로 숨기고 싶으면 기본 false
|
||||
if (exposeHandler) {
|
||||
String handler = MDC.get("handler"); // Controller#method
|
||||
if (handler != null) {
|
||||
p.setProperty("handler", handler);
|
||||
}
|
||||
}
|
||||
if (exposeService) {
|
||||
String service = MDC.get("service"); // Service#method (최초 진입)
|
||||
if (service != null) {
|
||||
p.setProperty("service", service);
|
||||
}
|
||||
}
|
||||
|
||||
/* 상황별 로그 레벨/스택트레이스 정책 */
|
||||
private void logBusiness(BusinessException e, HttpServletRequest req) {
|
||||
int sc = e.getStatus().value();
|
||||
String traceId = MDC.get("traceId");
|
||||
String path = req.getRequestURI();
|
||||
String code = e.getCode();
|
||||
var extras = e.getExtras();
|
||||
|
||||
if (sc >= 500) {
|
||||
// 5xx: 운영 이슈 → ERROR + 스택트레이스
|
||||
log.error("BusinessException status={} code={} path={} traceId={} extras={}",
|
||||
sc, code, path, traceId, extras, e);
|
||||
} else if (sc == 409 || sc == 404 || sc == 400 || sc == 403 || sc == 422) {
|
||||
// 사용자/도메인 입력 문제 → WARN, 스택트레이스 제외
|
||||
log.warn("BusinessException status={} code={} path={} traceId={} extras={}",
|
||||
sc, code, path, traceId, extras);
|
||||
} else {
|
||||
// 기타 → WARN 기본
|
||||
log.warn("BusinessException status={} code={} path={} traceId={} extras={}",
|
||||
sc, code, path, traceId, extras);
|
||||
}
|
||||
if (extras != null) {
|
||||
extras.forEach(p::setProperty);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/* ---------- 400: Bean Validation(@Valid) 바디/폼 바인딩 ---------- */
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpServletRequest req) {
|
||||
var fieldErrors = e.getBindingResult().getFieldErrors().stream()
|
||||
.map(fe -> Map.of(
|
||||
"field", fe.getField(),
|
||||
"message", Optional.ofNullable(fe.getDefaultMessage()).orElse("invalid"),
|
||||
"rejectedValue", String.valueOf(fe.getRejectedValue())
|
||||
))
|
||||
.collect(Collectors.toList());
|
||||
return pd(HttpStatus.BAD_REQUEST, "VALIDATION_ERROR", "요청 데이터가 올바르지 않습니다.", req,
|
||||
Map.of("errors", fieldErrors));
|
||||
}
|
||||
/* ---------- Custom Exception ---------- */
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ProblemDetail handleBusiness(BusinessException e, HttpServletRequest req) {
|
||||
logBusiness(e, req); // ← 로그 먼저
|
||||
return pd(
|
||||
e.getStatus(),
|
||||
e.getCode(), // 문자열 코드(없으면 상태명으로 이미 대체됨)
|
||||
e.getMessage(),
|
||||
req,
|
||||
e.getExtras().isEmpty() ? null : e.getExtras()
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- 400: 파라미터/타입 문제 ---------- */
|
||||
@ExceptionHandler({
|
||||
MissingServletRequestParameterException.class,
|
||||
HttpMessageNotReadableException.class
|
||||
})
|
||||
public ProblemDetail handleBadRequest(RuntimeException e, HttpServletRequest req) {
|
||||
String msg = (e instanceof HttpMessageNotReadableException)
|
||||
? "요청 바디를 읽을 수 없습니다(형식 오류/잘못된 JSON)."
|
||||
: e.getMessage();
|
||||
return pd(HttpStatus.BAD_REQUEST, "BAD_REQUEST", msg, req, null);
|
||||
}
|
||||
/* 상황별 로그 레벨/스택트레이스 정책 */
|
||||
private void logBusiness(BusinessException e, HttpServletRequest req) {
|
||||
int sc = e.getStatus().value();
|
||||
String traceId = MDC.get("traceId");
|
||||
String path = req.getRequestURI();
|
||||
String code = e.getCode();
|
||||
var extras = e.getExtras();
|
||||
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e, HttpServletRequest req) {
|
||||
String need = (e.getRequiredType() != null) ? e.getRequiredType().getSimpleName() : "required type";
|
||||
String msg = "파라미터 '" + e.getName() + "' 형식이 올바르지 않습니다. 필요 타입: " + need;
|
||||
return pd(HttpStatus.BAD_REQUEST, "TYPE_MISMATCH", msg, req, null);
|
||||
if (sc >= 500) {
|
||||
// 5xx: 운영 이슈 → ERROR + 스택트레이스
|
||||
log.error("BusinessException status={} code={} path={} traceId={} extras={}",
|
||||
sc, code, path, traceId, extras, e);
|
||||
} else if (sc == 409 || sc == 404 || sc == 400 || sc == 403 || sc == 422) {
|
||||
// 사용자/도메인 입력 문제 → WARN, 스택트레이스 제외
|
||||
log.warn("BusinessException status={} code={} path={} traceId={} extras={}",
|
||||
sc, code, path, traceId, extras);
|
||||
} else {
|
||||
// 기타 → WARN 기본
|
||||
log.warn("BusinessException status={} code={} path={} traceId={} extras={}",
|
||||
sc, code, path, traceId, extras);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 400: 메서드 파라미터(@Validated) 제약 위반 ---------- */
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ProblemDetail handleConstraintViolation(ConstraintViolationException e, HttpServletRequest req) {
|
||||
var errors = e.getConstraintViolations().stream()
|
||||
.map(v -> Map.of("property", v.getPropertyPath().toString(), "message", v.getMessage()))
|
||||
.collect(Collectors.toList());
|
||||
return pd(HttpStatus.BAD_REQUEST, "CONSTRAINT_VIOLATION", "요청 파라미터가 제약을 위반했습니다.", req,
|
||||
Map.of("errors", errors));
|
||||
}
|
||||
/* ---------- 400: Bean Validation(@Valid) 바디/폼 바인딩 ---------- */
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ProblemDetail handleMethodArgumentNotValid(MethodArgumentNotValidException e,
|
||||
HttpServletRequest req) {
|
||||
var fieldErrors = e.getBindingResult().getFieldErrors().stream()
|
||||
.map(fe -> Map.of(
|
||||
"field", fe.getField(),
|
||||
"message", Optional.ofNullable(fe.getDefaultMessage()).orElse("invalid"),
|
||||
"rejectedValue", String.valueOf(fe.getRejectedValue())
|
||||
))
|
||||
.collect(Collectors.toList());
|
||||
return pd(HttpStatus.BAD_REQUEST, "VALIDATION_ERROR", "요청 데이터가 올바르지 않습니다.", req,
|
||||
Map.of("errors", fieldErrors));
|
||||
}
|
||||
|
||||
/* ---------- 404/405/415 등 표준 스프링 예외 ---------- */
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
public ProblemDetail handleNoResourceFound(NoResourceFoundException e, HttpServletRequest req) {
|
||||
return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null);
|
||||
}
|
||||
/* ---------- 400: 파라미터/타입 문제 ---------- */
|
||||
@ExceptionHandler({
|
||||
MissingServletRequestParameterException.class,
|
||||
HttpMessageNotReadableException.class
|
||||
})
|
||||
public ProblemDetail handleBadRequest(RuntimeException e, HttpServletRequest req) {
|
||||
String msg = (e instanceof HttpMessageNotReadableException)
|
||||
? "요청 바디를 읽을 수 없습니다(형식 오류/잘못된 JSON)."
|
||||
: e.getMessage();
|
||||
return pd(HttpStatus.BAD_REQUEST, "BAD_REQUEST", msg, req, null);
|
||||
}
|
||||
|
||||
@ExceptionHandler(NoHandlerFoundException.class)
|
||||
public ProblemDetail handleNotFound(NoHandlerFoundException e, HttpServletRequest req) {
|
||||
return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null);
|
||||
}
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException e,
|
||||
HttpServletRequest req) {
|
||||
String need =
|
||||
(e.getRequiredType() != null) ? e.getRequiredType().getSimpleName() : "required type";
|
||||
String msg = "파라미터 '" + e.getName() + "' 형식이 올바르지 않습니다. 필요 타입: " + need;
|
||||
return pd(HttpStatus.BAD_REQUEST, "TYPE_MISMATCH", msg, req, null);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest req) {
|
||||
String supported = resolveSupportedMethods(e);
|
||||
String msg = "허용되지 않은 HTTP 메서드입니다. 지원: " + supported;
|
||||
// 필요하면 extras로 supported를 내려도 됩니다: Map.of("supported", supported)
|
||||
return pd(HttpStatus.METHOD_NOT_ALLOWED, "METHOD_NOT_ALLOWED", msg, req, null);
|
||||
}
|
||||
/* ---------- 400: 메서드 파라미터(@Validated) 제약 위반 ---------- */
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ProblemDetail handleConstraintViolation(ConstraintViolationException e,
|
||||
HttpServletRequest req) {
|
||||
var errors = e.getConstraintViolations().stream()
|
||||
.map(v -> Map.of("property", v.getPropertyPath().toString(), "message", v.getMessage()))
|
||||
.collect(Collectors.toList());
|
||||
return pd(HttpStatus.BAD_REQUEST, "CONSTRAINT_VIOLATION", "요청 파라미터가 제약을 위반했습니다.", req,
|
||||
Map.of("errors", errors));
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||
public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e, HttpServletRequest req) {
|
||||
String supported = e.getSupportedMediaTypes().stream().map(Object::toString).collect(Collectors.joining(","));
|
||||
String msg = "지원하지 않는 Content-Type입니다. 지원: " + supported;
|
||||
return pd(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", msg, req, null);
|
||||
}
|
||||
/* ---------- 404/405/415 등 표준 스프링 예외 ---------- */
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
public ProblemDetail handleNoResourceFound(NoResourceFoundException e, HttpServletRequest req) {
|
||||
return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null);
|
||||
}
|
||||
|
||||
/* ---------- 4xx/5xx를 명시하는 스프링 예외 ---------- */
|
||||
@ExceptionHandler({ ResponseStatusException.class, ErrorResponseException.class })
|
||||
public ProblemDetail handleResponseStatus(Exception e, HttpServletRequest req) {
|
||||
HttpStatus status;
|
||||
String reason;
|
||||
if (e instanceof ResponseStatusException rse) {
|
||||
status = HttpStatus.valueOf(rse.getStatusCode().value());
|
||||
reason = Optional.ofNullable(rse.getReason()).orElse(status.getReasonPhrase());
|
||||
} else { // ErrorResponseException (Spring 6+)
|
||||
var ere = (ErrorResponseException) e;
|
||||
status = HttpStatus.valueOf(ere.getStatusCode().value());
|
||||
reason = Optional.ofNullable(ere.getBody()).map(ProblemDetail::getDetail).orElse(status.getReasonPhrase());
|
||||
}
|
||||
return pd(status, "ERROR", reason, req, null);
|
||||
}
|
||||
@ExceptionHandler(NoHandlerFoundException.class)
|
||||
public ProblemDetail handleNotFound(NoHandlerFoundException e, HttpServletRequest req) {
|
||||
return pd(HttpStatus.NOT_FOUND, "NOT_FOUND", "요청한 리소스를 찾을 수 없습니다.", req, null);
|
||||
}
|
||||
|
||||
/* ---------- 마지막: 예상 못한 예외는 500 ---------- */
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ProblemDetail handleAny(Exception e, HttpServletRequest req) {
|
||||
log.error("Unhandled exception path={} traceId={}", req.getRequestURI(), MDC.get("traceId"), e);
|
||||
return pd(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "서버 내부 오류가 발생했습니다.", req, null);
|
||||
}
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
public ProblemDetail handleMethodNotSupported(HttpRequestMethodNotSupportedException e,
|
||||
HttpServletRequest req) {
|
||||
String supported = resolveSupportedMethods(e);
|
||||
String msg = "허용되지 않은 HTTP 메서드입니다. 지원: " + supported;
|
||||
// 필요하면 extras로 supported를 내려도 됩니다: Map.of("supported", supported)
|
||||
return pd(HttpStatus.METHOD_NOT_ALLOWED, "METHOD_NOT_ALLOWED", msg, req, null);
|
||||
}
|
||||
|
||||
private static String resolveSupportedMethods(HttpRequestMethodNotSupportedException e) {
|
||||
Set<HttpMethod> httpMethods = e.getSupportedHttpMethods();
|
||||
if (httpMethods != null && !httpMethods.isEmpty()) {
|
||||
// ✅ 핵심 수정: Enum::name 대신 HttpMethod::name
|
||||
return httpMethods.stream()
|
||||
.map(HttpMethod::name)
|
||||
.collect(Collectors.joining(", "));
|
||||
}
|
||||
String[] methods = e.getSupportedMethods(); // 구버전 호환용
|
||||
if (methods != null && methods.length > 0) {
|
||||
return String.join(", ", methods);
|
||||
}
|
||||
return "N/A";
|
||||
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||
public ProblemDetail handleMediaType(HttpMediaTypeNotSupportedException e,
|
||||
HttpServletRequest req) {
|
||||
String supported = e.getSupportedMediaTypes().stream().map(Object::toString)
|
||||
.collect(Collectors.joining(","));
|
||||
String msg = "지원하지 않는 Content-Type입니다. 지원: " + supported;
|
||||
return pd(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE", msg, req, null);
|
||||
}
|
||||
|
||||
/* ---------- 4xx/5xx를 명시하는 스프링 예외 ---------- */
|
||||
@ExceptionHandler({ResponseStatusException.class, ErrorResponseException.class})
|
||||
public ProblemDetail handleResponseStatus(Exception e, HttpServletRequest req) {
|
||||
HttpStatus status;
|
||||
String reason;
|
||||
if (e instanceof ResponseStatusException rse) {
|
||||
status = HttpStatus.valueOf(rse.getStatusCode().value());
|
||||
reason = Optional.ofNullable(rse.getReason()).orElse(status.getReasonPhrase());
|
||||
} else { // ErrorResponseException (Spring 6+)
|
||||
var ere = (ErrorResponseException) e;
|
||||
status = HttpStatus.valueOf(ere.getStatusCode().value());
|
||||
reason = Optional.ofNullable(ere.getBody()).map(ProblemDetail::getDetail)
|
||||
.orElse(status.getReasonPhrase());
|
||||
}
|
||||
return pd(status, "ERROR", reason, req, null);
|
||||
}
|
||||
|
||||
/* ---------- 마지막: 예상 못한 예외는 500 ---------- */
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ProblemDetail handleAny(Exception e, HttpServletRequest req) {
|
||||
log.error("Unhandled exception path={} traceId={}", req.getRequestURI(), MDC.get("traceId"), e);
|
||||
return pd(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "서버 내부 오류가 발생했습니다.", req, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +1,39 @@
|
||||
package com.kri.common.web;
|
||||
|
||||
import jakarta.servlet.http.*;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.config.annotation.*;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
public class MdcHandlerConfig {
|
||||
@Bean
|
||||
public WebMvcConfigurer mdcWebMvcConfigurer() {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() {
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
|
||||
if (handler instanceof HandlerMethod hm) {
|
||||
String ctrl = hm.getBeanType().getSimpleName(); // ex) ContactController
|
||||
String method = hm.getMethod().getName(); // ex) create
|
||||
MDC.put("handler", ctrl + "#" + method); // ex) ContactController#create
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) {
|
||||
MDC.remove("handler");
|
||||
}
|
||||
});
|
||||
|
||||
@Bean
|
||||
public WebMvcConfigurer mdcWebMvcConfigurer() {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(new org.springframework.web.servlet.HandlerInterceptor() {
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
|
||||
Object handler) {
|
||||
if (handler instanceof HandlerMethod hm) {
|
||||
String ctrl = hm.getBeanType().getSimpleName(); // ex) ContactController
|
||||
String method = hm.getMethod().getName(); // ex) create
|
||||
MDC.put("handler", ctrl + "#" + method); // ex) ContactController#create
|
||||
}
|
||||
};
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest req, HttpServletResponse res,
|
||||
Object handler, Exception ex) {
|
||||
MDC.remove("handler");
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
package com.kri.common.web;
|
||||
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.*;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
public class ServiceMdcAspect {
|
||||
@Around("within(@org.springframework.stereotype.Service *)")
|
||||
public Object aroundService(ProceedingJoinPoint pjp) throws Throwable {
|
||||
boolean first = (MDC.get("service") == null);
|
||||
if (first) {
|
||||
String cls = pjp.getSignature().getDeclaringType().getSimpleName(); // ex) ExportService
|
||||
String mtd = pjp.getSignature().getName(); // ex) enqueue
|
||||
MDC.put("service", cls + "#" + mtd); // ex) ExportService#enqueue
|
||||
}
|
||||
try {
|
||||
return pjp.proceed();
|
||||
} finally {
|
||||
if (first) MDC.remove("service");
|
||||
}
|
||||
|
||||
@Around("within(@org.springframework.stereotype.Service *)")
|
||||
public Object aroundService(ProceedingJoinPoint pjp) throws Throwable {
|
||||
boolean first = (MDC.get("service") == null);
|
||||
if (first) {
|
||||
String cls = pjp.getSignature().getDeclaringType().getSimpleName(); // ex) ExportService
|
||||
String mtd = pjp.getSignature().getName(); // ex) enqueue
|
||||
MDC.put("service",
|
||||
cls + "#" + mtd); // ex) ExportService#enqueue
|
||||
}
|
||||
try {
|
||||
return pjp.proceed();
|
||||
} finally {
|
||||
if (first) {
|
||||
MDC.remove("service");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,35 @@
|
||||
package com.kri.common.web;
|
||||
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.Filter;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.ServletRequest;
|
||||
import jakarta.servlet.ServletResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
public class TraceFilter implements Filter {
|
||||
private static final String REQ_HEADER = "X-Request-Id";
|
||||
private static final String MDC_KEY = "traceId";
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
var httpReq = (HttpServletRequest) req;
|
||||
var httpRes = (HttpServletResponse) res;
|
||||
private static final String REQ_HEADER = "X-Request-Id";
|
||||
private static final String MDC_KEY = "traceId";
|
||||
|
||||
String id = httpReq.getHeader(REQ_HEADER);
|
||||
if (id == null || id.isBlank()) id = UUID.randomUUID().toString();
|
||||
@Override
|
||||
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
var httpReq = (HttpServletRequest) req;
|
||||
var httpRes = (HttpServletResponse) res;
|
||||
|
||||
try (MDC.MDCCloseable ignored = MDC.putCloseable(MDC_KEY, id)) {
|
||||
httpRes.setHeader(REQ_HEADER, id); // 응답에도 echo
|
||||
chain.doFilter(req, res);
|
||||
}
|
||||
String id = httpReq.getHeader(REQ_HEADER);
|
||||
if (id == null || id.isBlank()) {
|
||||
id = UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
try (MDC.MDCCloseable ignored = MDC.putCloseable(MDC_KEY, id)) {
|
||||
httpRes.setHeader(REQ_HEADER, id); // 응답에도 echo
|
||||
chain.doFilter(req, res);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,33 +4,36 @@ import com.kri.common.enums.CodeEnum;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.core.convert.converter.ConverterFactory;
|
||||
|
||||
public class CodeEnumConverter implements ConverterFactory<String, CodeEnum> {
|
||||
public class CodeEnumConverter implements ConverterFactory<String, CodeEnum> {
|
||||
|
||||
@Override
|
||||
public <T extends CodeEnum> Converter<String, T> getConverter(Class<T> targetType) {
|
||||
return source -> convert(source, targetType);
|
||||
@Override
|
||||
public <T extends CodeEnum> Converter<String, T> getConverter(Class<T> targetType) {
|
||||
return source -> convert(source, targetType);
|
||||
}
|
||||
|
||||
private <T extends CodeEnum> T convert(String source, Class<T> targetType) {
|
||||
if (source == null || source.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
private <T extends CodeEnum> T convert(String source, Class<T> targetType) {
|
||||
if (source == null || source.isBlank()) return null;
|
||||
|
||||
// 1) enum name으로 먼저 시도 (EMAIL, SMS 등)
|
||||
if (targetType.isEnum()) {
|
||||
for (T e : targetType.getEnumConstants()) {
|
||||
if (((Enum<?>) e).name().equalsIgnoreCase(source)) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
// 1) enum name으로 먼저 시도 (EMAIL, SMS 등)
|
||||
if (targetType.isEnum()) {
|
||||
for (T e : targetType.getEnumConstants()) {
|
||||
if (((Enum<?>) e).name().equalsIgnoreCase(source)) {
|
||||
return e;
|
||||
}
|
||||
|
||||
// 2) code로 시도 ("11" 등)
|
||||
for (T e : targetType.getEnumConstants()) {
|
||||
Object code = e.getCode();
|
||||
if (code != null && source.equals(String.valueOf(code))) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Unknown enum value: " + source + " for " + targetType.getName());
|
||||
}
|
||||
}
|
||||
|
||||
// 2) code로 시도 ("11" 등)
|
||||
for (T e : targetType.getEnumConstants()) {
|
||||
Object code = e.getCode();
|
||||
if (code != null && source.equals(String.valueOf(code))) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException(
|
||||
"Unknown enum value: " + source + " for " + targetType.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,19 +8,19 @@ import org.springframework.web.servlet.HandlerInterceptor;
|
||||
@RequiredArgsConstructor
|
||||
public class IpAccessControlInterceptor implements HandlerInterceptor {
|
||||
|
||||
private final IpAccessControlService ipAccessControlService;
|
||||
private final IpAccessControlService ipAccessControlService;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
Object handler) throws Exception {
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
Object handler) throws Exception {
|
||||
|
||||
String clientIpAddress = IpUtil.getClientIp(request);
|
||||
if (!ipAccessControlService.isAccessible(clientIpAddress)) {
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
String clientIpAddress = IpUtil.getClientIp(request);
|
||||
if (!ipAccessControlService.isAccessible(clientIpAddress)) {
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,19 @@
|
||||
package com.kri.common.webmvc;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.web.util.matcher.IpAddressMatcher;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class IpAccessControlService {
|
||||
|
||||
private final KriIpAccessProperties properties;
|
||||
private final KriIpAccessProperties properties;
|
||||
|
||||
public boolean isAccessible(String ipAddress) {
|
||||
List<String> cidrs = properties.getEffectiveCidrs();
|
||||
public boolean isAccessible(String ipAddress) {
|
||||
List<String> cidrs = properties.getEffectiveCidrs();
|
||||
|
||||
return cidrs.stream()
|
||||
.map(IpAddressMatcher::new)
|
||||
.anyMatch(matcher -> matcher.matches(ipAddress));
|
||||
}
|
||||
return cidrs.stream()
|
||||
.map(IpAddressMatcher::new)
|
||||
.anyMatch(matcher -> matcher.matches(ipAddress));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,24 +4,24 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
public final class IpUtil {
|
||||
|
||||
private IpUtil() {
|
||||
private IpUtil() {
|
||||
}
|
||||
|
||||
public static String getClientIp(HttpServletRequest request) {
|
||||
// 1. Proxy 환경 고려: X-Forwarded-For 헤더 우선
|
||||
String xff = request.getHeader("X-Forwarded-For");
|
||||
if (xff != null && !xff.isBlank()) {
|
||||
// X-Forwarded-For: client, proxy1, proxy2 ...
|
||||
return xff.split(",")[0].trim();
|
||||
}
|
||||
|
||||
public static String getClientIp(HttpServletRequest request) {
|
||||
// 1. Proxy 환경 고려: X-Forwarded-For 헤더 우선
|
||||
String xff = request.getHeader("X-Forwarded-For");
|
||||
if (xff != null && !xff.isBlank()) {
|
||||
// X-Forwarded-For: client, proxy1, proxy2 ...
|
||||
return xff.split(",")[0].trim();
|
||||
}
|
||||
|
||||
// 2. 그 다음 X-Real-IP
|
||||
String realIp = request.getHeader("X-Real-IP");
|
||||
if (realIp != null && !realIp.isBlank()) {
|
||||
return realIp;
|
||||
}
|
||||
|
||||
// 3. 최후 fallback
|
||||
return request.getRemoteAddr();
|
||||
// 2. 그 다음 X-Real-IP
|
||||
String realIp = request.getHeader("X-Real-IP");
|
||||
if (realIp != null && !realIp.isBlank()) {
|
||||
return realIp;
|
||||
}
|
||||
|
||||
// 3. 최후 fallback
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,44 +1,41 @@
|
||||
package com.kri.common.webmvc;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "kri.webmvc.ip")
|
||||
public class KriIpAccessProperties {
|
||||
|
||||
/**
|
||||
* 공통에서 고정으로 들고 갈 기본 CIDR 들
|
||||
* → setter 없음 (외부에서 못 바꿈)
|
||||
*/
|
||||
private final List<String> defaultCidrs = List.of(
|
||||
"127.0.0.1/32", // 로컬 IPv4
|
||||
"::1/128", // 로컬 IPv6
|
||||
"10.10.13.0/24", //석오 내부망
|
||||
"211.254.145.128/25" //석오 내부망 외부 IP
|
||||
);
|
||||
/**
|
||||
* 공통에서 고정으로 들고 갈 기본 CIDR 들 → setter 없음 (외부에서 못 바꿈)
|
||||
*/
|
||||
private final List<String> defaultCidrs = List.of(
|
||||
"127.0.0.1/32", // 로컬 IPv4
|
||||
"::1/128", // 로컬 IPv6
|
||||
"10.10.13.0/24", //석오 내부망
|
||||
"211.254.145.128/25" //석오 내부망 외부 IP
|
||||
);
|
||||
|
||||
/**
|
||||
* 서비스에서 추가로 넣고 싶은 CIDR 목록
|
||||
* application.yml / properties 로 바인딩되는 리스트
|
||||
*
|
||||
* 예) kri.webmvc.ip.additional-cidrs[0]=10.10.0.0/16
|
||||
*/
|
||||
private List<String> additionalCidrs = new ArrayList<>();
|
||||
/**
|
||||
* 서비스에서 추가로 넣고 싶은 CIDR 목록 application.yml / properties 로 바인딩되는 리스트
|
||||
* <p>
|
||||
* 예) kri.webmvc.ip.additional-cidrs[0]=10.10.0.0/16
|
||||
*/
|
||||
private List<String> additionalCidrs = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* 기본 + 추가를 합친 최종 목록
|
||||
*/
|
||||
public List<String> getEffectiveCidrs() {
|
||||
return Stream.concat(defaultCidrs.stream(), additionalCidrs.stream())
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
/**
|
||||
* 기본 + 추가를 합친 최종 목록
|
||||
*/
|
||||
public List<String> getEffectiveCidrs() {
|
||||
return Stream.concat(defaultCidrs.stream(), additionalCidrs.stream())
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@@ -19,70 +19,70 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
@RequiredArgsConstructor
|
||||
public class KriWebMvcAutoConfiguration {
|
||||
|
||||
private final KriIpAccessProperties ipProps; // 생성자 주입 (RequiredArgsConstructor)
|
||||
private final KriIpAccessProperties ipProps; // 생성자 주입 (RequiredArgsConstructor)
|
||||
// 선택 주입: 있으면 쓰고, 없으면 안 씀
|
||||
private final ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider;
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public IpAccessControlService ipAccessControlService(KriIpAccessProperties ipProps) {
|
||||
return new IpAccessControlService(ipProps);
|
||||
}
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public IpAccessControlService ipAccessControlService(KriIpAccessProperties ipProps) {
|
||||
return new IpAccessControlService(ipProps);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public IpAccessControlInterceptor ipAccessControlInterceptor(IpAccessControlService service) {
|
||||
return new IpAccessControlInterceptor(service);
|
||||
}
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public IpAccessControlInterceptor ipAccessControlInterceptor(IpAccessControlService service) {
|
||||
return new IpAccessControlInterceptor(service);
|
||||
}
|
||||
|
||||
// 선택 주입: 있으면 쓰고, 없으면 안 씀
|
||||
private final ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider;
|
||||
@Bean
|
||||
@ConditionalOnBean(JwtService.class)// JwtService 있을 때만 동작
|
||||
@ConditionalOnMissingBean
|
||||
public RequestUserContextArgumentResolver requestUserContextArgumentResolver(
|
||||
JwtService jwtService
|
||||
) {
|
||||
return new RequestUserContextArgumentResolver(jwtService);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(JwtService.class)// JwtService 있을 때만 동작
|
||||
@ConditionalOnMissingBean
|
||||
public RequestUserContextArgumentResolver requestUserContextArgumentResolver(
|
||||
JwtService jwtService
|
||||
) {
|
||||
return new RequestUserContextArgumentResolver(jwtService);
|
||||
}
|
||||
/**
|
||||
* 실제로 WebMvc 설정을 하는 WebMvcConfigurer Bean
|
||||
*/
|
||||
@Bean
|
||||
public WebMvcConfigurer kriCommonWebMvcConfigurer(
|
||||
KriIpAccessProperties properties,
|
||||
ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider,
|
||||
ObjectProvider<RequestUserContextArgumentResolver> requestUserContextArgumentResolverProvider
|
||||
) {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
// 기본 CORS – 필요하면 나중에 조정
|
||||
registry.addMapping("/**")
|
||||
.allowedOriginPatterns("*")
|
||||
.allowedMethods("*")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 실제로 WebMvc 설정을 하는 WebMvcConfigurer Bean
|
||||
*/
|
||||
@Bean
|
||||
public WebMvcConfigurer kriCommonWebMvcConfigurer(
|
||||
KriIpAccessProperties properties,
|
||||
ObjectProvider<IpAccessControlInterceptor> ipAccessControlInterceptorProvider,
|
||||
ObjectProvider<RequestUserContextArgumentResolver> requestUserContextArgumentResolverProvider
|
||||
) {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
// 기본 CORS – 필요하면 나중에 조정
|
||||
registry.addMapping("/**")
|
||||
.allowedOriginPatterns("*")
|
||||
.allowedMethods("*")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
ipAccessControlInterceptorProvider.ifAvailable(interceptor ->
|
||||
registry.addInterceptor(interceptor)
|
||||
.order(1)
|
||||
.addPathPatterns("/swagger-ui/**", "/v3/api-docs/**")
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
ipAccessControlInterceptorProvider.ifAvailable(interceptor ->
|
||||
registry.addInterceptor(interceptor)
|
||||
.order(1)
|
||||
.addPathPatterns("/swagger-ui/**", "/v3/api-docs/**")
|
||||
);
|
||||
}
|
||||
@Override
|
||||
public void addArgumentResolvers(
|
||||
java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver> resolvers) {
|
||||
requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addArgumentResolvers(java.util.List<org.springframework.web.method.support.HandlerMethodArgumentResolver> resolvers) {
|
||||
requestUserContextArgumentResolverProvider.ifAvailable(resolvers::add);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addFormatters(org.springframework.format.FormatterRegistry registry) {
|
||||
registry.addConverterFactory(new com.kri.common.webmvc.CodeEnumConverter());
|
||||
}
|
||||
};
|
||||
}
|
||||
@Override
|
||||
public void addFormatters(org.springframework.format.FormatterRegistry registry) {
|
||||
registry.addConverterFactory(new com.kri.common.webmvc.CodeEnumConverter());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -7,15 +7,15 @@ import lombok.Value;
|
||||
@Builder
|
||||
public class RequestUserContext {
|
||||
|
||||
String userId;
|
||||
String userCmpn;
|
||||
String userTeam;
|
||||
String userName;
|
||||
Integer userRole;
|
||||
String userId;
|
||||
String userCmpn;
|
||||
String userTeam;
|
||||
String userName;
|
||||
Integer userRole;
|
||||
|
||||
String clientIp; // IpUtil 에서 가져온 값
|
||||
String clientIp; // IpUtil 에서 가져온 값
|
||||
|
||||
public boolean isAuthenticated() {
|
||||
return userId != null;
|
||||
}
|
||||
public boolean isAuthenticated() {
|
||||
return userId != null;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.kri.common.webmvc;
|
||||
|
||||
import com.kri.common.auth.jwt.JwtService;
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import com.kri.common.auth.jwt.JwtService;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -17,60 +17,60 @@ import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
@RequiredArgsConstructor
|
||||
public class RequestUserContextArgumentResolver implements HandlerMethodArgumentResolver {
|
||||
|
||||
private final JwtService jwtService;
|
||||
private final JwtService jwtService;
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(MethodParameter parameter) {
|
||||
return RequestUserContext.class.isAssignableFrom(parameter.getParameterType());
|
||||
@Override
|
||||
public boolean supportsParameter(MethodParameter parameter) {
|
||||
return RequestUserContext.class.isAssignableFrom(parameter.getParameterType());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolveArgument(
|
||||
MethodParameter parameter,
|
||||
@Nullable ModelAndViewContainer mavContainer,
|
||||
NativeWebRequest webRequest,
|
||||
@Nullable WebDataBinderFactory binderFactory
|
||||
) {
|
||||
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
|
||||
|
||||
String clientIp = request != null ? IpUtil.getClientIp(request) : null;
|
||||
|
||||
JwtUserClaimsDto claims = null;
|
||||
|
||||
// 1) SecurityContext 에 이미 JwtUserClaimsDto 가 principal 로 들어있는 경우
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (auth != null && auth.getPrincipal() instanceof JwtUserClaimsDto jwtDto) {
|
||||
claims = jwtDto;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolveArgument(
|
||||
MethodParameter parameter,
|
||||
@Nullable ModelAndViewContainer mavContainer,
|
||||
NativeWebRequest webRequest,
|
||||
@Nullable WebDataBinderFactory binderFactory
|
||||
) {
|
||||
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
|
||||
|
||||
String clientIp = request != null ? IpUtil.getClientIp(request) : null;
|
||||
|
||||
JwtUserClaimsDto claims = null;
|
||||
|
||||
// 1) SecurityContext 에 이미 JwtUserClaimsDto 가 principal 로 들어있는 경우
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (auth != null && auth.getPrincipal() instanceof JwtUserClaimsDto jwtDto) {
|
||||
claims = jwtDto;
|
||||
// 2) 현재 공통 JwtService 는 principal 을 userId(String) 로 쓰고 있으니까,
|
||||
// 필요하면 Authorization 헤더에서 직접 토큰 파싱
|
||||
if (claims == null && request != null) {
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
try {
|
||||
claims = jwtService.toUserClaimsDto(token);
|
||||
} catch (JwtException ex) {
|
||||
// 토큰 이상하면 그냥 anonymous 로 둠
|
||||
}
|
||||
|
||||
// 2) 현재 공통 JwtService 는 principal 을 userId(String) 로 쓰고 있으니까,
|
||||
// 필요하면 Authorization 헤더에서 직접 토큰 파싱
|
||||
if (claims == null && request != null) {
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
try {
|
||||
claims = jwtService.toUserClaimsDto(token);
|
||||
} catch (JwtException ex) {
|
||||
// 토큰 이상하면 그냥 anonymous 로 둠
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (claims == null) {
|
||||
// 비인증 상태: IP만 채운 빈 컨텍스트
|
||||
return RequestUserContext.builder()
|
||||
.clientIp(clientIp)
|
||||
.build();
|
||||
}
|
||||
|
||||
return RequestUserContext.builder()
|
||||
.userId(claims.getUserId())
|
||||
.userCmpn(claims.getUserCmpn())
|
||||
.userTeam(claims.getUserTeam())
|
||||
.userName(claims.getUserName())
|
||||
.userRole(claims.getUserRole())
|
||||
.clientIp(clientIp)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
if (claims == null) {
|
||||
// 비인증 상태: IP만 채운 빈 컨텍스트
|
||||
return RequestUserContext.builder()
|
||||
.clientIp(clientIp)
|
||||
.build();
|
||||
}
|
||||
|
||||
return RequestUserContext.builder()
|
||||
.userId(claims.getUserId())
|
||||
.userCmpn(claims.getUserCmpn())
|
||||
.userTeam(claims.getUserTeam())
|
||||
.userName(claims.getUserName())
|
||||
.userRole(claims.getUserRole())
|
||||
.clientIp(clientIp)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,13 +8,14 @@ import lombok.Setter;
|
||||
@Setter
|
||||
@Schema(description = "페이지 검색 조건")
|
||||
public class PageRequestDto {
|
||||
@Schema(description = "페이지 번호")
|
||||
private int pageIndex = 0; // 0-base
|
||||
@Schema(description = "페이지 크기")
|
||||
private int pageSize = 10;
|
||||
|
||||
@Schema(description = "정렬 기준")
|
||||
private String sortBy = "prjctIdx"; // 가변
|
||||
@Schema(description = "오름차순/내림차순")
|
||||
private String sortDir = "desc"; // asc/desc
|
||||
@Schema(description = "페이지 번호")
|
||||
private int pageIndex = 0; // 0-base
|
||||
@Schema(description = "페이지 크기")
|
||||
private int pageSize = 10;
|
||||
|
||||
@Schema(description = "정렬 기준")
|
||||
private String sortBy = "prjctIdx"; // 가변
|
||||
@Schema(description = "오름차순/내림차순")
|
||||
private String sortDir = "desc"; // asc/desc
|
||||
}
|
||||
@@ -1,35 +1,35 @@
|
||||
package com.kri.common.webmvc.page;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Builder
|
||||
public class PageResponseDto <T> {
|
||||
private List<T> content;
|
||||
private long totalElements;
|
||||
private int totalPages;
|
||||
private int pageIndex;
|
||||
private int pageSize;
|
||||
private int numberOfElements;
|
||||
private boolean first;
|
||||
private boolean last;
|
||||
private boolean empty;
|
||||
public class PageResponseDto<T> {
|
||||
|
||||
public static <T> PageResponseDto<T> from(Page<T> page) {
|
||||
return PageResponseDto.<T>builder()
|
||||
.content(page.getContent())
|
||||
.totalElements(page.getTotalElements())
|
||||
.totalPages(page.getTotalPages())
|
||||
.pageIndex(page.getNumber()) // ✅ 현재 페이지 index(0-base)
|
||||
.pageSize(page.getSize())
|
||||
.numberOfElements(page.getNumberOfElements())
|
||||
.first(page.isFirst())
|
||||
.last(page.isLast())
|
||||
.empty(page.isEmpty())
|
||||
.build();
|
||||
}
|
||||
private List<T> content;
|
||||
private long totalElements;
|
||||
private int totalPages;
|
||||
private int pageIndex;
|
||||
private int pageSize;
|
||||
private int numberOfElements;
|
||||
private boolean first;
|
||||
private boolean last;
|
||||
private boolean empty;
|
||||
|
||||
public static <T> PageResponseDto<T> from(Page<T> page) {
|
||||
return PageResponseDto.<T>builder()
|
||||
.content(page.getContent())
|
||||
.totalElements(page.getTotalElements())
|
||||
.totalPages(page.getTotalPages())
|
||||
.pageIndex(page.getNumber()) // ✅ 현재 페이지 index(0-base)
|
||||
.pageSize(page.getSize())
|
||||
.numberOfElements(page.getNumberOfElements())
|
||||
.first(page.isFirst())
|
||||
.last(page.isLast())
|
||||
.empty(page.isEmpty())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,67 +1,77 @@
|
||||
package com.kri.common.webmvc.page;
|
||||
|
||||
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public final class Pageables {
|
||||
private Pageables() {}
|
||||
|
||||
public static Pageable of(PageRequestDto req, Class<?> sortType) {
|
||||
int page = Math.max(req.getPageIndex(), 0);
|
||||
int size = Math.max(req.getPageSize(), 1);
|
||||
private Pageables() {
|
||||
}
|
||||
|
||||
Sort sort = buildSort(req, sortType);
|
||||
return (sort == null) ? PageRequest.of(page, size) : PageRequest.of(page, size, sort);
|
||||
public static Pageable of(PageRequestDto req, Class<?> sortType) {
|
||||
int page = Math.max(req.getPageIndex(), 0);
|
||||
int size = Math.max(req.getPageSize(), 1);
|
||||
|
||||
Sort sort = buildSort(req, sortType);
|
||||
return (sort == null) ? PageRequest.of(page, size) : PageRequest.of(page, size, sort);
|
||||
}
|
||||
|
||||
private static Sort buildSort(PageRequestDto req, Class<?> sortType) {
|
||||
String sortBy = req.getSortBy();
|
||||
if (sortBy == null || sortBy.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Sort buildSort(PageRequestDto req, Class<?> sortType) {
|
||||
String sortBy = req.getSortBy();
|
||||
if (sortBy == null || sortBy.isBlank()) return null;
|
||||
Sort.Direction dir = "asc".equalsIgnoreCase(req.getSortDir())
|
||||
? Sort.Direction.ASC
|
||||
: Sort.Direction.DESC;
|
||||
|
||||
Sort.Direction dir = "asc".equalsIgnoreCase(req.getSortDir())
|
||||
? Sort.Direction.ASC
|
||||
: Sort.Direction.DESC;
|
||||
Set<String> allowed = allowedProperties(sortType);
|
||||
|
||||
Set<String> allowed = allowedProperties(sortType);
|
||||
List<String> props = Arrays.stream(sortBy.split(","))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isBlank())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<String> props = Arrays.stream(sortBy.split(","))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isBlank())
|
||||
.collect(Collectors.toList());
|
||||
// 허용되지 않은 필드가 섞이면 예외(또는 무시 정책으로 바꿔도 됨)
|
||||
List<String> invalid = props.stream()
|
||||
.filter(p -> !allowed.contains(p))
|
||||
.toList();
|
||||
|
||||
// 허용되지 않은 필드가 섞이면 예외(또는 무시 정책으로 바꿔도 됨)
|
||||
List<String> invalid = props.stream()
|
||||
.filter(p -> !allowed.contains(p))
|
||||
.toList();
|
||||
if (!invalid.isEmpty()) {
|
||||
throw new IllegalArgumentException("Invalid sortBy: " + invalid + ", allowed=" + allowed);
|
||||
}
|
||||
|
||||
if (!invalid.isEmpty()) {
|
||||
throw new IllegalArgumentException("Invalid sortBy: " + invalid + ", allowed=" + allowed);
|
||||
return Sort.by(dir, props.toArray(String[]::new));
|
||||
}
|
||||
|
||||
private static Set<String> allowedProperties(Class<?> sortType) {
|
||||
try {
|
||||
// getter 기반 프로퍼티 추출 (필드보다 JPA/롬복 환경에서 안정적)
|
||||
PropertyDescriptor[] pds = Introspector.getBeanInfo(sortType).getPropertyDescriptors();
|
||||
Set<String> props = new HashSet<>();
|
||||
for (PropertyDescriptor pd : pds) {
|
||||
String name = pd.getName();
|
||||
if ("class".equals(name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return Sort.by(dir, props.toArray(String[]::new));
|
||||
}
|
||||
|
||||
private static Set<String> allowedProperties(Class<?> sortType) {
|
||||
try {
|
||||
// getter 기반 프로퍼티 추출 (필드보다 JPA/롬복 환경에서 안정적)
|
||||
PropertyDescriptor[] pds = Introspector.getBeanInfo(sortType).getPropertyDescriptors();
|
||||
Set<String> props = new HashSet<>();
|
||||
for (PropertyDescriptor pd : pds) {
|
||||
String name = pd.getName();
|
||||
if ("class".equals(name)) continue;
|
||||
if (pd.getReadMethod() == null) continue;
|
||||
props.add(name);
|
||||
}
|
||||
return props;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to introspect sortType=" + sortType.getName(), e);
|
||||
if (pd.getReadMethod() == null) {
|
||||
continue;
|
||||
}
|
||||
props.add(name);
|
||||
}
|
||||
return props;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to introspect sortType=" + sortType.getName(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user