Merge remote-tracking branch 'origin/main'

This commit is contained in:
jiang 2024-11-12 11:08:10 +08:00
commit e764864a99
19 changed files with 300 additions and 228 deletions

View File

@ -36,12 +36,12 @@ public interface RemoteConfigService {
/** /**
* 根据参数键名查询参数值 * 根据参数键名查询参数值
*
* @param configKey 参数键名 * @param configKey 参数键名
* @param source 请求来源使用SecurityConstants.INNER
* @return 获取参数信息 * @return 获取参数信息
*/ */
@GetMapping(value = "/config/configKey/{configKey}") @GetMapping(value = "/config/configKey/{configKey}")
public AjaxResult getConfigKey(@PathVariable("configKey") String configKey, @RequestHeader(SecurityConstants.FROM_SOURCE) String source); public AjaxResult getConfigKey(@PathVariable("configKey") String configKey);
/** /**
* 新增参数配置 * 新增参数配置

View File

@ -10,11 +10,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -45,7 +40,7 @@ public class RemoteConfigFallbackFactory implements FallbackFactory<RemoteConfig
return AjaxResult.error("根据参数编号获取参数配置列表失败:" + throwable.getMessage()); return AjaxResult.error("根据参数编号获取参数配置列表失败:" + throwable.getMessage());
} }
@Override @Override
public AjaxResult getConfigKey(String configKey, String source){ public AjaxResult getConfigKey(String configKey){
return AjaxResult.error("根据参数键名获取参数配置列表失败:" + throwable.getMessage()); return AjaxResult.error("根据参数键名获取参数配置列表失败:" + throwable.getMessage());
} }

View File

@ -27,6 +27,7 @@ public class ConfigController {
map.put("loginConfig", systemConfig.getLoginConfig()); map.put("loginConfig", systemConfig.getLoginConfig());
map.put("registersConfig", systemConfig.getRegistersConfig()); map.put("registersConfig", systemConfig.getRegistersConfig());
map.put("isAdmin", systemConfig.isAdmin()); map.put("isAdmin", systemConfig.isAdmin());
map.put("webSocketurl", systemConfig.getWebsocketurl());
map.put("isAddRootCompany",systemConfig.isAddRootCompany()); map.put("isAddRootCompany",systemConfig.isAddRootCompany());
map.put("requestConfig",systemConfig.getRequestConfig()); map.put("requestConfig",systemConfig.getRequestConfig());
map.put("passwordConfig",systemConfig.getPasswordConfig()); map.put("passwordConfig",systemConfig.getPasswordConfig());

View File

@ -5,14 +5,18 @@ import com.bonus.auth.factory.LoginStrategyFactory;
import com.bonus.auth.form.LoginBody; import com.bonus.auth.form.LoginBody;
import com.bonus.auth.form.RegisterBody; import com.bonus.auth.form.RegisterBody;
import com.bonus.auth.service.*; import com.bonus.auth.service.*;
import com.bonus.common.core.constant.CacheConstants;
import com.bonus.common.core.constant.SecurityConstants; import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.domain.R; import com.bonus.common.core.domain.R;
import com.bonus.common.core.utils.JwtUtils; import com.bonus.common.core.utils.JwtUtils;
import com.bonus.common.core.utils.StringUtils; import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.redis.service.RedisService;
import com.bonus.common.security.auth.AuthUtil; import com.bonus.common.security.auth.AuthUtil;
import com.bonus.common.security.service.TokenService; import com.bonus.common.security.service.TokenService;
import com.bonus.common.security.utils.SecurityUtils; import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.config.SystemConfig; import com.bonus.config.SystemConfig;
import com.bonus.system.api.RemoteConfigService;
import com.bonus.system.api.RemoteLogService; import com.bonus.system.api.RemoteLogService;
import com.bonus.system.api.RemoteUserService; import com.bonus.system.api.RemoteUserService;
import com.bonus.system.api.domain.SysUser; import com.bonus.system.api.domain.SysUser;
@ -26,6 +30,7 @@ import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Set; import java.util.Set;
/** /**
@ -60,6 +65,12 @@ public class TokenController {
@Autowired @Autowired
private SysRecordLogService logService; private SysRecordLogService logService;
@Autowired
private RedisService redisService;
@Resource
private RemoteConfigService configService;
@PostMapping("isAdmin") @PostMapping("isAdmin")
public R<?> isAdmin(@RequestBody LoginBody form) { public R<?> isAdmin(@RequestBody LoginBody form) {
if (!config.isAdmin()) { if (!config.isAdmin()) {
@ -109,6 +120,19 @@ public class TokenController {
if (form.getLoginType()== LoginType.EMAIL_OTP || form.getLoginType()== LoginType.PHONE_OTP ){ if (form.getLoginType()== LoginType.EMAIL_OTP || form.getLoginType()== LoginType.PHONE_OTP ){
form.setPassword(form.getVerificationCode()); form.setPassword(form.getVerificationCode());
} }
/**对系统并发数进行判断*/
long concurrency = 100;
AjaxResult result = configService.getConfigKey("sys.backend.concurrency");
if (result.isSuccess())
{
concurrency = Long.parseLong(result.get("msg").toString());
}
Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
if (keys.size() >= concurrency){
return R.fail("当前系统用户并发数超过系统配置,请稍后再试");
}
LoginUser login = strategy.login(form.getUsername(), form.getPassword()); LoginUser login = strategy.login(form.getUsername(), form.getPassword());
logService.saveLogin(form.getUsername(), "登录", "登录成功", null, "成功"); logService.saveLogin(form.getUsername(), "登录", "登录成功", null, "成功");
return R.ok(tokenService.createToken(login)); return R.ok(tokenService.createToken(login));

View File

@ -298,12 +298,24 @@ public class PasswordValidatorService {
// 如果 ipAddress 为空检查是否在 ip 范围内 // 如果 ipAddress 为空检查是否在 ip 范围内
if (ObjectUtils.isEmpty(ipAddress)) { if (ObjectUtils.isEmpty(ipAddress)) {
if (isIpInRange(ip, ipRangeStart, ipRangeEnd)) { if (isIpInRange(ip, ipRangeStart, ipRangeEnd)) {
handleAccessTimeCheck(accessStartTime, accessEndTime); boolean result = handleAccessTimeCheck(user, accessStartTime, accessEndTime);
if (!result) {
throw new ServiceException("ip地址异常");
}else{
return;
}
} }
} else if (ipAddress.equals(ip)) { } else if (ipAddress.equals(ip)) {
handleAccessTimeCheck(accessStartTime, accessEndTime); boolean result = handleAccessTimeCheck(user, accessStartTime, accessEndTime);
if (!result) {
throw new ServiceException("ip地址异常");
}else{
return;
}
} }
} }
} }
@ -312,27 +324,20 @@ public class PasswordValidatorService {
* @param accessStartTime 访问开始时间 * @param accessStartTime 访问开始时间
* @param accessEndTime 访问结束时间 * @param accessEndTime 访问结束时间
*/ */
private void handleAccessTimeCheck(String accessStartTime, String accessEndTime) { private boolean handleAccessTimeCheck(SysUser user, String accessStartTime, String accessEndTime) {
if (ObjectUtils.isNotEmpty(accessStartTime)) { if (ObjectUtils.isNotEmpty(accessStartTime)) {
boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime); boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime);
if (!currentTimeInRange) { if (!currentTimeInRange) {
handleException(); // 异常处理 recordLogService.saveErrorLogs(user.getUserName(), System.currentTimeMillis(), user.getUserId().toString(),"IP地址异常");
return false;
} else { } else {
handleNormalProcess(); // 正常处理 return true;
} }
} else { } else {
handleNormalProcess(); // 正常处理 return true;
} }
} }
/**
* 处理异常情况
*/
private void handleException() {
// 异常处理的具体逻辑
System.out.println("IP access is outside the allowed time range or other error occurred.");
}
/** /**
* 处理正常情况 * 处理正常情况
*/ */

