修改类名

This commit is contained in:
zhuoda 2021-09-23 20:47:57 +08:00
commit 12a4aae299
17 changed files with 208 additions and 179 deletions

View File

@ -1,4 +1,4 @@
package net.lab1024.smartadmin.service.handler;
package net.lab1024.smartadmin.service.common.security;
import com.alibaba.fastjson.JSONObject;
import net.lab1024.smartadmin.service.common.codeconst.LoginResponseCodeConst;
@ -15,8 +15,7 @@ import java.io.IOException;
/**
* 认证失败处理
*/
@Component
public class AuthenticationFailHandler implements AuthenticationEntryPoint {
public class SmartSecurityAuthenticationFailHandler implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {

View File

@ -4,6 +4,7 @@ import net.lab1024.smartadmin.service.common.anno.NoValidPrivilege;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.prepost.*;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@ -79,7 +80,10 @@ public class SmartSecurityMetadataSource extends PrePostAnnotationSecurityMetada
String uriPrefix = SmartSecurityUrl.getUriPrefix(method);
List<String> annotationValueList = SmartSecurityUrl.getAnnotationValueList(method, uriPrefix);
//判断是否被忽略
if (this.contain(noValidUrlList, annotationValueList)) {
AntPathMatcher antPathMatcher = new AntPathMatcher();
antPathMatcher.setCaseSensitive(false);
antPathMatcher.setTrimTokens(true);
if (this.contain(antPathMatcher, noValidUrlList, annotationValueList)) {
return super.getAttributes(method, targetClass);
}
ArrayList<ConfigAttribute> configAttributes = new ArrayList(1);
@ -96,13 +100,13 @@ public class SmartSecurityMetadataSource extends PrePostAnnotationSecurityMetada
return configAttributes;
}
public Boolean contain(List<String> ignores, List<String> valueList) {
public Boolean contain(AntPathMatcher antPathMatcher, List<String> ignores, List<String> valueList) {
if (CollectionUtils.isEmpty(ignores)) {
return false;
}
for (String ignoreUrl : ignores) {
for (String uri : valueList) {
if (uri.contains(ignoreUrl)) {
if (antPathMatcher.match(ignoreUrl, uri)) {
return true;
}
}

View File

@ -2,6 +2,7 @@ package net.lab1024.smartadmin.service.common.security;
import com.google.common.collect.Lists;
import net.lab1024.smartadmin.service.common.anno.NoNeedLogin;
import net.lab1024.smartadmin.service.common.constant.CommonConst;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
@ -23,7 +24,7 @@ public class SmartSecurityUrlMatchers {
/**
* 匿名访问URL
*/
private List<String> PERMIT_URL;
private List<String> ANONYMOUS_URL;
/**
* 忽略的URL(注意加入忽略的URL无法进入Security filter)
@ -41,6 +42,7 @@ public class SmartSecurityUrlMatchers {
IGNORE_URL.add("/swagger-resources/**");
IGNORE_URL.add("/webjars/**");
IGNORE_URL.add("/*/api-docs");
IGNORE_URL.add(CommonConst.ApiUrl.API_PREFIX_SUPPORT +"/**");
AUTHENTICATED_URL = new ArrayList<>();
AUTHENTICATED_URL.add("/admin/**");
@ -51,7 +53,7 @@ public class SmartSecurityUrlMatchers {
* @param scanPath 需要扫描的类路径
*/
public SmartSecurityUrlMatchers(String scanPath){
this.PERMIT_URL = this.initAnonymousUrlList(scanPath);
this.ANONYMOUS_URL = this.initAnonymousUrlList(scanPath);
}
/**
@ -62,10 +64,18 @@ public class SmartSecurityUrlMatchers {
return IGNORE_URL;
}
public List<String> getPermitUrlList() {
return PERMIT_URL;
/**
* 获取需要匿名访问的url集合
* @return
*/
public List<String> getAnonymousUrlList() {
return ANONYMOUS_URL;
}
/**
* 获取需要认证的url集合
* @return
*/
public List<String> getAuthenticatedUrlList() {
return AUTHENTICATED_URL;
}
@ -77,20 +87,32 @@ public class SmartSecurityUrlMatchers {
public List<String> getNoValidUrlList() {
List<String> noValidUrl = Lists.newArrayList();
noValidUrl.addAll(IGNORE_URL);
noValidUrl.addAll(PERMIT_URL);
noValidUrl.addAll(ANONYMOUS_URL);
return noValidUrl;
}
/**
* 获取需要忽略的url集合
* @return
*/
public String [] getIgnoreUrlArray() {
String [] ignoreUrlArray = IGNORE_URL.toArray(new String[IGNORE_URL.size()]);
return ignoreUrlArray;
}
public String [] getPermitUrlArray() {
String [] anonymousUrlArray = PERMIT_URL.toArray(new String[PERMIT_URL.size()]);
/**
* 获取需要匿名访问的url集合
* @return
*/
public String [] getAnonymousUrlArray() {
String [] anonymousUrlArray = ANONYMOUS_URL.toArray(new String[ANONYMOUS_URL.size()]);
return anonymousUrlArray;
}
/**
* 获取需要认证的url集合
* @return
*/
public String [] getAuthenticatedUrlArray() {
String [] anonymousUrlArray = AUTHENTICATED_URL.toArray(new String[AUTHENTICATED_URL.size()]);
return anonymousUrlArray;

View File

@ -2,7 +2,7 @@ package net.lab1024.smartadmin.service.config;
import net.lab1024.smartadmin.service.common.security.SmartSecurityUrlMatchers;
import net.lab1024.smartadmin.service.filter.SmartSecurityTokenFilter;
import net.lab1024.smartadmin.service.handler.AuthenticationFailHandler;
import net.lab1024.smartadmin.service.common.security.SmartSecurityAuthenticationFailHandler;
import net.lab1024.smartadmin.service.module.system.login.EmployeeLoginTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@ -31,11 +31,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${access-control-allow-origin}")
private String accessControlAllowOrigin;
/**
* 认证失败处理类
*/
@Autowired
private AuthenticationFailHandler authenticationFailHandler;
/**
* url
*/
@ -74,12 +69,12 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
// CSRF禁用因为不使用session
.csrf().disable()
// 认证失败处理类
.exceptionHandling().authenticationEntryPoint(authenticationFailHandler).and()
.exceptionHandling().authenticationEntryPoint(new SmartSecurityAuthenticationFailHandler()).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 过滤请求
.authorizeRequests();
//可以匿名登录的URL
String [] anonymousUrlArray = smartSecurityUrlMatchers.getPermitUrlArray();
String [] anonymousUrlArray = smartSecurityUrlMatchers.getAnonymousUrlArray();
interceptUrlRegistry.antMatchers(anonymousUrlArray).permitAll();
//登录的URL

View File

@ -1,7 +1,7 @@
package net.lab1024.smartadmin.service.module.support.heartbeat;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.smartadmin.service.module.support.heartbeat.core.HeartBeatRecordDTO;
import net.lab1024.smartadmin.service.module.support.heartbeat.core.HeartBeatRecord;
import net.lab1024.smartadmin.service.module.support.heartbeat.core.IHeartBeatRecordHandler;
import net.lab1024.smartadmin.service.util.SmartBeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
@ -21,11 +21,11 @@ public class HeartBeatRecordHandler implements IHeartBeatRecordHandler {
/**
* 心跳日志处理方法
* @param heartBeatRecordDTO
* @param heartBeatRecord
*/
@Override
public void handler(HeartBeatRecordDTO heartBeatRecordDTO) {
HeartBeatRecordEntity heartBeatRecordEntity = SmartBeanUtil.copy(heartBeatRecordDTO, HeartBeatRecordEntity.class);
public void handler(HeartBeatRecord heartBeatRecord) {
HeartBeatRecordEntity heartBeatRecordEntity = SmartBeanUtil.copy(heartBeatRecord, HeartBeatRecordEntity.class);
HeartBeatRecordEntity heartBeatRecordOld = heartBeatRecordDao.query(heartBeatRecordEntity);
if (heartBeatRecordOld == null) {
heartBeatRecordDao.insertHeartBeat(heartBeatRecordEntity);

View File

@ -1,98 +0,0 @@
package net.lab1024.smartadmin.service.module.support.heartbeat.core;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import net.lab1024.smartadmin.service.util.SmartIPUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* @Description: 心跳服务
* @Author: 1024lab
* @Date: 2018/7/9 16:26
*/
public abstract class AbstractHeartBeatManager {
ScheduledExecutorService executorService;
int threadNum = 1;
/**
* 项目路径
*/
private String projectPath;
/**
* 服务器ip多网卡
*/
private List<String> serverIps;
/**
* 进程号
*/
private Integer processNo;
/**
* 进程开启时间
*/
private Date processStartTime;
HeartBeatLogger logger;
/**
* 初始化
*/
public void init(HeartBeatConfig config, HeartBeatLogger logger){
this.handlerHeartBeat();
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("AbstractHeartBeatCommand-%s").build();
executorService = Executors.newScheduledThreadPool(threadNum, threadFactory);
executorService.scheduleWithFixedDelay(new DoHeartBeat(), config.getDelayHandlerTime(), config.getIntervalTime(), TimeUnit.MILLISECONDS);
}
public void handlerHeartBeat(){
try {
projectPath = HeatBeatRecordHelper.getProjectPath();
serverIps = SmartIPUtil.getLocalHostIPList();
processNo = HeatBeatRecordHelper.getProcessID();
processStartTime = HeatBeatRecordHelper.getStartTime();
}catch (Throwable e){
logger.error("get heart beat info error.", e);
}
}
/**
* 销毁线程池
*/
public void destroy(){
if (executorService != null && !executorService.isShutdown()) {
executorService.shutdown();
executorService = null;
}
}
public class DoHeartBeat implements Runnable{
@Override
public void run() {
try {
HeartBeatRecordDTO heartBeatRecord = new HeartBeatRecordDTO();
heartBeatRecord.setProjectPath(projectPath);
heartBeatRecord.setServerIp(StringUtils.join(serverIps,";"));
heartBeatRecord.setProcessNo(processNo);
heartBeatRecord.setProcessStartTime(processStartTime);
heartBeatRecord.setHeartBeatTime(new Date());
handler(heartBeatRecord);
}catch (Throwable t){
logger.error("handler heartbeat error.", t);
}
}
}
abstract void handler(HeartBeatRecordDTO heartBeatRecord);
}

View File

@ -1,15 +0,0 @@
package net.lab1024.smartadmin.service.module.support.heartbeat.core;
/**
* [ ]
*
* @author 罗伊
*/
public interface HeartBeatLogger {
void error(String string);
void error(String string, Throwable e);
void info(String string);
}

View File

@ -1,54 +1,68 @@
package net.lab1024.smartadmin.service.module.support.heartbeat.core;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.smartadmin.service.util.SmartIPUtil;
import net.lab1024.smartadmin.service.util.SmartThreadFactory;
import javax.annotation.PreDestroy;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* [ ]
*
* @author 罗伊
*/
@Slf4j
public class HeartBeatManager extends AbstractHeartBeatManager {
public class HeartBeatManager {
private ScheduledThreadPoolExecutor threadPoolExecutor;
/**
* 服务状态持久化处理类
*/
private IHeartBeatRecordHandler heartBeatRecordHandler;
/**
* 调度配置信息
*/
private HeartBeatConfig config;
/**
* 服务信息
*/
private HeartBeatServer server;
/**
* @param delayHandlerTime 延迟执行时间
* @param intervalTime 间隔执行时间
*/
public HeartBeatManager(Long delayHandlerTime, Long intervalTime, IHeartBeatRecordHandler heartBeatRecordHandler) {
HeartBeatConfig config = HeartBeatConfig.builder().delayHandlerTime(delayHandlerTime).intervalTime(intervalTime).build();
super.init(config, new HeartBeatLogger() {
@Override
public void error(String string) {
log.error(string);
}
@Override
public void error(String string, Throwable e) {
log.error(string, e);
}
@Override
public void info(String string) {
log.info(string);
}
});
public HeartBeatManager(Long delayHandlerTime,
Long intervalTime,
IHeartBeatRecordHandler heartBeatRecordHandler) {
this.config = HeartBeatConfig.builder().delayHandlerTime(delayHandlerTime).intervalTime(intervalTime).build();
this.heartBeatRecordHandler = heartBeatRecordHandler;
this.server = handlerHeartServer();
this.threadPoolExecutor = new ScheduledThreadPoolExecutor(1, new HeartBeatThreadFactory());
this.heartBeatScheduler();
}
@PreDestroy
@Override
public void destroy() {
super.destroy();
/**
* 调度监控服务状态
*/
private void heartBeatScheduler() {
HeartBeatRunnable heartBeatRunnable = new HeartBeatRunnable(heartBeatRecordHandler,server);
threadPoolExecutor.scheduleWithFixedDelay(heartBeatRunnable, config.getDelayHandlerTime(), config.getIntervalTime(), TimeUnit.MILLISECONDS);
}
@Override
public void handler(HeartBeatRecordDTO heartBeatRecordDTO) {
heartBeatRecordHandler.handler(heartBeatRecordDTO);
/**
* 服务信息
* @return
*/
private HeartBeatServer handlerHeartServer(){
HeartBeatServer server = new HeartBeatServer();
server.setProjectPath(HeatBeatRecordHelper.getProjectPath());
server.setServerIps(SmartIPUtil.getLocalHostIPList());
server.setProcessNo(HeatBeatRecordHelper.getProcessID());
server.setProcessStartTime(HeatBeatRecordHelper.getStartTime());
return server;
}
}

View File

@ -10,7 +10,7 @@ import java.util.Date;
* @Date: 2018/7/9 11:11
*/
@Data
public class HeartBeatRecordDTO {
public class HeartBeatRecord {
/**
* 项目名字

View File

@ -0,0 +1,34 @@
package net.lab1024.smartadmin.service.module.support.heartbeat.core;
import org.apache.commons.lang3.StringUtils;
import java.util.Date;
/**
* [ ]
*
* @author 罗伊
* @date 2021/9/23 18:52
*/
public class HeartBeatRunnable implements Runnable {
private IHeartBeatRecordHandler recordHandler;
private HeartBeatServer server;
public HeartBeatRunnable(IHeartBeatRecordHandler recordHandler, HeartBeatServer server) {
this.recordHandler = recordHandler;
this.server = server;
}
@Override
public void run() {
HeartBeatRecord heartBeatRecord = new HeartBeatRecord();
heartBeatRecord.setProjectPath(server.getProjectPath());
heartBeatRecord.setServerIp(StringUtils.join(server.getServerIps(), ";"));
heartBeatRecord.setProcessNo(server.getProcessNo());
heartBeatRecord.setProcessStartTime(server.getProcessStartTime());
heartBeatRecord.setHeartBeatTime(new Date());
recordHandler.handler(heartBeatRecord);
}
}

View File

@ -0,0 +1,33 @@
package net.lab1024.smartadmin.service.module.support.heartbeat.core;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* [ ]
*
* @author 罗伊
* @date 2021/9/23 19:39
*/
@Data
public class HeartBeatServer {
/**
* 项目路径
*/
private String projectPath;
/**
* 服务器ip多网卡
*/
private List<String> serverIps;
/**
* 进程号
*/
private Integer processNo;
/**
* 进程开启时间
*/
private Date processStartTime;
}

View File

@ -0,0 +1,23 @@
package net.lab1024.smartadmin.service.module.support.heartbeat.core;
import java.util.concurrent.ThreadFactory;
/**
* [ ]
*
* @author 罗伊
* @date 2021/9/23 20:19
*/
public class HeartBeatThreadFactory implements ThreadFactory {
private static String namePrefix = "heart-beat";
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, namePrefix);
if (!t.isDaemon()) {
t.setDaemon(true);
}
return t;
}
}

View File

@ -10,7 +10,7 @@ public interface IHeartBeatRecordHandler {
/**
* 心跳日志处理方法
*
* @param recordDTO
* @param heartBeatRecord
*/
void handler(HeartBeatRecordDTO recordDTO);
void handler(HeartBeatRecord heartBeatRecord);
}

View File

@ -104,6 +104,8 @@ public class SystemConfigService {
SystemConfigEntity entity = this.CONFIG_CACHE.get(configKey);
Assert.notNull(entity, "缺少系统配置[" + configKey + "]");
Assert.isTrue(!entity.getDisabledFlag(), "系统配置[" + configKey + "]已被禁用");
return SmartBeanUtil.copy(entity, SystemConfigDTO.class);
}

View File

@ -1,6 +1,6 @@
package net.lab1024.smartadmin.service.util;
import net.lab1024.smartadmin.service.common.exception.SmartBusinessException;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.smartadmin.service.module.system.login.domain.EmployeeLoginInfoDTO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@ -8,22 +8,26 @@ import org.springframework.security.core.context.SecurityContextHolder;
/**
* @author 罗伊
*/
@Slf4j
public class SmartEmployeeTokenUtil {
/**
* 获取用户信息
*
* @return
*/
public static EmployeeLoginInfoDTO getRequestEmployee() {
try {
return (EmployeeLoginInfoDTO) getAuthentication().getPrincipal();
} catch (Exception e) {
throw new SmartBusinessException("获取用户信息异常");
log.error("获取用户信息异常{}", e);
}
return null;
}
/**
* 获取用户认证信息
*
* @return
*/
public static Authentication getAuthentication() {
@ -32,6 +36,7 @@ public class SmartEmployeeTokenUtil {
/**
* 获取用户id
*
* @return
*/
public static Long getRequestEmployeeId() {

View File

@ -22,9 +22,9 @@ spring.jackson.time-zone=GMT+8
spring.jackson.serialization.write-dates-as-timestamps=false
######################### database #########################
spring.datasource.url=jdbc:p6spy:mysql://127.0.0.1:3306/smart_admin_v2?autoReconnect=true&useServerPreparedStmts=false&rewriteBatchedStatements=true&characterEncoding=UTF-8&useSSL=false&allowMultiQueries=true&serverTimezone=Asia/Shanghai
spring.datasource.url=jdbc:p6spy:mysql://115.29.150.222:11024/smart_admin_v2?autoReconnect=true&useServerPreparedStmts=false&rewriteBatchedStatements=true&characterEncoding=UTF-8&useSSL=false&allowMultiQueries=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=1024lab
spring.datasource.password=11024Lab
spring.datasource.initial-size=2
spring.datasource.min-idle=1
spring.datasource.max-active=10
@ -40,14 +40,14 @@ spring.datasource.druid.service.scanner=net.lab1024.smartadmin.module..*Service.
######################### redis #######################################
spring.redis.database=1
spring.redis.host=127.0.0.1
spring.redis.host=115.29.150.222
spring.redis.lettuce.pool.max-active=100
spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-wait=30000ms
spring.redis.port=6379
spring.redis.port=21024
spring.redis.timeout=10000ms
spring.redis.password=
spring.redis.password=21024Lab
######################### swagger #########################
swagger.apiGroupName=smartAdmin
@ -70,7 +70,7 @@ spring.servlet.multipart.max-file-size=30MB
spring.servlet.multipart.max-request-size=30MB
######################### ali oss #########################
file.storage.mode=cloud
file.storage.mode=local
file.storage.local.path=/home/upload/
file.storage.cloud.region=oss-cn-qingdao
file.storage.cloud.endpoint=oss-cn-qingdao.aliyuncs.com

View File

@ -4074,6 +4074,17 @@ CREATE TABLE IF NOT EXISTS `t_system_config` (
PRIMARY KEY (`config_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
DROP TABLE IF EXISTS `t_heart_beat_record`;
CREATE TABLE `t_heart_beat_record` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '自增id',
`project_path` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '项目名称',
`server_ip` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '服务器ip',
`process_no` int NOT NULL COMMENT '进程号',
`process_start_time` datetime NOT NULL COMMENT '进程开启时间',
`heart_beat_time` datetime NOT NULL COMMENT '心跳时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='公用服务 - 服务心跳';
-- 正在导出表 smart_admin_v2.t_system_config 的数据:~0 rows (大约)
DELETE FROM `t_system_config`;
/*!40000 ALTER TABLE `t_system_config` DISABLE KEYS */;