添加越权处理

This commit is contained in:
haozq 2024-04-16 15:26:55 +08:00
parent 22f90d8cea
commit b09b12eed1
14 changed files with 286 additions and 27 deletions

View File

@ -70,13 +70,14 @@ public class TokenController {
@PostMapping("logout")
public Result<?> loginOut(HttpServletRequest request) {
try{
long startTime = System.currentTimeMillis();
String jwtToken = SecurityUtils.getToken(request);
if(StringHelper.isNotEmpty(jwtToken) && !NULL_STRING.equals(jwtToken)){
Claims claims = JwtUtils.parseToken(jwtToken);
Integer userId = (Integer) claims.get(SecurityConstants.DETAILS_USER_ID);
String iscUser = (String) claims.get(SecurityConstants.DETAILS_ISC_USER_ID);
String userName = (String) claims.get(SecurityConstants.DETAILS_USERNAME);
recordLogService.recordLogininfor(userName, Long.valueOf(userId + ""), "登出", "用户退出登录", 2,1,"");
recordLogService.recordLogininfor(userName, Long.valueOf(userId + ""), "登出", "用户退出登录", 2,1,"",startTime);
redisUtil.delete("token:" + jwtToken);
redisUtil.delete("userId:" + userId);
redisUtil.delete("ISCUserId:" + iscUser);

View File

@ -5,7 +5,10 @@ import com.securitycontrol.common.core.constant.SecurityConstants;
import com.securitycontrol.common.core.domain.Result;
import com.securitycontrol.common.core.enums.UserStatus;
import com.securitycontrol.common.core.exception.ServiceException;
import com.securitycontrol.common.core.utils.ServletUtils;
import com.securitycontrol.common.core.utils.StringUtils;
import com.securitycontrol.common.core.utils.ip.IpUtils;
import com.securitycontrol.common.redis.service.RedisService;
import com.securitycontrol.system.api.RemoteUserService;
import com.securitycontrol.system.api.domain.SysUser;
import com.securitycontrol.system.api.domain.decision.SysMenu;
@ -36,55 +39,61 @@ public class SysLoginService
@Autowired
private SysRecordLogService recordLogService;
@Resource
private RedisService redisUtil;
public int times =5*60;
/**
* 登录
*/
public LoginUser login(String username, String password,String loginType,List<SysMenu> list)
{
public LoginUser login(String username, String password,String loginType,List<SysMenu> list) {
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
long startTime = System.currentTimeMillis();
// 用户名或密码为空 错误
if (StringUtils.isAnyBlank(username, password))
{
recordLogService.recordLogininfor(username,null,"用户登录","用户/密码不能为空",1,0,"username="+username);
recordLogService.recordLogininfor(username,null,"用户登录","用户/密码不能为空",1,0,"username="+username,startTime);
throw new ServiceException("用户/密码不能为空",201);
}
// 查询用户信息
Result<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
{
recordLogService.recordLogininfor(username,null,"用户登录","登录用户:" + username + " 不存在",1,0,"username="+username);
recordLogService.recordLogininfor(username,null,"用户登录","登录用户:" + username + " 不存在",1,0,"username="+username,startTime);
throw new ServiceException("登录用户:" + username + " 不存在",201);
}
if (Result.FAIL == userResult.getCode())
{
recordLogService.recordLogininfor(username,null,"用户登录",userResult.getMsg(),1,0,"username="+username);
recordLogService.recordLogininfor(username,null,"用户登录",userResult.getMsg(),1,0,"username="+username,startTime);
throw new ServiceException(userResult.getMsg());
}
LoginUser userInfo = userResult.getData();
SysUser user = userResult.getData().getSysUser();
if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
recordLogService.recordLogininfor(username,null,"用户登录","对不起,您的账号:" + username + " 已被删除",1,0,"username="+username);
recordLogService.recordLogininfor(username,null,"用户登录","对不起,您的账号:" + username + " 已被删除",1,0,"username="+username,startTime);
throw new ServiceException("对不起,您的账号:" + username + " 已被删除",201);
}
if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
{
recordLogService.recordLogininfor(username,null,"用户登录","对不起,您的账号:" + username + " 已锁定",1,0,"username="+username);
recordLogService.recordLogininfor(username,null,"用户登录","对不起,您的账号:" + username + " 已锁定",1,0,"username="+username,startTime);
throw new ServiceException("对不起,您的账号:" + username + " 已锁定",201);
}
if(StringUtils.isEmpty(loginType) && !user.getLoginType().contains(Constant.BACK_LOGIN)){
recordLogService.recordLogininfor(username,null,"用户登录","账号无权限",1,0,"username="+username);
recordLogService.recordLogininfor(username,null,"用户登录","账号无权限",1,0,"username="+username,startTime);
throw new ServiceException("对不起,您的账号:" + username + " 无登录后台权限",201);
}
if(StringUtils.isNotEmpty(loginType) && !user.getLoginType().contains(Constant.SC_SCREEN)){
recordLogService.recordLogininfor(username,null,"省侧大屏用户登录","账号无权限",1,0,"username="+username);
recordLogService.recordLogininfor(username,null,"省侧大屏用户登录","账号无权限",1,0,"username="+username,startTime);
throw new ServiceException("对不起,您的账号:" + username + " 无登录省侧大屏权限",201);
}
if(StringUtils.isEmpty(loginType) && !user.getLoginType().contains(Constant.SG_SCREEN)){
recordLogService.recordLogininfor(username,null,"施工大屏用户登录","账号无权限",1,0,"username="+username);
recordLogService.recordLogininfor(username,null,"施工大屏用户登录","账号无权限",1,0,"username="+username,startTime);
throw new ServiceException("对不起,您的账号:" + username + " 无登录施工大屏权限",201);
}
if(StringUtils.isEmpty(loginType) && !user.getLoginType().contains(Constant.APP_LOGIN)){
recordLogService.recordLogininfor(username,null,"APP用户登录","账号无权限",1,0,"username="+username);
recordLogService.recordLogininfor(username,null,"APP用户登录","账号无权限",1,0,"username="+username,startTime);
throw new ServiceException("对不起,您的账号:" + username + " 无登录APP权限",201);
}
passwordService.validate(user, password);
@ -92,7 +101,13 @@ public class SysLoginService
list = handleMenuList(menu.getData(),loginType);
user.setJumpType(loginType);
userInfo.getSysUser().setMenus(list);
recordLogService.recordLogininfor(username,user.getUserId(), "用户登录", "登录成功",1,1,"username="+username);
String hisIp=redisUtil.getVal(username);
if(ip.equals(hisIp)){
redisUtil.set("username",ip,times);
}else{
recordLogService.errorLogs(username,null,"用户登录","IP异常",1,0,"username="+username,startTime);
}
recordLogService.recordLogininfor(username,user.getUserId(), "用户登录", "登录成功",1,1,"username="+username,startTime);
remoteUserService.updateUserLogin(user.getUserId(),SecurityConstants.INNER);
return userInfo;
}

View File

@ -37,7 +37,9 @@ public class SysRecordLogService {
* @param operaType 1.登录 2.登出
* @return
*/
public void recordLogininfor(String username, Long userId, String model, String detail, int operaType,int result,String params) {
public void recordLogininfor(String username, Long userId, String model, String detail, int operaType,int result,String params,long startTime) {
long endTime = System.currentTimeMillis();
SysLog sysLog = new SysLog();
String id = IdUtils.getuid();
sysLog.setLogId(id);
@ -51,6 +53,9 @@ public class SysRecordLogService {
if(userId != null){
sysLog.setUserId(userId);
}
sysLog.setTitle("用户登录");
long times=endTime-startTime;
sysLog.setTimes(times+"");
sysLog.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
sysLog.setModel(model);
sysLog.setOperType(model);
@ -63,4 +68,49 @@ public class SysRecordLogService {
sysLog.setLogType(0);
remoteLogService.saveSysLog(sysLog, SecurityConstants.INNER);
}
/**
* 记录登录信息
*
* @param username 用户名
* @param model 操作模块
* @param detail 详情
* @param operaType 1.登录 2.登出
* @return
*/
public void errorLogs(String username, Long userId, String model, String detail, int operaType,int result,String params,long startTime) {
SysLog sysLog = new SysLog();
long endTime = System.currentTimeMillis();
sysLog.setLogType(2);
sysLog.setOperaUserName(username);
LoginUser loginUser = SecurityUtils.getLoginUser();
if (null != loginUser && null != loginUser.getSysUser()) {
SysUser sysUser = loginUser.getSysUser();
sysLog.setUserId(sysUser.getUserId());
}
String id = IdUtils.getuid();
sysLog.setLogId(id);
if(userId != null){
sysLog.setUserId(userId);
}
sysLog.setTitle("用户登录");
long times=endTime-startTime;
sysLog.setTimes(times+"");
sysLog.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
sysLog.setModel(model);
sysLog.setOperType(model);
sysLog.setOperateDetail("用户登录系统");
sysLog.setMethod("com.securitycontrol.auth.controller.login()" );
sysLog.setResult(result);
sysLog.setOperUri("/auth/login");
sysLog.setFailureReason(detail);
sysLog.setParams(params);
sysLog.setGrade("");
sysLog.setErrType("IP异常");
sysLog.setFailureReason("IP异常");
sysLog.setOperTime(DateTimeHelper.getNowTime());
remoteLogService.saveSysLog(sysLog, SecurityConstants.INNER);
}
}

View File

@ -44,6 +44,8 @@ public class CommonConstant {
public static final String MESSAGE = "message";
public static final String MSG = "msg";
public static final String UTF8 = "UTF-8";
public static final String RSA_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDFJIl4il6nDBlF/3byWB/KXRqfEXkviz7ZvO7TU7JBfh7sFqfgLtJFDSA33+qTHOtYTCjCrwl6oWWX7Aff39HiFW1IBnhKjYdSK5/8ruQY+Y2xbpBMgslA0m2euOv3XPJUXWh0JGBqPllgzvtbtUA1iBELAHVYBACuQPYP2VcPeQIDAQAB";
@ -62,7 +64,7 @@ public class CommonConstant {
response.getHeaders().add(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON_UTF8_VALUE);
JSONObject jsonObject = new JSONObject();
jsonObject.put(CODE, code);
jsonObject.put(MESSAGE, message);
jsonObject.put(MSG, message);
DataBuffer bodyDataBuffer = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
return response.writeWith(Mono.just(bodyDataBuffer));
}

View File

@ -49,6 +49,11 @@ public class OperLogAspect {
private static String[] constantArr;
private static String SYSTEM_LOG="系统日志";
private static String YW_LOG="业务日志";
static {
constantArr = new String[]{"业务日志,系统日志,异常日志"};
}
@ -142,7 +147,6 @@ public class OperLogAspect {
if (e != null) {
//失败
sysLog.setResult(BusinessStatus.FAIL.ordinal());
System.err.println(e.getClass().getName());
sysLog.setFailureReason(StringUtils.substring(e.getMessage(), 0, 2000));
} else{
if(jsonObject!=null){
@ -154,8 +158,14 @@ public class OperLogAspect {
}else {
sysLog.setResult(0);
}
sysLog.setFailureReason(msg);
if(StringHelper.isEmpty(msg)){
sysLog.setFailureReason("查询成功");
}else{
sysLog.setFailureReason(msg);
}
}
}else {
sysLog.setFailureReason("查询成功");
}
}
asyncLogService.addSaveSysLog(sysLog);
@ -182,9 +192,9 @@ public class OperLogAspect {
sysLog.setOperType(log.grade().getInfo());
sysLog.setOperateDetail(log.details());
sysLog.setOperTime(DateTimeHelper.getNowTime());
if(log.type().equals(constantArr[0])){
if(log.type().equals(YW_LOG)){
sysLog.setLogType(1);
}else if(log.type().equals(constantArr[1])){
}else if(log.type().equals(SYSTEM_LOG)){
sysLog.setLogType(0);
}else {
sysLog.setLogType(1);

View File

@ -321,6 +321,23 @@ public class RedisService
public Object get(String key){
return key==null?null:redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存获取
* @param key
* @return
*/
public String getVal(String key){
try{
Object object=redisTemplate.opsForValue().get(key);
if(object!=null){
return (String) object;
}
}catch (Exception e){
log.error(e.toString());
}
return "";
}
/**
* 获取指定key的缓存

View File

@ -53,6 +53,8 @@ public class ParamSecureHandler implements AsyncHandlerInterceptor {
*/
public static String WHITE_URL="/sys/select/";
public static String[] WHITE_URLS= new String[]{"/sys/sysLog/addLogs"};
private final String whiteURL = "http://127.0.0.1:18080/";
@ -147,9 +149,13 @@ public class ParamSecureHandler implements AsyncHandlerInterceptor {
returnJson(response,"请求参数丢失",500);
return false;
}*/
if (!checkIsYq(request, requestWrapper)) {
returnJson(response, "越权访问,请检查用户权限", 500);
return false;
try{
if (!checkIsYq(request, requestWrapper)) {
returnJson(response, "越权访问,接口未授权", 500);
return false;
}
}catch (Exception e){
returnJson(response, "令牌不能为空", 401);
}
return true;
}
@ -174,6 +180,9 @@ public class ParamSecureHandler implements AsyncHandlerInterceptor {
*/
private boolean checkIsYq(HttpServletRequest request, XssRequestWrapper requestWrapper) throws Exception {
String requestUri = request.getRequestURI();
if(Arrays.binarySearch(WHITE_URLS,requestUri)>0){
return false;
}
String[] urls=requestUri.split(ur);
if(urls.length>4){
requestUri=ur+urls[1]+ur+urls[2]+ur+urls[3];
@ -200,7 +209,7 @@ public class ParamSecureHandler implements AsyncHandlerInterceptor {
}
if (!result) {
addExceedsAccessLog(requestUri, token);
// return false;
return false;
}
return true;
}
@ -253,7 +262,7 @@ public class ParamSecureHandler implements AsyncHandlerInterceptor {
sysLog.setOperType("异常日志");
sysLog.setLogType(2);
sysLog.setOperUri(url);
sysLog.setFailureReason("用户越权访问地址");
sysLog.setFailureReason("接口未授权");
sysLog.setGrade("");
sysLog.setErrType("越权访问");
sysLog.setResult(0);

View File

@ -96,7 +96,7 @@ class RsaDecryptResponseGatewayFilterFactory extends AbstractGatewayFilterFactor
decrypBytes = decryptMsg.getBytes();
} catch (Exception e) {
log.error("数据 解密失败:{}", e);
return CommonConstant.buildResponse(exchange, HttpStatus.BAD_REQUEST.value(), "数据解密失败");
return CommonConstant.buildResponse(exchange, 201, "请求参数异常!");
}
// 根据解密后的参数重新构建请求
DataBufferFactory dataBufferFactory = exchange.getResponse().bufferFactory();

View File

@ -50,7 +50,6 @@ public class XcIndexServiceImpl implements XcIndexService {
public AjaxResult getProDetails(ScreenParamDto dto) {
Map<String ,Object> map= Maps.newHashMap();
try{
System.err.println(dto.getBidCode());
ProVo proVo=mapper.getProDetails(dto.getBidCode());
Result<List<TbSourceFile>> result=remoteSourceService.getSourceFile(proVo.getProId(), SystemGlobal.PRO_IMAGE, SecurityConstants.INNER);
if(result.getCode()==SystemGlobal.SUCCESS_CODE){

View File

@ -46,12 +46,20 @@ public class SysLogController extends BaseController {
@Value("${sql.filePath}")
private String filePath;
@ApiOperation(value = "保存系统日志")
@PostMapping("saveLogs")
public AjaxResult saveLogs(@RequestBody SysLog sysLog) {
return service.saveLogs(sysLog);
}
@PostMapping("addLogs")
public void addLogs(@RequestBody SysLog sysLog,HttpServletRequest request) {
service.addLogs(sysLog,request);
}
@Autowired
private ExportSqlService exportSqlService;
@ -164,6 +172,11 @@ public class SysLogController extends BaseController {
public Result<Map<String,Object>> getLogStatistics(@RequestBody SysLog dto) {
return service.getLogStatistics(dto);
}
@ApiOperation(value = "查询日志溶剂")
@PostMapping("logWarn")
public Result<Map<String,Object>> logWarn() {
return service.logWarn();
}
}

View File

@ -72,4 +72,30 @@ public interface ISysLogMapper {
* @return
*/
SysLog getModule(@Param("module") String operUri);
/**
* 查询当日异常告警数量
* @return
*/
int getErrorLogs();
/**
* 查询日志容量
* @return
*/
String getLogsRl();
/**
* 查询全部日志细腻系
* @param dto
* @return
*/
List<SysLog> getAllLogs(SysLog dto);
/**
* 查询
* @param sysLog
* @return
*/
String getModuleName(SysLog sysLog);
}

View File

@ -4,6 +4,7 @@ import com.securitycontrol.common.core.domain.Result;
import com.securitycontrol.common.core.web.domain.AjaxResult;
import com.securitycontrol.system.api.domain.SysLog;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
@ -51,4 +52,18 @@ public interface ISysLogService {
* @return
*/
Result<Map<String, Object>> getLogStatistics(SysLog dto);
/**
*日志容量告警
* @return
*/
Result<Map<String, Object>> logWarn( );
/**
* 保存日志
* @param sysLog
* @param request
* @return
*/
void addLogs(SysLog sysLog, HttpServletRequest request);
}

View File

@ -5,7 +5,9 @@ import com.securitycontrol.common.core.domain.Result;
import com.securitycontrol.common.core.utils.aes.DateTimeHelper;
import com.securitycontrol.common.core.utils.aes.ListHelper;
import com.securitycontrol.common.core.utils.aes.StringHelper;
import com.securitycontrol.common.core.utils.ip.IpUtils;
import com.securitycontrol.common.core.web.domain.AjaxResult;
import com.securitycontrol.common.security.utils.SecurityUtils;
import com.securitycontrol.entity.system.SystemGlobal;
import com.securitycontrol.system.api.domain.SysLog;
import com.securitycontrol.system.base.mapper.ISysLogMapper;
@ -14,8 +16,11 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import sun.net.util.IPAddressUtil;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@ -63,6 +68,29 @@ public class SysLogServiceImpl implements ISysLogService {
return null;
}
@Override
public void addLogs(SysLog sysLog, HttpServletRequest request) {
try{
sysLog.setFruit("失败");
sysLog.setIp(IpUtils.getIpAddr(request));
sysLog.setGrade("");
sysLog.setErrType("越权访问");
sysLog.setFailureReason("页面未授权");
sysLog.setOperType("查询");
sysLog.setOperateDetail("查看页面");
String module=mapper.getModuleName(sysLog);
sysLog.setLogType(1);
sysLog.setResult(0);
sysLog.setOperTime(DateTimeHelper.getNowTime());
sysLog.setModel(module);
sysLog.setUserId(SecurityUtils.getUserId());
sysLog.setOperaUserName(SecurityUtils.getUsername());
mapper.saveLogs(sysLog);
}catch (Exception e){
log.error(e.toString(),e);
}
}
@Override
public List<SysLog> getSystemLogs(SysLog dto) {
try{
@ -136,6 +164,8 @@ public class SysLogServiceImpl implements ISysLogService {
@Override
public Result<Map<String, Object>> getLogStatistics(SysLog dto) {
Map<String,Object> map= Maps.newHashMap();
String SUCCESS="成功";
try{
if (StringHelper.isNotEmpty(dto.getOperTime())) {
dto.setStartTime(dto.getOperTime().split(" - ")[0].trim());
@ -143,6 +173,17 @@ public class SysLogServiceImpl implements ISysLogService {
}else {
dto.setStartTime(DateTimeHelper.getNowDay());
dto.setEndTime(DateTimeHelper.getNowDay());
}
List<SysLog> all=mapper.getAllLogs(dto);
if(ListHelper.isNotEmpty(all)){
int allNum= all.stream().mapToInt(SysLog::getNum).sum();
all.forEach(vo->{
if(SUCCESS.equals(vo.getResult())){
map.put("sNum",vo.getNum());
}else {
map.put("eNum",vo.getNum());
}
});
}
if (SystemGlobal.LOG_TYPE.equals(dto.getType())){
List<Integer> type=new ArrayList<>();
@ -175,7 +216,41 @@ public class SysLogServiceImpl implements ISysLogService {
return Result.ok(map);
}
/**
* 日志容量告警
* @return
*/
@Override
public Result<Map<String, Object>> logWarn() {
Map<String, Object> map=Maps.newHashMap();
try {
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 city=mapper.getLogsSet();
Double d=Double.parseDouble(rl);
Double max=Double.parseDouble(city)*bfb;
if(d>=max){
map.put("warnType","1");
map.put("warnError","日志容量告警,当日日志内存为"+d+"MB,日志内存超过总内存的90%,请及时处理!");
}else {
map.put("warnType","0");
}
return Result.ok(map);
}catch (Exception e){
map.put("logWarn","0");
map.put("warnType","0");
log.error(e.toString(),e);
}
return Result.ok(map);
}

View File

@ -132,4 +132,31 @@
where sm3.menu_auth=#{module}
limit 1
</select>
<select id="getErrorLogs" resultType="java.lang.Integer">
select count(1)
from sys_logs
where log_type=2
and DATE_FORMAT(oper_time,'%Y-%m-%d')=CURRENT_DATE
</select>
<select id="getLogsRl" resultType="java.lang.String">
SELECT
round(((data_length + index_length) / 1024 / 1024), 2) AS 'Size in MB'
FROM information_schema.TABLES
WHERE table_schema = 'jj_zhgd' AND table_name = 'sys_logs'
</select>
<select id="getAllLogs" resultType="com.securitycontrol.system.api.domain.SysLog">
select count(1) num,result
from sys_logs
where oper_time BETWEEN CONCAT(#{startTime}, ' 00:00:00') AND CONCAT(#{endTime},' 23:59:59')
GROUP BY result
</select>
<select id="getModuleName" resultType="java.lang.String">
select CONCAT(IFNULL(sm.menu_name,''),'->',IFNULL(sm2.menu_name,'')) module
from sys_menu sm
left join sys_menu sm2 on sm2.p_id=sm.menu_id and sm2.menu_type=1
where sm2.menu_url=#{operUri}
limit 1
</select>
</mapper>