View File

@ -2,7 +2,6 @@ package com.bonus.auth.service;
import com.bonus.common.core.constant.CacheConstants; import com.bonus.common.core.constant.CacheConstants;
import com.bonus.common.core.constant.Constants; import com.bonus.common.core.constant.Constants;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.domain.R; import com.bonus.common.core.domain.R;
import com.bonus.common.core.exception.CaptchaException; import com.bonus.common.core.exception.CaptchaException;
import com.bonus.common.core.exception.ServiceException; import com.bonus.common.core.exception.ServiceException;
@ -57,8 +56,8 @@ public class SysPasswordService {
Integer retryCount = redisService.getCacheObject(getCacheKey(username)); Integer retryCount = redisService.getCacheObject(getCacheKey(username));
Integer times = 5; Integer times = 5;
Integer lockTime = 20; Integer lockTime = 20;
AjaxResult timesAjaxResult = configService.getConfigKey("sys.login.failed.times", SecurityConstants.INNER); AjaxResult timesAjaxResult = configService.getConfigKey("sys.login.failed.times");
AjaxResult lockTimeAjaxResult = configService.getConfigKey("sys.login.failed.locktime", SecurityConstants.INNER); AjaxResult lockTimeAjaxResult = configService.getConfigKey("sys.login.failed.locktime");
if (timesAjaxResult.isSuccess()){ if (timesAjaxResult.isSuccess()){
times = Integer.parseInt(timesAjaxResult.get("msg").toString()); times = Integer.parseInt(timesAjaxResult.get("msg").toString());
} }

View File

@ -48,7 +48,7 @@ public class SystemConfig {
/** /**
* websocketUrl * websocketUrl
*/ */
private String webSocketurl; private String websocketurl;
@Data @Data
@RefreshScope @RefreshScope

View File

@ -25,7 +25,7 @@ import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
public class ParamSecureHandler implements AsyncHandlerInterceptor { public class ParamSecureHandler implements AsyncHandlerInterceptor {
private static final String [] WHITE_URL = { private static final String [] WHITE_URL = {
"/login", "/isAdmin", "/isLogin" ,"/register","/user/register","/operlog/addLogs","/job/edit","/user/resetPwd","/user/profile/updatePwd'"}; "/login", "/isAdmin", "/isLogin" ,"/register","/user/register","/operlog/addLogs","/job/edit","/user/resetPwd","/user/profile/updatePwd","/user/confirmPassword"};
private String rnd = null; private String rnd = null;
public static String ur = "/"; public static String ur = "/";

View File

@ -1,5 +1,6 @@
package com.bonus.common.security.service; package com.bonus.common.security.service;
import cn.hutool.core.util.ObjectUtil;
import com.bonus.common.core.constant.CacheConstants; import com.bonus.common.core.constant.CacheConstants;
import com.bonus.common.core.constant.SecurityConstants; import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.utils.JwtUtils; import com.bonus.common.core.utils.JwtUtils;
@ -11,6 +12,7 @@ import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.redis.service.RedisService; import com.bonus.common.redis.service.RedisService;
import com.bonus.common.security.utils.SecurityUtils; import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.config.SystemConfig; import com.bonus.config.SystemConfig;
import com.bonus.system.api.RemoteConfigService;
import com.bonus.system.api.RemoteUserService; import com.bonus.system.api.RemoteUserService;
import com.bonus.system.api.domain.SysUser; import com.bonus.system.api.domain.SysUser;
import com.bonus.system.api.model.LoginUser; import com.bonus.system.api.model.LoginUser;
@ -81,8 +83,9 @@ public class TokenService {
rspMap.put("access_token", accessToken); rspMap.put("access_token", accessToken);
rspMap.put("expires_in", EXPIRETIME); rspMap.put("expires_in", EXPIRETIME);
rspMap.put("isLogin", isLogin(String.valueOf(userId))); rspMap.put("isLogin", isLogin(String.valueOf(userId)));
long tokenTime = getTokenTime();
//对token进行存储 //对token进行存储
redisService.setCacheObject(LOGIN_USER_KEY + userId, token, systemConfig.getTokenTime(), TimeUnit.MINUTES); redisService.setCacheObject(LOGIN_USER_KEY + userId, token, tokenTime, TimeUnit.MINUTES);
SysUser sysUser = new SysUser(); SysUser sysUser = new SysUser();
sysUser.setUserId(loginUser.getSysUser().getUserId()); sysUser.setUserId(loginUser.getSysUser().getUserId());
sysUser.setLoginDate(new Date()); sysUser.setLoginDate(new Date());
@ -187,14 +190,29 @@ public class TokenService {
* @param loginUser 登录信息 * @param loginUser 登录信息
*/ */
public void refreshToken(LoginUser loginUser) { public void refreshToken(LoginUser loginUser) {
long tokenTime = getTokenTime();
loginUser.setLoginTime(System.currentTimeMillis()); loginUser.setLoginTime(System.currentTimeMillis());
loginUser.setExpireTime(loginUser.getLoginTime() + systemConfig.getTokenTime() * MILLIS_MINUTE); loginUser.setExpireTime(loginUser.getLoginTime() + tokenTime * MILLIS_MINUTE);
// 根据uuid将loginUser缓存 // 根据uuid将loginUser缓存
String userKey = getTokenKey(loginUser.getToken()); String userKey = getTokenKey(loginUser.getToken());
redisService.setCacheObject(userKey, loginUser, systemConfig.getTokenTime(), TimeUnit.MINUTES); redisService.setCacheObject(userKey, loginUser, tokenTime, TimeUnit.MINUTES);
} }
private String getTokenKey(String token) { private String getTokenKey(String token) {
return ACCESS_TOKEN + token; return ACCESS_TOKEN + token;
} }
private Long getTokenTime(){
long tokenTime = 20L;
String redisResult = redisService.getCacheObject("sys_config:"+ "sys.visit.tokentime");
if(!redisResult.isEmpty()) {
tokenTime = Long.parseLong(redisResult);
}else {
Long result = systemConfig.getTokenTime();
if (!ObjectUtil.isEmpty(result)){
tokenTime = result;
}
}
return tokenTime;
}
} }

View File

@ -1,95 +1,101 @@
package com.bonus.gateway.filter; //package com.bonus.gateway.filter;
//
import com.bonus.common.core.constant.CacheConstants; //import com.bonus.common.core.constant.CacheConstants;
import com.bonus.common.redis.service.RedisService; //import com.bonus.common.core.utils.DateUtils;
//import com.bonus.common.core.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j; //import com.bonus.common.core.utils.ip.IpUtils;
import org.apache.commons.lang3.ObjectUtils; //import com.bonus.common.redis.service.RedisService;
import org.springframework.cloud.gateway.filter.GatewayFilterChain; //
import org.springframework.cloud.gateway.filter.GlobalFilter; //import com.bonus.system.api.RemoteLogService;
import org.springframework.core.Ordered; //import com.bonus.system.api.domain.SysLogsVo;
import org.springframework.stereotype.Component; //import lombok.extern.slf4j.Slf4j;
import org.springframework.web.server.ServerWebExchange; //import org.apache.commons.lang3.ObjectUtils;
import reactor.core.publisher.Mono; //import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
import javax.annotation.Resource; //import org.springframework.core.Ordered;
import java.net.InetAddress; //import org.springframework.stereotype.Component;
import java.net.UnknownHostException; //import org.springframework.web.server.ServerWebExchange;
import java.time.LocalDateTime; //import reactor.core.publisher.Mono;
import java.time.format.DateTimeFormatter; //
import java.util.List; //import javax.annotation.Resource;
import java.util.Map; //import java.net.InetAddress;
//import java.net.UnknownHostException;
/** //import java.time.LocalDateTime;
* @author bonus //import java.time.format.DateTimeFormatter;
*/ //import java.util.List;
@Component //import java.util.Map;
@Slf4j //import java.util.UUID;
public class IpFilter implements GlobalFilter, Ordered { //
@Resource ///**
private RedisService redisService; // * @author bonus
// */
//@Component
//@Slf4j
//public class IpFilter implements GlobalFilter, Ordered {
// @Resource // @Resource
// private RemoteLogService remoteLogService; // private RedisService redisService;
// public RemoteLogService remoteLogService = SpringUtils.getBean(RemoteLogService.class); //
/** //// @Resource
* Process the Web request and (optionally) delegate to the next {@code GatewayFilter} //// private RemoteLogService remoteLogService;
* through the given {@link GatewayFilterChain}. //// public RemoteLogService remoteLogService = SpringUtils.getBean(RemoteLogService.class);
* // /**
* @param exchange the current server exchange // * Process the Web request and (optionally) delegate to the next {@code GatewayFilter}
* @param chain provides a way to delegate to the next filter // * through the given {@link GatewayFilterChain}.
* @return {@code Mono<Void>} to indicate when request processing is complete // *
*/ // * @param exchange the current server exchange
@Override // * @param chain provides a way to delegate to the next filter
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // * @return {@code Mono<Void>} to indicate when request processing is complete
List<Map<String,Object>> cacheList = redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST); // */
// @Override
// 获取客户端的 IP 地址 // public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String ip = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For"); // List<Map<String,Object>> cacheList = redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST);
for (Map<String,Object> map : cacheList) { //
String ipAddress = map.containsKey("ipAddress") ? map.get("ipAddress").toString() : null; // // 获取客户端的 IP 地址
String ipRangeEnd = map.containsKey("ipRangeEnd") ?map.get("ipRangeEnd").toString(): null; // String ip = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For");
String ipRangeStart = map.containsKey("ipRangeStart")?map.get("ipRangeStart").toString():null; // for (Map<String,Object> map : cacheList) {
String accessStartTime =map.containsKey("accessStartTime")? map.get("accessStartTime").toString():null; // String ipAddress = map.containsKey("ipAddress") ? map.get("ipAddress").toString() : null;
String accessEndTime = map.containsKey("accessEndTime")?map.get("accessEndTime").toString():null; // String ipRangeEnd = map.containsKey("ipRangeEnd") ?map.get("ipRangeEnd").toString(): null;
if (ObjectUtils.isEmpty(ipAddress)){ // String ipRangeStart = map.containsKey("ipRangeStart")?map.get("ipRangeStart").toString():null;
if (isIpInRange(ip, ipRangeStart, ipRangeEnd)){ // String accessStartTime =map.containsKey("accessStartTime")? map.get("accessStartTime").toString():null;
if (ObjectUtils.isNotEmpty(accessStartTime)){ // String accessEndTime = map.containsKey("accessEndTime")?map.get("accessEndTime").toString():null;
boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime); // if (ObjectUtils.isEmpty(ipAddress)){
if (!currentTimeInRange){ // if (isIpInRange(ip, ipRangeStart, ipRangeEnd)){
// 完成响应 // if (ObjectUtils.isNotEmpty(accessStartTime)){
// boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime);
// if (!currentTimeInRange){
// // 完成响应
// handleLog(); // handleLog();
exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN); // exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN);
return exchange.getResponse().setComplete(); // return exchange.getResponse().setComplete();
}else { // }else {
return chain.filter(exchange); // return chain.filter(exchange);
} // }
}else { // }else {
return chain.filter(exchange); // return chain.filter(exchange);
} // }
//
} // }
}else { // }else {
if (ipAddress.equals(ip)){ // if (ipAddress.equals(ip)){
if (ObjectUtils.isNotEmpty(accessStartTime)){ // if (ObjectUtils.isNotEmpty(accessStartTime)){
boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime); // boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime);
if (!currentTimeInRange){ // if (!currentTimeInRange){
// 完成响应 // // 完成响应
// handleLog(); //// handleLog();
exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN); // exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN);
return exchange.getResponse().setComplete(); // return exchange.getResponse().setComplete();
}else { // }else {
return chain.filter(exchange); // return chain.filter(exchange);
} // }
}else { // }else {
return chain.filter(exchange); // return chain.filter(exchange);
} // }
} // }
} // }
} // }
exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN); // exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN);
return exchange.getResponse().setComplete(); // return exchange.getResponse().setComplete();
} // }
// private void handleLog() // private void handleLog()
// { // {
// SysLogsVo sysLogsVo = new SysLogsVo(); // SysLogsVo sysLogsVo = new SysLogsVo();
@ -102,77 +108,77 @@ public class IpFilter implements GlobalFilter, Ordered {
// sysLogsVo.setOperType("IP地址异常"); // sysLogsVo.setOperType("IP地址异常");
// sysLogsVo.setWarningStatus("0"); // sysLogsVo.setWarningStatus("0");
// try { // try {
// remoteLogService.addLogs(sysLogsVo, SecurityConstants.INNER); //// remoteLogService.addLogs(sysLogsVo, "inner");
// } catch (Exception e) { // } catch (Exception e) {
// throw new RuntimeException(e); // throw new RuntimeException(e);
// } // }
// } // }
/** // /**
* 检查给定的IP地址是否在指定的网段区间内 // * 检查给定的IP地址是否在指定的网段区间内
* // *
* @param ip 要检查的IP地址例如 "192.168.1.10" // * @param ip 要检查的IP地址例如 "192.168.1.10"
* @param startIp 区间开始的IP地址例如 "192.168.1.0" // * @param startIp 区间开始的IP地址例如 "192.168.1.0"
* @param endIp 区间结束的IP地址例如 "192.168.1.255" // * @param endIp 区间结束的IP地址例如 "192.168.1.255"
* @return true 如果IP在区间内否则返回 false // * @return true 如果IP在区间内否则返回 false
*/ // */
public static boolean isIpInRange(String ip, String startIp, String endIp) { // public static boolean isIpInRange(String ip, String startIp, String endIp) {
try { // try {
// IP 地址起始 IP 和结束 IP 转换为整数 // // IP 地址起始 IP 和结束 IP 转换为整数
long ipToCheck = ipToLong(InetAddress.getByName(ip)); // long ipToCheck = ipToLong(InetAddress.getByName(ip));
long start = ipToLong(InetAddress.getByName(startIp)); // long start = ipToLong(InetAddress.getByName(startIp));
long end = ipToLong(InetAddress.getByName(endIp)); // long end = ipToLong(InetAddress.getByName(endIp));
//
// 检查 IP 是否在区间内 // // 检查 IP 是否在区间内
return ipToCheck >= start && ipToCheck <= end; // return ipToCheck >= start && ipToCheck <= end;
} catch (UnknownHostException e) { // } catch (UnknownHostException e) {
e.printStackTrace(); // e.printStackTrace();
return false; // return false;
} // }
} // }
//
/** // /**
* 将IP地址转换为整数 // * 将IP地址转换为整数
* // *
* @param inetAddress IP地址对象 // * @param inetAddress IP地址对象
* @return 转换后的长整数 // * @return 转换后的长整数
*/ // */
private static long ipToLong(InetAddress inetAddress) { // private static long ipToLong(InetAddress inetAddress) {
byte[] octets = inetAddress.getAddress(); // byte[] octets = inetAddress.getAddress();
long result = 0; // long result = 0;
for (byte octet : octets) { // for (byte octet : octets) {
result = (result << 8) | (octet & 0xFF); // result = (result << 8) | (octet & 0xFF);
} // }
return result; // return result;
} // }
public static boolean isCurrentTimeInRange(String startDateTime, String endDateTime) { // public static boolean isCurrentTimeInRange(String startDateTime, String endDateTime) {
// 定义日期时间格式 // // 定义日期时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//
// 将字符串转换为 LocalDateTime // // 将字符串转换为 LocalDateTime
LocalDateTime start = LocalDateTime.parse(startDateTime, formatter); // LocalDateTime start = LocalDateTime.parse(startDateTime, formatter);
LocalDateTime end = LocalDateTime.parse(endDateTime, formatter); // LocalDateTime end = LocalDateTime.parse(endDateTime, formatter);
//
// 获取当前日期和时间 // // 获取当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now(); // LocalDateTime currentDateTime = LocalDateTime.now();
//
// 检查当前日期和时间是否在指定的范围内 // // 检查当前日期和时间是否在指定的范围内
return !currentDateTime.isBefore(start) && !currentDateTime.isAfter(end); // return !currentDateTime.isBefore(start) && !currentDateTime.isAfter(end);
} // }
//
/** // /**
* Get the order value of this object. // * Get the order value of this object.
* <p>Higher values are interpreted as lower priority. As a consequence, // * <p>Higher values are interpreted as lower priority. As a consequence,
* the object with the lowest value has the highest priority (somewhat // * the object with the lowest value has the highest priority (somewhat
* analogous to Servlet {@code load-on-startup} values). // * analogous to Servlet {@code load-on-startup} values).
* <p>Same order values will result in arbitrary sort positions for the // * <p>Same order values will result in arbitrary sort positions for the
* affected objects. // * affected objects.
* // *
* @return the order value // * @return the order value
* @see #HIGHEST_PRECEDENCE // * @see #HIGHEST_PRECEDENCE
* @see #LOWEST_PRECEDENCE // * @see #LOWEST_PRECEDENCE
*/ // */
@Override // @Override
public int getOrder() { // public int getOrder() {
return 0; // return 0;
} // }
} //}

