20260716173254
This commit is contained in:
1 parent
704dda07b5
commit
5cd4e1e1d2
46 files changed
+3569
-528
No files matched your search
@@ -0,0 +1,15 @@
|
||||
package cn.g3soft.fmsapi;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan
|
||||
public class FmsApiApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(FmsApiApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.g3soft.fmsapi.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@ConfigurationProperties(prefix = "fms.auth")
|
||||
public class AuthProperties {
|
||||
|
||||
private String jwtSecret;
|
||||
private Duration jwtExpiration = Duration.ofHours(24);
|
||||
|
||||
public String getJwtSecret() {
|
||||
return jwtSecret;
|
||||
}
|
||||
|
||||
public void setJwtSecret(String jwtSecret) {
|
||||
this.jwtSecret = jwtSecret;
|
||||
}
|
||||
|
||||
public Duration getJwtExpiration() {
|
||||
return jwtExpiration;
|
||||
}
|
||||
|
||||
public void setJwtExpiration(Duration jwtExpiration) {
|
||||
this.jwtExpiration = jwtExpiration;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package cn.g3soft.fmsapi.config;
|
||||
|
||||
import cn.g3soft.fmsapi.database.OrgContext;
|
||||
import cn.g3soft.fmsapi.utils.ApiResponse;
|
||||
import cn.g3soft.fmsapi.utils.JwtUtils;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import jakarta.annotation.Resource;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class JwtAuthFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final String BEARER_PREFIX = "Bearer ";
|
||||
private static final String LOGIN_PATH = "/auth/login";
|
||||
|
||||
@Resource
|
||||
private JwtUtils jwtUtils;
|
||||
|
||||
@Resource
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
return "OPTIONS".equalsIgnoreCase(request.getMethod())
|
||||
|| LOGIN_PATH.equals(request.getServletPath());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
String orgId;
|
||||
try {
|
||||
String token = getToken(request);
|
||||
orgId = jwtUtils.getOrgId(token);
|
||||
OrgContext.setOrgId(orgId);
|
||||
} catch (JwtException | IllegalArgumentException exception) {
|
||||
writeUnauthorized(response);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
OrgContext.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private String getToken(HttpServletRequest request) {
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (authorization == null || !authorization.startsWith(BEARER_PREFIX)) {
|
||||
throw new IllegalArgumentException("缺少登录凭证");
|
||||
}
|
||||
return authorization.substring(BEARER_PREFIX.length()).trim();
|
||||
}
|
||||
|
||||
private void writeUnauthorized(HttpServletResponse response) throws IOException {
|
||||
ApiResponse<Void> body = ApiResponse.fail(
|
||||
ApiResponse.AUTH_ERROR_CODE,
|
||||
"未登录或登录已失效"
|
||||
);
|
||||
response.setStatus(200);
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setContentType("application/json");
|
||||
objectMapper.writeValue(response.getWriter(), body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package cn.g3soft.fmsapi.controller;
|
||||
|
||||
import cn.g3soft.fmsapi.exception.BusinessException;
|
||||
import cn.g3soft.fmsapi.service.AuthService;
|
||||
import cn.g3soft.fmsapi.utils.ApiResponse;
|
||||
import cn.g3soft.fmsapi.utils.ParamUtils;
|
||||
import cn.g3soft.fmsapi.utils.StringUtils;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
public class AuthController {
|
||||
|
||||
@Resource
|
||||
private AuthService authService;
|
||||
|
||||
@PostMapping("/login")
|
||||
public ApiResponse<Map<String, Object>> login(
|
||||
@RequestBody(required = false) Map<String, Object> request
|
||||
) throws SQLException {
|
||||
String orgId = ParamUtils.getString(request, "orgid");
|
||||
String userId = ParamUtils.getString(request, "userid");
|
||||
String password = ParamUtils.getString(request, "password");
|
||||
|
||||
if (StringUtils.isBlank(orgId)) {
|
||||
throw new BusinessException("机构码不能为空");
|
||||
}
|
||||
if (StringUtils.isBlank(userId)) {
|
||||
throw new BusinessException("用户ID不能为空");
|
||||
}
|
||||
|
||||
Optional<Map<String, Object>> loginResponse = authService.login(
|
||||
orgId,
|
||||
userId,
|
||||
password
|
||||
);
|
||||
if (loginResponse.isEmpty()) {
|
||||
return ApiResponse.fail(
|
||||
ApiResponse.AUTH_ERROR_CODE,
|
||||
"机构码、账号或密码错误"
|
||||
);
|
||||
}
|
||||
return ApiResponse.success(loginResponse.get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package cn.g3soft.fmsapi.controller;
|
||||
|
||||
import cn.g3soft.fmsapi.service.DataService;
|
||||
import cn.g3soft.fmsapi.utils.ApiResponse;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/data")
|
||||
public class DataController {
|
||||
|
||||
@Resource
|
||||
private DataService dataService;
|
||||
|
||||
@PostMapping("/loaddata")
|
||||
public ApiResponse<List<Map<String, Object>>> loadData(
|
||||
@RequestBody(required = false) Map<String, Object> params
|
||||
) throws SQLException {
|
||||
return ApiResponse.success(dataService.loadData(params));
|
||||
}
|
||||
|
||||
@PostMapping("/loaddatabysql")
|
||||
public ApiResponse<List<Map<String, Object>>> loadDataBySql(
|
||||
@RequestBody(required = false) Map<String, Object> params
|
||||
) throws SQLException {
|
||||
return ApiResponse.success(dataService.loadDataBySql(params));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cn.g3soft.fmsapi.database;
|
||||
|
||||
public final class OrgContext {
|
||||
|
||||
private static final ThreadLocal<String> ORG_ID_HOLDER = new ThreadLocal<>();
|
||||
|
||||
private OrgContext() {
|
||||
}
|
||||
|
||||
public static void setOrgId(String orgId) {
|
||||
if (orgId == null || orgId.isBlank()) {
|
||||
throw new IllegalArgumentException("机构码不能为空");
|
||||
}
|
||||
ORG_ID_HOLDER.set(orgId);
|
||||
}
|
||||
|
||||
public static String getOrgId() {
|
||||
return ORG_ID_HOLDER.get();
|
||||
}
|
||||
|
||||
public static String requireOrgId() {
|
||||
String orgId = getOrgId();
|
||||
if (orgId == null) {
|
||||
throw new IllegalStateException("当前请求未设置机构上下文");
|
||||
}
|
||||
return orgId;
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
ORG_ID_HOLDER.remove();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package cn.g3soft.fmsapi.database;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
@Component
|
||||
public class OrgDataSourceFactory {
|
||||
|
||||
@Resource
|
||||
private OrgDatabaseProperties properties;
|
||||
|
||||
public DruidDataSource create(String orgId, OrgDatabaseConfig config) {
|
||||
OrgDatabaseProperties.Pool poolProperties = properties.getPool();
|
||||
DruidDataSource dataSource = new DruidDataSource();
|
||||
dataSource.setName("fms-" + orgId);
|
||||
dataSource.setUrl(config.url());
|
||||
dataSource.setUsername(config.username());
|
||||
dataSource.setPassword(config.password());
|
||||
dataSource.setDriverClassName(config.driver());
|
||||
dataSource.setInitialSize(poolProperties.getInitialSize());
|
||||
dataSource.setMinIdle(poolProperties.getMinIdle());
|
||||
dataSource.setMaxActive(poolProperties.getMaxActive());
|
||||
dataSource.setMaxWait(poolProperties.getMaxWait());
|
||||
dataSource.setValidationQuery(poolProperties.getValidationQuery());
|
||||
dataSource.setTestWhileIdle(poolProperties.isTestWhileIdle());
|
||||
dataSource.setTestOnBorrow(poolProperties.isTestOnBorrow());
|
||||
dataSource.setTestOnReturn(poolProperties.isTestOnReturn());
|
||||
dataSource.setTimeBetweenEvictionRunsMillis(
|
||||
poolProperties.getTimeBetweenEvictionRuns().toMillis()
|
||||
);
|
||||
dataSource.setMinEvictableIdleTimeMillis(
|
||||
poolProperties.getMinEvictableIdleTime().toMillis()
|
||||
);
|
||||
|
||||
try {
|
||||
dataSource.init();
|
||||
return dataSource;
|
||||
} catch (SQLException exception) {
|
||||
dataSource.close();
|
||||
throw new IllegalStateException("初始化机构数据库连接池失败: " + orgId, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package cn.g3soft.fmsapi.database;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
@Component
|
||||
public class OrgDataSourceManager {
|
||||
|
||||
private final ConcurrentMap<String, DruidDataSource> dataSources = new ConcurrentHashMap<>();
|
||||
|
||||
@Resource
|
||||
private OrgDatabaseConfigLoader configLoader;
|
||||
|
||||
@Resource
|
||||
private OrgDataSourceFactory dataSourceFactory;
|
||||
|
||||
public DruidDataSource getDataSource(String orgId) {
|
||||
String normalizedOrgId = configLoader.normalizeOrgId(orgId);
|
||||
return dataSources.computeIfAbsent(normalizedOrgId, this::createDataSource);
|
||||
}
|
||||
|
||||
public Connection getConnection(String orgId) throws SQLException {
|
||||
return getDataSource(orgId).getConnection();
|
||||
}
|
||||
|
||||
public Connection getConnection() throws SQLException {
|
||||
return getConnection(OrgContext.requireOrgId());
|
||||
}
|
||||
|
||||
public boolean closeDataSource(String orgId) {
|
||||
String normalizedOrgId = configLoader.normalizeOrgId(orgId);
|
||||
DruidDataSource dataSource = dataSources.remove(normalizedOrgId);
|
||||
if (dataSource == null) {
|
||||
return false;
|
||||
}
|
||||
dataSource.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
public int getDataSourceCount() {
|
||||
return dataSources.size();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void closeAll() {
|
||||
dataSources.values().forEach(DruidDataSource::close);
|
||||
dataSources.clear();
|
||||
}
|
||||
|
||||
private DruidDataSource createDataSource(String orgId) {
|
||||
OrgDatabaseConfig config = configLoader.load(orgId);
|
||||
return dataSourceFactory.create(orgId, config);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package cn.g3soft.fmsapi.database;
|
||||
|
||||
public record OrgDatabaseConfig(
|
||||
String url,
|
||||
String username,
|
||||
String password,
|
||||
String driver
|
||||
) {
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package cn.g3soft.fmsapi.database;
|
||||
|
||||
import cn.g3soft.fmsapi.exception.BusinessException;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Locale;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Component
|
||||
public class OrgDatabaseConfigLoader {
|
||||
|
||||
private static final Pattern ORG_ID_PATTERN = Pattern.compile("[A-Z0-9_-]{1,32}");
|
||||
private static final String DEFAULT_SQL_SERVER_DRIVER =
|
||||
"com.microsoft.sqlserver.jdbc.SQLServerDriver";
|
||||
|
||||
@Resource
|
||||
private OrgDatabaseProperties properties;
|
||||
|
||||
private Path configDir;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.configDir = properties.getConfigDir().toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
public OrgDatabaseConfig load(String orgId) {
|
||||
String normalizedOrgId = normalizeOrgId(orgId);
|
||||
Path configFile = configDir.resolve(normalizedOrgId + ".properties").normalize();
|
||||
if (!configFile.startsWith(configDir)) {
|
||||
throw new IllegalArgumentException("机构配置文件路径不合法");
|
||||
}
|
||||
if (!Files.isRegularFile(configFile)) {
|
||||
throw new IllegalStateException("未找到机构数据库配置文件: " + configFile);
|
||||
}
|
||||
|
||||
Properties properties = new Properties();
|
||||
try (InputStream input = Files.newInputStream(configFile);
|
||||
InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8)) {
|
||||
properties.load(reader);
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("读取机构数据库配置文件失败: " + configFile, exception);
|
||||
}
|
||||
|
||||
String url = required(properties, "url", configFile);
|
||||
if (!url.toLowerCase(Locale.ROOT).startsWith("jdbc:sqlserver:")) {
|
||||
throw new IllegalStateException("机构数据库必须使用 SQL Server: " + configFile);
|
||||
}
|
||||
|
||||
return new OrgDatabaseConfig(
|
||||
url,
|
||||
required(properties, "username", configFile),
|
||||
requiredPassword(properties, configFile),
|
||||
readDriver(properties)
|
||||
);
|
||||
}
|
||||
|
||||
public String normalizeOrgId(String orgId) {
|
||||
if (orgId == null) {
|
||||
throw new BusinessException("机构码不能为空");
|
||||
}
|
||||
|
||||
String normalized = orgId.trim().toUpperCase(Locale.ROOT);
|
||||
if (!ORG_ID_PATTERN.matcher(normalized).matches()) {
|
||||
throw new BusinessException("机构码格式不正确");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
public Path getConfigDir() {
|
||||
return configDir;
|
||||
}
|
||||
|
||||
private String required(Properties properties, String key, Path configFile) {
|
||||
String value = properties.getProperty(key);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalStateException("机构数据库配置缺少 " + key + ": " + configFile);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
private String requiredPassword(Properties properties, Path configFile) {
|
||||
String password = properties.getProperty("password");
|
||||
if (password == null || password.isBlank()) {
|
||||
throw new IllegalStateException("机构数据库配置缺少 password: " + configFile);
|
||||
}
|
||||
return password;
|
||||
}
|
||||
|
||||
private String readDriver(Properties properties) {
|
||||
String driver = properties.getProperty("driver");
|
||||
return driver == null || driver.isBlank() ? DEFAULT_SQL_SERVER_DRIVER : driver.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package cn.g3soft.fmsapi.database;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
|
||||
@ConfigurationProperties(prefix = "fms.database")
|
||||
public class OrgDatabaseProperties {
|
||||
|
||||
private Path configDir = Path.of("./config/dbconfigs");
|
||||
private final Pool pool = new Pool();
|
||||
|
||||
public Path getConfigDir() {
|
||||
return configDir;
|
||||
}
|
||||
|
||||
public void setConfigDir(Path configDir) {
|
||||
this.configDir = configDir;
|
||||
}
|
||||
|
||||
public Pool getPool() {
|
||||
return pool;
|
||||
}
|
||||
|
||||
public static class Pool {
|
||||
|
||||
private int initialSize;
|
||||
private int minIdle;
|
||||
private int maxActive = 10;
|
||||
private long maxWait = 5000;
|
||||
private String validationQuery = "SELECT 1";
|
||||
private boolean testWhileIdle = true;
|
||||
private boolean testOnBorrow;
|
||||
private boolean testOnReturn;
|
||||
private Duration timeBetweenEvictionRuns = Duration.ofMinutes(1);
|
||||
private Duration minEvictableIdleTime = Duration.ofMinutes(5);
|
||||
|
||||
public int getInitialSize() {
|
||||
return initialSize;
|
||||
}
|
||||
|
||||
public void setInitialSize(int initialSize) {
|
||||
this.initialSize = initialSize;
|
||||
}
|
||||
|
||||
public int getMinIdle() {
|
||||
return minIdle;
|
||||
}
|
||||
|
||||
public void setMinIdle(int minIdle) {
|
||||
this.minIdle = minIdle;
|
||||
}
|
||||
|
||||
public int getMaxActive() {
|
||||
return maxActive;
|
||||
}
|
||||
|
||||
public void setMaxActive(int maxActive) {
|
||||
this.maxActive = maxActive;
|
||||
}
|
||||
|
||||
public long getMaxWait() {
|
||||
return maxWait;
|
||||
}
|
||||
|
||||
public void setMaxWait(long maxWait) {
|
||||
this.maxWait = maxWait;
|
||||
}
|
||||
|
||||
public String getValidationQuery() {
|
||||
return validationQuery;
|
||||
}
|
||||
|
||||
public void setValidationQuery(String validationQuery) {
|
||||
this.validationQuery = validationQuery;
|
||||
}
|
||||
|
||||
public boolean isTestWhileIdle() {
|
||||
return testWhileIdle;
|
||||
}
|
||||
|
||||
public void setTestWhileIdle(boolean testWhileIdle) {
|
||||
this.testWhileIdle = testWhileIdle;
|
||||
}
|
||||
|
||||
public boolean isTestOnBorrow() {
|
||||
return testOnBorrow;
|
||||
}
|
||||
|
||||
public void setTestOnBorrow(boolean testOnBorrow) {
|
||||
this.testOnBorrow = testOnBorrow;
|
||||
}
|
||||
|
||||
public boolean isTestOnReturn() {
|
||||
return testOnReturn;
|
||||
}
|
||||
|
||||
public void setTestOnReturn(boolean testOnReturn) {
|
||||
this.testOnReturn = testOnReturn;
|
||||
}
|
||||
|
||||
public Duration getTimeBetweenEvictionRuns() {
|
||||
return timeBetweenEvictionRuns;
|
||||
}
|
||||
|
||||
public void setTimeBetweenEvictionRuns(Duration timeBetweenEvictionRuns) {
|
||||
this.timeBetweenEvictionRuns = timeBetweenEvictionRuns;
|
||||
}
|
||||
|
||||
public Duration getMinEvictableIdleTime() {
|
||||
return minEvictableIdleTime;
|
||||
}
|
||||
|
||||
public void setMinEvictableIdleTime(Duration minEvictableIdleTime) {
|
||||
this.minEvictableIdleTime = minEvictableIdleTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.g3soft.fmsapi.database;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.jdbc.datasource.AbstractDataSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
@Primary
|
||||
@Component
|
||||
public class OrgRoutingDataSource extends AbstractDataSource {
|
||||
|
||||
@Resource
|
||||
private OrgDataSourceManager dataSourceManager;
|
||||
|
||||
@Override
|
||||
public Connection getConnection() throws SQLException {
|
||||
return dataSourceManager.getConnection();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Connection getConnection(String username, String password) throws SQLException {
|
||||
return dataSourceManager.getDataSource(OrgContext.requireOrgId())
|
||||
.getConnection(username, password);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package cn.g3soft.fmsapi.exception;
|
||||
|
||||
public class BusinessException extends RuntimeException {
|
||||
|
||||
public BusinessException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package cn.g3soft.fmsapi.exception;
|
||||
|
||||
import cn.g3soft.fmsapi.utils.ApiResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ApiResponse<Void> handleBusinessException(BusinessException exception) {
|
||||
return ApiResponse.fail(exception.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ApiResponse<Void> handleException(
|
||||
Exception exception,
|
||||
HttpServletRequest request
|
||||
) {
|
||||
LOGGER.error(
|
||||
"系统异常,method={},uri={}",
|
||||
request.getMethod(),
|
||||
request.getRequestURI(),
|
||||
exception
|
||||
);
|
||||
return ApiResponse.fail(
|
||||
ApiResponse.SYSTEM_ERROR_CODE,
|
||||
"系统异常,请稍后重试"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package cn.g3soft.fmsapi.service;
|
||||
|
||||
import cn.g3soft.fmsapi.utils.DbUtils;
|
||||
import cn.g3soft.fmsapi.utils.JwtUtils;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.sql.SQLException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class AuthService {
|
||||
|
||||
@Resource
|
||||
private DbUtils dbUtils;
|
||||
|
||||
@Resource
|
||||
private JwtUtils jwtUtils;
|
||||
|
||||
public Optional<Map<String, Object>> login(
|
||||
String orgId,
|
||||
String userId,
|
||||
String password
|
||||
) throws SQLException {
|
||||
String normalizedOrgId = orgId.trim().toUpperCase(Locale.ROOT);
|
||||
String normalizedUserId = userId.trim();
|
||||
List<Map<String, Object>> users = dbUtils.loadData(
|
||||
normalizedOrgId,
|
||||
"b_user",
|
||||
"b_id = " + dbUtils.toSqlStringLiteral(normalizedUserId),
|
||||
null,
|
||||
List.of("b_id", "b_name", "b_password")
|
||||
);
|
||||
|
||||
if (users.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Map<String, Object> account = users.getFirst();
|
||||
String storedPassword = getString(account, "b_password");
|
||||
if (!passwordMatches(storedPassword, password)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
String accountId = getString(account, "b_id");
|
||||
String token = jwtUtils.generateToken(accountId, normalizedOrgId);
|
||||
|
||||
Map<String, Object> user = new LinkedHashMap<>();
|
||||
user.put("id", accountId);
|
||||
user.put("name", getString(account, "b_name"));
|
||||
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("token", token);
|
||||
result.put("orgid", normalizedOrgId);
|
||||
result.put("user", user);
|
||||
return Optional.of(result);
|
||||
}
|
||||
|
||||
private String getString(Map<String, Object> row, String column) {
|
||||
for (Map.Entry<String, Object> entry : row.entrySet()) {
|
||||
if (entry.getKey().equalsIgnoreCase(column)) {
|
||||
Object value = entry.getValue();
|
||||
return value == null ? null : value.toString();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean passwordMatches(String storedPassword, String submittedPassword) {
|
||||
if (storedPassword == null || submittedPassword == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return MessageDigest.isEqual(
|
||||
storedPassword.getBytes(StandardCharsets.UTF_8),
|
||||
submittedPassword.getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cn.g3soft.fmsapi.service;
|
||||
|
||||
import cn.g3soft.fmsapi.utils.DbUtils;
|
||||
import cn.g3soft.fmsapi.utils.ParamUtils;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class DataService {
|
||||
|
||||
@Resource
|
||||
private DbUtils dbUtils;
|
||||
|
||||
public List<Map<String, Object>> loadData(Map<String, Object> params) throws SQLException {
|
||||
return dbUtils.loadData(
|
||||
ParamUtils.getRequiredString(params, "viewName"),
|
||||
ParamUtils.getString(params, "searchCondition"),
|
||||
ParamUtils.getString(params, "orderField"),
|
||||
ParamUtils.getList(params, "searchColumns")
|
||||
);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> loadDataBySql(Map<String, Object> params) throws SQLException {
|
||||
return dbUtils.loadDataBySql(
|
||||
ParamUtils.getRequiredString(params, "sql")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package cn.g3soft.fmsapi.utils;
|
||||
|
||||
public record ApiResponse<T>(
|
||||
int code,
|
||||
String message,
|
||||
T data
|
||||
) {
|
||||
|
||||
public static final int SUCCESS_CODE = 0;
|
||||
public static final int AUTH_ERROR_CODE = 401;
|
||||
public static final int SYSTEM_ERROR_CODE = 500;
|
||||
public static final int BUSINESS_ERROR_CODE = 1000;
|
||||
|
||||
public static <T> ApiResponse<T> success(T data) {
|
||||
return new ApiResponse<>(SUCCESS_CODE, "操作成功", data);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> fail(String message) {
|
||||
return fail(BUSINESS_ERROR_CODE, message);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> fail(int code, String message) {
|
||||
return new ApiResponse<>(code, message, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package cn.g3soft.fmsapi.utils;
|
||||
|
||||
import cn.g3soft.fmsapi.database.OrgDataSourceManager;
|
||||
import cn.g3soft.fmsapi.exception.BusinessException;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.jdbc.datasource.DataSourceUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class DbUtils {
|
||||
|
||||
private static final Pattern SAFE_IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");
|
||||
private static final Pattern READ_SQL_PATTERN = Pattern.compile("(?is)^\\s*(select|with)\\b");
|
||||
private static final Pattern WRITE_SQL_PATTERN = Pattern.compile(
|
||||
"(?i)\\b(insert|update|delete|merge|drop|truncate|alter|create|exec|execute|grant|revoke|backup|restore|dbcc|kill|use|into)\\b"
|
||||
);
|
||||
private static final Pattern SQL_COMMENT_PATTERN = Pattern.compile("--|/\\*|\\*/");
|
||||
|
||||
@Resource
|
||||
private OrgDataSourceManager dataSourceManager;
|
||||
|
||||
@Resource
|
||||
private DataSource dataSource;
|
||||
|
||||
public List<Map<String, Object>> loadData(String viewName) throws SQLException {
|
||||
return loadData(viewName, null, null, null);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> loadData(
|
||||
String viewName,
|
||||
String searchCondition,
|
||||
String orderField,
|
||||
List<String> searchColumns
|
||||
) throws SQLException {
|
||||
String sql = buildLoadDataSql(viewName, searchCondition, orderField, searchColumns);
|
||||
Connection connection = DataSourceUtils.getConnection(dataSource);
|
||||
try {
|
||||
return executeQuery(connection, sql);
|
||||
} finally {
|
||||
DataSourceUtils.releaseConnection(connection, dataSource);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> loadData(
|
||||
String orgId,
|
||||
String viewName,
|
||||
String searchCondition,
|
||||
String orderField,
|
||||
List<String> searchColumns
|
||||
) throws SQLException {
|
||||
String sql = buildLoadDataSql(viewName, searchCondition, orderField, searchColumns);
|
||||
try (Connection connection = dataSourceManager.getConnection(orgId)) {
|
||||
return executeQuery(connection, sql);
|
||||
}
|
||||
}
|
||||
|
||||
private String buildLoadDataSql(
|
||||
String viewName,
|
||||
String searchCondition,
|
||||
String orderField,
|
||||
List<String> searchColumns
|
||||
) {
|
||||
String columnsSql = buildColumns(searchColumns);
|
||||
StringBuilder sql = new StringBuilder("SELECT ")
|
||||
.append(columnsSql)
|
||||
.append(" FROM ")
|
||||
.append(quoteQualifiedIdentifier(viewName));
|
||||
|
||||
if (hasText(searchCondition)) {
|
||||
sql.append(" WHERE ").append(searchCondition.trim());
|
||||
}
|
||||
if (hasText(orderField)) {
|
||||
sql.append(" ORDER BY ").append(buildOrderBy(orderField));
|
||||
}
|
||||
|
||||
String querySql = sql.toString();
|
||||
validateReadOnlySql(querySql);
|
||||
return querySql;
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> loadDataBySql(String sql) throws SQLException {
|
||||
validateReadOnlySql(sql);
|
||||
|
||||
Connection connection = DataSourceUtils.getConnection(dataSource);
|
||||
try {
|
||||
return executeQuery(connection, sql);
|
||||
} finally {
|
||||
DataSourceUtils.releaseConnection(connection, dataSource);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> loadDataBySql(
|
||||
Connection connection,
|
||||
String sql
|
||||
) throws SQLException {
|
||||
if (connection == null) {
|
||||
throw new IllegalArgumentException("数据库连接不能为空");
|
||||
}
|
||||
validateReadOnlySql(sql);
|
||||
|
||||
return executeQuery(connection, sql);
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> executeQuery(
|
||||
Connection connection,
|
||||
String sql
|
||||
) throws SQLException {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
try (ResultSet resultSet = statement.executeQuery(sql)) {
|
||||
return readRows(resultSet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String toSqlStringLiteral(String value) {
|
||||
if (value == null) {
|
||||
return "NULL";
|
||||
}
|
||||
return "N'" + value.replace("'", "''") + "'";
|
||||
}
|
||||
|
||||
public void validateIdentifier(String identifier) {
|
||||
if (!hasText(identifier) || !SAFE_IDENTIFIER.matcher(identifier).matches()) {
|
||||
throw new BusinessException("非法数据库标识符: " + identifier);
|
||||
}
|
||||
}
|
||||
|
||||
public void validateReadOnlySql(String sql) {
|
||||
if (!hasText(sql)) {
|
||||
throw new BusinessException("查询 SQL 不能为空");
|
||||
}
|
||||
|
||||
String normalizedSql = sql.trim();
|
||||
if (!READ_SQL_PATTERN.matcher(normalizedSql).find()) {
|
||||
throw new BusinessException("只允许执行只读查询");
|
||||
}
|
||||
String sqlStructure = removeStringLiterals(normalizedSql);
|
||||
if (sqlStructure.contains(";")) {
|
||||
throw new BusinessException("查询 SQL 不允许包含分号");
|
||||
}
|
||||
if (SQL_COMMENT_PATTERN.matcher(sqlStructure).find()) {
|
||||
throw new BusinessException("查询 SQL 不允许包含注释");
|
||||
}
|
||||
if (WRITE_SQL_PATTERN.matcher(sqlStructure).find()) {
|
||||
throw new BusinessException("查询 SQL 包含非只读关键字");
|
||||
}
|
||||
}
|
||||
|
||||
private String removeStringLiterals(String sql) {
|
||||
StringBuilder result = new StringBuilder(sql.length());
|
||||
boolean inString = false;
|
||||
|
||||
for (int index = 0; index < sql.length(); index++) {
|
||||
char character = sql.charAt(index);
|
||||
if (character != '\'') {
|
||||
result.append(inString ? ' ' : character);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inString && index + 1 < sql.length() && sql.charAt(index + 1) == '\'') {
|
||||
result.append(" ");
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
|
||||
inString = !inString;
|
||||
result.append(' ');
|
||||
}
|
||||
|
||||
if (inString) {
|
||||
throw new BusinessException("SQL 字符串未闭合");
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private String buildColumns(List<String> searchColumns) {
|
||||
if (searchColumns == null || searchColumns.isEmpty()) {
|
||||
return "*";
|
||||
}
|
||||
return searchColumns.stream()
|
||||
.map(this::quoteQualifiedIdentifier)
|
||||
.collect(Collectors.joining(", "));
|
||||
}
|
||||
|
||||
private String buildOrderBy(String orderField) {
|
||||
String[] parts = orderField.trim().split("\\s+");
|
||||
if (parts.length > 2) {
|
||||
throw new BusinessException("排序字段格式不正确");
|
||||
}
|
||||
|
||||
String direction = "";
|
||||
if (parts.length == 2) {
|
||||
if (!"asc".equalsIgnoreCase(parts[1]) && !"desc".equalsIgnoreCase(parts[1])) {
|
||||
throw new BusinessException("排序方向只允许 ASC 或 DESC");
|
||||
}
|
||||
direction = " " + parts[1].toUpperCase();
|
||||
}
|
||||
return quoteQualifiedIdentifier(parts[0]) + direction;
|
||||
}
|
||||
|
||||
private String quoteQualifiedIdentifier(String identifier) {
|
||||
if (!hasText(identifier)) {
|
||||
throw new BusinessException("数据库标识符不能为空");
|
||||
}
|
||||
|
||||
return Arrays.stream(identifier.trim().split("\\."))
|
||||
.peek(this::validateIdentifier)
|
||||
.map(part -> "[" + part + "]")
|
||||
.collect(Collectors.joining("."));
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> readRows(ResultSet resultSet) throws SQLException {
|
||||
ResultSetMetaData metadata = resultSet.getMetaData();
|
||||
int columnCount = metadata.getColumnCount();
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
|
||||
while (resultSet.next()) {
|
||||
Map<String, Object> row = new LinkedHashMap<>(columnCount);
|
||||
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
|
||||
row.put(metadata.getColumnLabel(columnIndex), resultSet.getObject(columnIndex));
|
||||
}
|
||||
rows.add(row);
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
private boolean hasText(String value) {
|
||||
return value != null && !value.isBlank();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package cn.g3soft.fmsapi.utils;
|
||||
|
||||
import cn.g3soft.fmsapi.config.AuthProperties;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
|
||||
@Component
|
||||
public class JwtUtils {
|
||||
|
||||
@Resource
|
||||
private AuthProperties properties;
|
||||
|
||||
private SecretKey signingKey;
|
||||
private Duration expiration;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
String jwtSecret = properties.getJwtSecret();
|
||||
if (jwtSecret == null || jwtSecret.getBytes(StandardCharsets.UTF_8).length < 32) {
|
||||
throw new IllegalStateException("JWT 密钥长度不能少于 32 字节");
|
||||
}
|
||||
if (properties.getJwtExpiration() == null
|
||||
|| properties.getJwtExpiration().isZero()
|
||||
|| properties.getJwtExpiration().isNegative()) {
|
||||
throw new IllegalStateException("JWT 有效期必须大于 0");
|
||||
}
|
||||
|
||||
this.signingKey = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
|
||||
this.expiration = properties.getJwtExpiration();
|
||||
}
|
||||
|
||||
public String generateToken(String userId, String orgId) {
|
||||
Instant issuedAt = Instant.now();
|
||||
Instant expiresAt = issuedAt.plus(expiration);
|
||||
|
||||
return Jwts.builder()
|
||||
.subject(userId)
|
||||
.claim("orgid", orgId)
|
||||
.issuedAt(Date.from(issuedAt))
|
||||
.expiration(Date.from(expiresAt))
|
||||
.signWith(signingKey)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public String getOrgId(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(signingKey)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload()
|
||||
.get("orgid", String.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cn.g3soft.fmsapi.utils;
|
||||
|
||||
import cn.g3soft.fmsapi.exception.BusinessException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public final class ParamUtils {
|
||||
|
||||
private ParamUtils() {
|
||||
}
|
||||
|
||||
public static String getString(Map<String, ?> params, String field) {
|
||||
return get(params, field, String.class);
|
||||
}
|
||||
|
||||
public static String getRequiredString(Map<String, ?> params, String field) {
|
||||
String value = getString(params, field);
|
||||
if (StringUtils.isBlank(value)) {
|
||||
throw new BusinessException(field + " 不能为空");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static <T> T get(Map<String, ?> params, String field, Class<T> type) {
|
||||
Object value = getValue(params, field);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (!type.isInstance(value)) {
|
||||
throw new BusinessException(field + " 参数类型不正确");
|
||||
}
|
||||
return type.cast(value);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> List<T> getList(Map<String, ?> params, String field) {
|
||||
Object value = getValue(params, field);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (!(value instanceof List<?> values)) {
|
||||
throw new BusinessException(field + " 参数类型不正确");
|
||||
}
|
||||
return (List<T>) values;
|
||||
}
|
||||
|
||||
public static Object[] getArray(Map<String, ?> params, String field) {
|
||||
List<?> values = getList(params, field);
|
||||
if (values == null) {
|
||||
return null;
|
||||
}
|
||||
return values.toArray();
|
||||
}
|
||||
|
||||
private static Object getValue(Map<String, ?> params, String field) {
|
||||
return params == null ? null : params.get(field);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package cn.g3soft.fmsapi.utils;
|
||||
|
||||
public final class StringUtils {
|
||||
|
||||
private StringUtils() {
|
||||
}
|
||||
|
||||
public static boolean isBlank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
server:
|
||||
servlet:
|
||||
context-path: /api
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: fms-api
|
||||
|
||||
fms:
|
||||
auth:
|
||||
jwt-secret: "${FMS_JWT_SECRET:fms-api-development-jwt-secret-change-me}"
|
||||
jwt-expiration: 24h
|
||||
database:
|
||||
config-dir: ./config/dbconfigs
|
||||
pool:
|
||||
initial-size: 0
|
||||
min-idle: 0
|
||||
max-active: 10
|
||||
max-wait: 5000
|
||||
validation-query: SELECT 1
|
||||
test-while-idle: true
|
||||
test-on-borrow: false
|
||||
test-on-return: false
|
||||
time-between-eviction-runs: 60s
|
||||
min-evictable-idle-time: 5m
|
||||
@@ -0,0 +1,13 @@
|
||||
package cn.g3soft.fmsapi;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class FmsApiApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user