View File

@ -6,6 +6,7 @@ import com.bonus.common.security.annotation.EnableCustomConfig;
import com.bonus.common.security.annotation.EnableRyFeignClients; import com.bonus.common.security.annotation.EnableRyFeignClients;
import com.bonus.common.swagger.annotation.EnableCustomSwagger2; import com.bonus.common.swagger.annotation.EnableCustomSwagger2;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;
/** /**
* 系统模块 * 系统模块
@ -16,6 +17,7 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@EnableCustomSwagger2 @EnableCustomSwagger2
@EnableRyFeignClients @EnableRyFeignClients
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@EnableScheduling
public class BonusSystemApplication public class BonusSystemApplication
{ {
public static void main(String[] args) public static void main(String[] args)

View File

@ -183,11 +183,12 @@ public class SysLogController extends BaseController {
public R<Map<String,Object>> getLogStatistics(@RequestBody SysLogsVo dto) { public R<Map<String,Object>> getLogStatistics(@RequestBody SysLogsVo dto) {
return service.getLogStatistics(dto); return service.getLogStatistics(dto);
} }
@ApiOperation(value = "查询日志告警")
@PostMapping("logWarn") // @ApiOperation(value = "查询日志告警")
public R<Map<String,Object>> logWarn() { // @PostMapping("logWarn")
return service.logWarn(); // public R<Map<String,Object>> logWarn() {
} // return service.logWarn();
// }
} }

View File

@ -59,7 +59,7 @@ public interface ISysLogService {
*日志容量告警 *日志容量告警
* @return * @return
*/ */
R<Map<String, Object>> logWarn( ); void logWarn( );
/** /**
* 保存日志 * 保存日志

View File

@ -16,6 +16,7 @@ import com.bonus.common.core.utils.global.SystemGlobal;
import com.bonus.system.api.domain.SysLogsVo; import com.bonus.system.api.domain.SysLogsVo;
import com.bonus.system.api.model.LoginUser; import com.bonus.system.api.model.LoginUser;
import com.bonus.system.mapper.SysLogMapper; import com.bonus.system.mapper.SysLogMapper;
import com.mysql.cj.xdevapi.Warning;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode; import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -263,38 +264,22 @@ public class SysLogServiceImpl implements ISysLogService {
* @return * @return
*/ */
@Override @Override
public R<Map<String, Object>> logWarn() { public void logWarn() {
Map<String, Object> map=Maps.newHashMap(); try {
try { double bfb=0.9;
double bfb=0.9;
//查询当日的告警
int num =mapper.getErrorLogs();
if(num>0){
map.put("logWarn","1");
map.put("err","您有新的异常告警"+num +",请及时处理!");
}else{
map.put("logWarn","0");
}
String rl=mapper.getLogsRl(); String rl=mapper.getLogsRl();
String city=mapper.getLogsSet(); String city=mapper.getLogsSet();
Double d=Double.parseDouble(rl); Double d=Double.parseDouble(rl);
Double max=Double.parseDouble(city)*bfb; Double max=Double.parseDouble(city)*bfb;
if(d>=max){ if(d>=max){
map.put("warnType","1"); String warningEvent = "日志容量告警,当日日志内存为" +d+ "MB,日志内存超过总内存的90%,请及时处理!";
map.put("warnError","日志容量告警,当日日志内存为"+d+"MB,日志内存超过总内存的90%,请及时处理!"); eventPublisher.publishEvent(new WaringLogEvent(new SysWarning("0",warningEvent,"",null,null)));
}else {
map.put("warnType","0");
} }
return R.ok(map); }catch (Exception e){
}catch (Exception e){ log.error(e.toString(),e);
map.put("logWarn","0"); }
map.put("warnType","0");
log.error(e.toString(),e);
}
return R.ok(map);
} }
@Override @Override
@Async @Async
public void handleWarningLog(){ public void handleWarningLog(){

View File

@ -104,7 +104,7 @@ public class SysOperLogServiceImpl implements ISysOperLogService
public int addLogs(SysLogsVo sysLogsVo) { public int addLogs(SysLogsVo sysLogsVo) {
if (sysLogsVo.getLogType() == 2) { if (sysLogsVo.getLogType() == 2) {
sysLogsVo.setWarningStatus("0"); sysLogsVo.setWarningStatus("0");
eventPublisher.publishEvent(new WaringLogEvent(new SysWarning(sysLogsVo.getLogId(), sysLogsVo.getOperType(), sysLogsVo.getIp(), sysLogsVo.getOperaUserName(), sysLogsVo.getOperTime()))); eventPublisher.publishEvent(new WaringLogEvent(new SysWarning(sysLogsVo.getLogId(), sysLogsVo.getErrType(), sysLogsVo.getIp(), sysLogsVo.getOperaUserName(), sysLogsVo.getOperTime())));
} }
return operLogMapper.addLogs(sysLogsVo); return operLogMapper.addLogs(sysLogsVo);
} }

View File

@ -0,0 +1,31 @@
package com.bonus.system.warning;
import com.bonus.system.service.ISysLogService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class ScheduledTasks {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Resource(name = "ISysLogService")
private ISysLogService service;
// 每5秒执行一次
@Scheduled(fixedRate = 300000)
public void taskWithFixedRate() {
service.logWarn();
System.out.println("数据库容量固定速率任务执行时间:" + LocalDateTime.now().format(formatter));
}
// // 每天凌晨1点执行
// @Scheduled(cron = "0 */5 * * * ?")
// public void taskWithCron() {
// System.out.println("定时任务执行时间:" + LocalDateTime.now().format(formatter));
// }
}

View File

@ -12,6 +12,6 @@ import org.springframework.web.socket.config.annotation.*;
public class WebSocketConfig implements WebSocketConfigurer { public class WebSocketConfig implements WebSocketConfigurer {
@Override @Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*"); registry.addHandler(new WebSocketHandler(), "/alert").setAllowedOrigins("*");
} }
} }

View File

@ -6,6 +6,11 @@ spring:
profiles: profiles:
# 环境配置 # 环境配置
active: dev active: dev
task:
scheduling:
pool:
size: 1 # 定时任务线程池大小
thread-name-prefix: scheduled-task- # 定时任务线程名称前缀
#加密组件 #加密组件
jasypt: jasypt:

View File

@ -64,12 +64,12 @@ create table sys_user (
login_type varchar(100) default null comment '登录类型', login_type varchar(100) default null comment '登录类型',
approval_status char(1) default '1' comment '审批状态0未审批1已审批', approval_status char(1) default '1' comment '审批状态0未审批1已审批',
is_permanent char(1) default '1' comment '长期和临时用户标识0临时用户1长期用户', is_permanent char(1) default '1' comment '长期和临时用户标识0临时用户1长期用户',
is_built_in char(1) default '0' comment '是否内置用户0内置用户1内置用户', is_built_in char(1) default '0' comment '是否内置用户0内置用户1内置用户',
primary key (user_id) primary key (user_id)
) engine=innodb auto_increment=100 comment = '用户信息表'; ) engine=innodb auto_increment=100 comment = '用户信息表';
ALTER TABLE `bns-cloud`.sys_user ADD is_permanent char(1) DEFAULT '1' NULL COMMENT '长期和临时用户标识0临时用户1长期用户'; ALTER TABLE `bns-cloud`.sys_user ADD is_permanent char(1) DEFAULT '1' NULL COMMENT '长期和临时用户标识0临时用户1长期用户';
ALTER TABLE `bns-cloud`.sys_user ADD is_built_in char(1) DEFAULT '0' NULL COMMENT '是否内置用户0内置用户1内置用户'; ALTER TABLE `bns-cloud`.sys_user ADD is_built_in char(1) DEFAULT '1' NULL COMMENT '是否内置用户0内置用户1内置用户';
ALTER TABLE `bns-cloud`.sys_dept MODIFY COLUMN phone varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '联系电话'; ALTER TABLE `bns-cloud`.sys_dept MODIFY COLUMN phone varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '联系电话';
ALTER TABLE `bns-cloud`.sys_dept MODIFY COLUMN email varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '邮箱'; ALTER TABLE `bns-cloud`.sys_dept MODIFY COLUMN email varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '邮箱';
@ -80,8 +80,8 @@ ALTER TABLE `bns-cloud`.sys_user MODIFY COLUMN phonenumber varchar(255) CHARACTE
-- ---------------------------- -- ----------------------------
-- 初始化-用户信息表数据 -- 初始化-用户信息表数据
-- ---------------------------- -- ----------------------------
insert into sys_user values(1, 103, 'bonus', '博诺思', '00', '38fb2b6be1e8b9024b0140fc673f0ed245b6b82ae6464387bbe806dc68e66fa8', '4eb762402e0ce5ef9d0028e2d622c53bc8ea1d7680ea4416975e4cc23b4ef7f0', '1', '', '$2a$10$5azz92OgGRyRUETz/ZJeZu1exkggPYUDRssvreywTjKk.0Pmn2Q16', '0', '0', '127.0.0.1', sysdate(), 'admin', sysdate(), '', null,sysdate(), '系统管理员','0','1','1'); insert into sys_user values(1, 103, 'bonus', '博诺思', '00', '38fb2b6be1e8b9024b0140fc673f0ed245b6b82ae6464387bbe806dc68e66fa8', '4eb762402e0ce5ef9d0028e2d622c53bc8ea1d7680ea4416975e4cc23b4ef7f0', '1', '', '$2a$10$5azz92OgGRyRUETz/ZJeZu1exkggPYUDRssvreywTjKk.0Pmn2Q16', '0', '0', '127.0.0.1', sysdate(), 'admin', sysdate(), '', null,sysdate(), '系统管理员','0','0','1');
insert into sys_user values(2, 103, 'audit', '博诺思', '00', '38fb2b6be1e8b9024b0140fc673f0ed245b6b82ae6464387bbe806dc68e66fa8', '4eb762402e0ce5ef9d0028e2d622c53bc8ea1d7680ea4416975e4cc23b4ef7f0', '1', '', '$2a$10$5azz92OgGRyRUETz/ZJeZu1exkggPYUDRssvreywTjKk.0Pmn2Q16', '0', '0', '127.0.0.1', sysdate(), 'admin', sysdate(), '', null,sysdate(),'审计管理员','0','1','1'); insert into sys_user values(2, 103, 'audit', '博诺思', '00', '38fb2b6be1e8b9024b0140fc673f0ed245b6b82ae6464387bbe806dc68e66fa8', '4eb762402e0ce5ef9d0028e2d622c53bc8ea1d7680ea4416975e4cc23b4ef7f0', '1', '', '$2a$10$5azz92OgGRyRUETz/ZJeZu1exkggPYUDRssvreywTjKk.0Pmn2Q16', '0', '0', '127.0.0.1', sysdate(), 'admin', sysdate(), '', null,sysdate(),'审计管理员','0','0','1');
-- ---------------------------- -- ----------------------------
@ -131,12 +131,12 @@ create table sys_role (
update_by varchar(64) default '' comment '更新者', update_by varchar(64) default '' comment '更新者',
update_time datetime comment '更新时间', update_time datetime comment '更新时间',
remark varchar(500) default null comment '备注', remark varchar(500) default null comment '备注',
is_built_in char(1) default '0' comment '是否内置0内置1内置', is_built_in char(1) default '0' comment '是否内置0内置1内置',
primary key (role_id) primary key (role_id)
) engine=innodb auto_increment=100 comment = '角色信息表'; ) engine=innodb auto_increment=100 comment = '角色信息表';
ALTER TABLE `bns-cloud`.sys_role ADD is_built_in char(1) DEFAULT '0' NULL COMMENT '是否内置0非内置角色1内置角色'; ALTER TABLE `bns-cloud`.sys_role ADD is_built_in char(1) DEFAULT '1' NULL COMMENT '是否内置0非内置角色1内置角色';
---------------------- ----------------------
-- 初始化-角色信息表数据 -- 初始化-角色信息表数据