"eladmin-system/src/vscode:/vscode.git/clone" did not exist on "59bf09eb31eabf0509cd2d00734994123fff58a8"
Commit 05beecd0 authored by Huang's avatar Huang
Browse files

no commit message

parent bc5dd330
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jeespring</groupId>
<artifactId>jeespring-framework</artifactId>
<name>jeespring-framework</name>
<description>jeespring-framework</description>
<version>1.0.0</version>
<packaging>jar</packaging>
<parent>
<groupId>com.jeespring</groupId>
<artifactId>jeespring</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.ckfinder</groupId>
<artifactId>apache-ant-zip</artifactId>
<version>2.3</version>
<scope>system</scope>
<systemPath>${project.basedir}/../jeespring-web/src/main/webapp/WEB-INF/lib/apache-ant-zip-2.3.jar</systemPath>
</dependency>
<dependency>
<groupId>com.ckfinder</groupId>
<artifactId>ckfinder</artifactId>
<version>2.3</version>
<scope>system</scope>
<systemPath>${project.basedir}/../jeespring-web/src/main/webapp/WEB-INF/lib/ckfinder-2.3.jar</systemPath>
</dependency>
<dependency>
<groupId>com.ckfinder</groupId>
<artifactId>ckfinderplugin-fileeditor</artifactId>
<version>2.3</version>
<scope>system</scope>
<systemPath>${project.basedir}/../jeespring-web/src/main/webapp/WEB-INF/lib/ckfinderplugin-fileeditor-2.3.jar</systemPath>
</dependency>
<dependency>
<groupId>com.ckfinder</groupId>
<artifactId>ckfinderplugin-imageresize</artifactId>
<version>2.3</version>
<scope>system</scope>
<systemPath>${project.basedir}/../jeespring-web/src/main/webapp/WEB-INF/lib/ckfinderplugin-imageresize-2.3.jar</systemPath>
</dependency>
<dependency>
<groupId>com.swetake</groupId>
<artifactId>qrcode</artifactId>
<version>1.5</version>
<scope>system</scope>
<systemPath>${project.basedir}/../jeespring-web/src/main/webapp/WEB-INF/lib/QRCode-1.5.jar</systemPath>
</dependency>
<dependency>
<groupId>bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.13</version>
<scope>system</scope>
<systemPath>${project.basedir}/../jeespring-web/src/main/webapp/WEB-INF/lib/UserAgentUtils-1.13.jar</systemPath>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>
\ No newline at end of file
package com.jeespring.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* bean中文名注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldName {
String value();
}
/**
* * Copyright &copy; 2015-2020 <a href="https://gitee.com/JeeHuangBingGui/JeeSpring">JeeSpring</a> All rights reserved..
*/
package com.jeespring.common.beanvalidator;
/**
* 添加Bean验证组
* @author 黄炳桂 516821420@qq.com
*
*/
public interface AddGroup {
}
/**
* * Copyright &copy; 2015-2020 <a href="https://gitee.com/JeeHuangBingGui/JeeSpring">JeeSpring</a> All rights reserved..
*/
package com.jeespring.common.beanvalidator;
/**
* 默认Bean验证组
* @author 黄炳桂 516821420@qq.com
*/
public interface DefaultGroup {
}
/**
* * Copyright &copy; 2015-2020 <a href="https://gitee.com/JeeHuangBingGui/JeeSpring">JeeSpring</a> All rights reserved..
*/
package com.jeespring.common.beanvalidator;
/**
* 编辑Bena验证组
* @author 黄炳桂 516821420@qq.com
*/
public interface EditGroup {
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.config;
import com.ckfinder.connector.ServletContextFactory;
import com.google.common.collect.Maps;
import com.jeespring.common.utils.PropertiesLoader;
import com.jeespring.common.utils.StringUtils;
import com.jeespring.modules.sys.entity.SysConfig;
import com.jeespring.modules.sys.service.SysConfigService;
import org.apache.ibatis.io.Resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* 全局配置类
*
* @author 黄炳桂 516821420@qq.com
* @version 2014-06-25
*/
public class Global {
private static Logger logger = LoggerFactory.getLogger(Global.class);
static RelaxedPropertyResolver resolver;
//@Autowired
//private static Environment env;
/**
* 当前对象实例
*/
private static Global global = new Global();
/**
* 保存全局属性值
*/
private static Map<String, String> map = Maps.newHashMap();
/**
* 属性文件加载对象
*/
private static PropertiesLoader loader = new PropertiesLoader("bootstrap.yml");
/**
* 显示/隐藏
*/
public static final String SHOW = "1";
public static final String HIDE = "0";
/**
* 是/否
*/
public static final String YES = "1";
public static final String NO = "0";
/**
* 对/错
*/
public static final String TRUE = "true";
public static final String FALSE = "false";
/**
* 上传文件基础虚拟路径
*/
public static final String USERFILES_BASE_URL = "/userfiles/";
/**
* 获取当前对象实例
*/
public static Global getInstance() {
return global;
}
/**
* 获取配置
* ${fns:getConfig('adminPath')}
*/
public static String getConfig(String key) {
String value = map.get(key);
if (value == null) {
try {
value = resolver.getProperty(key);
//value =env.getProperty(key);
if (StringUtils.isBlank(value)) {
throw new RuntimeException("value null");
}
map.put(key, value);
} catch (Exception e) {
value = loader.getProperty(key);
map.put(key, value != null ? value : StringUtils.EMPTY);
}
}
return value;
}
public static String getConfig(String key,String value){
String result=getConfig(key);
if(result==StringUtils.EMPTY){
return value;
}
return result;
}
/**
* 获取管理端根路径
*/
public static String getAdminPath() {
return getConfig("adminPath");
}
/**
* 获取前端根路径
*/
public static String getFrontPath() {
return getConfig("frontPath");
}
/**
* 获取URL后缀
*/
public static String getUrlSuffix() {
return getConfig("urlSuffix");
}
/**
* 是否是演示模式,演示模式下不能修改用户、角色、密码、菜单、授权
*/
public static Boolean isDemoMode() {
String dm = getConfig("demoMode");
return "true".equals(dm) || "1".equals(dm);
}
public static String isDemoModeDescription() {
String dmd = getConfig("demoModeDescription");
if(dmd==null){
return "演示版启用为系统能正常演示,暂时不允许操作!";
}
return dmd;
}
public static Boolean isDubbo() {
String dm = getConfig("dubbo.run");
return "true".equals(dm) || "1".equals(dm);
}
/**
* 获取上传文件的根目录
*
* @return
*/
public static String getUserfilesBaseDir() {
String dir = getConfig("userfiles.basedir");
if (StringUtils.isBlank(dir)) {
try {
dir = ServletContextFactory.getServletContext().getRealPath("/");
} catch (Exception e) {
return "";
}
}
if (!dir.endsWith("/")) {
dir += "/";
}
return dir;
}
public static String getJdbcType() {
if (map.containsKey("spring.datasource.url")) {
return map.get("spring.datasource.url");
}
try {
String url = resolver.getProperty("spring.datasource.url");
//String url = env.getProperty("spring.datasource.url");
String type = getDbType(url);
map.put("spring.datasource.url", type);
return type;
} catch (Exception e) {
logger.error("get jdbcType error", e);
}
logger.error("return the defaut jdbc type is mysql");
return "mysql";
}
private static String getDbType(String rawUrl) {
return rawUrl == null ? null : (!rawUrl.startsWith("jdbc:derby:") && !rawUrl.startsWith("jdbc:log4jdbc:derby:") ? (!rawUrl.startsWith("jdbc:mysql:") && !rawUrl.startsWith("jdbc:cobar:") && !rawUrl.startsWith("jdbc:log4jdbc:mysql:") ? (rawUrl.startsWith("jdbc:mariadb:") ? "mariadb" : (!rawUrl.startsWith("jdbc:oracle:") && !rawUrl.startsWith("jdbc:log4jdbc:oracle:") ? (rawUrl.startsWith("jdbc:alibaba:oracle:") ? "AliOracle" : (!rawUrl.startsWith("jdbc:microsoft:") && !rawUrl.startsWith("jdbc:log4jdbc:microsoft:") ? (!rawUrl.startsWith("jdbc:sqlserver:") && !rawUrl.startsWith("jdbc:log4jdbc:sqlserver:") ? (!rawUrl.startsWith("jdbc:sybase:Tds:") && !rawUrl.startsWith("jdbc:log4jdbc:sybase:") ? (!rawUrl.startsWith("jdbc:jtds:") && !rawUrl.startsWith("jdbc:log4jdbc:jtds:") ? (!rawUrl.startsWith("jdbc:fake:") && !rawUrl.startsWith("jdbc:mock:") ? (!rawUrl.startsWith("jdbc:postgresql:") && !rawUrl.startsWith("jdbc:log4jdbc:postgresql:") ? (rawUrl.startsWith("jdbc:edb:") ? "edb" : (!rawUrl.startsWith("jdbc:hsqldb:") && !rawUrl.startsWith("jdbc:log4jdbc:hsqldb:") ? (rawUrl.startsWith("jdbc:odps:") ? "odps" : (rawUrl.startsWith("jdbc:db2:") ? "db2" : (rawUrl.startsWith("jdbc:sqlite:") ? "sqlite" : (rawUrl.startsWith("jdbc:ingres:") ? "ingres" : (!rawUrl.startsWith("jdbc:h2:") && !rawUrl.startsWith("jdbc:log4jdbc:h2:") ? (rawUrl.startsWith("jdbc:mckoi:") ? "mckoi" : (rawUrl.startsWith("jdbc:cloudscape:") ? "cloudscape" : (!rawUrl.startsWith("jdbc:informix-sqli:") && !rawUrl.startsWith("jdbc:log4jdbc:informix-sqli:") ? (rawUrl.startsWith("jdbc:timesten:") ? "timesten" : (rawUrl.startsWith("jdbc:as400:") ? "as400" : (rawUrl.startsWith("jdbc:sapdb:") ? "sapdb" : (rawUrl.startsWith("jdbc:JSQLConnect:") ? "JSQLConnect" : (rawUrl.startsWith("jdbc:JTurbo:") ? "JTurbo" : (rawUrl.startsWith("jdbc:firebirdsql:") ? "firebirdsql" : (rawUrl.startsWith("jdbc:interbase:") ? "interbase" : (rawUrl.startsWith("jdbc:pointbase:") ? "pointbase" : (rawUrl.startsWith("jdbc:edbc:") ? "edbc" : (rawUrl.startsWith("jdbc:mimer:multi1:") ? "mimer" : (rawUrl.startsWith("jdbc:dm:") ? "dm" : (rawUrl.startsWith("jdbc:kingbase:") ? "kingbase" : (rawUrl.startsWith("jdbc:log4jdbc:") ? "log4jdbc" : (rawUrl.startsWith("jdbc:hive:") ? "hive" : (rawUrl.startsWith("jdbc:hive2:") ? "hive" : (rawUrl.startsWith("jdbc:phoenix:") ? "phoenix" : null)))))))))))))))) : "informix"))) : "h2"))))) : "hsql")) : "postgresql") : "mock") : "jtds") : "sybase") : "sqlserver") : "sqlserver")) : "oracle")) : "mysql") : "derby");
}
/**
* 获取工程路径
* @return
*/
public static String getProjectPath(){
// 如果配置了工程路径,则直接返回,否则自动获取。
String projectPath = Global.getConfig("projectPath");
if (StringUtils.isNotBlank(projectPath)){
return projectPath;
}
try {
File file = new DefaultResourceLoader().getResource("").getFile();
if (file != null){
while(true){
File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
if (f == null || f.exists()){
break;
}
if (file.getParentFile() != null){
file = file.getParentFile();
}else{
break;
}
}
projectPath = file.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return projectPath;
}
/**
* 写入properties信息
*
* @param key
* 名称
* @param value
* 值
*/
public static void modifyConfig(String key, String value) {
try {
// 从输入流中读取属性列表(键和元素对)
Properties prop = getProperties();
prop.setProperty(key, value);
String path = Global.class.getResource("/jeespring.properties").getPath();
FileOutputStream outputFile = new FileOutputStream(path);
prop.store(outputFile, "modify");
outputFile.close();
outputFile.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* (注意:加载的是src下的文件,如果在某个包下.请把包名加上)
* 返回 Properties 
* @return
*/
public static Properties getProperties(){
Properties prop = new Properties();
try {
Reader reader = Resources.getResourceAsReader("/jeespring.properties");
prop.load(reader);
} catch (Exception e) {
return null;
}
return prop;
}
}
package com.jeespring.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.util.Properties;
/**
* 定时任务配置
*
* @author JeeSpring
*
*/
@Configuration
public class ScheduleConfig
{
@Bean
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource)
{
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setDataSource(dataSource);
// quartz参数
Properties prop = new Properties();
prop.put("org.quartz.scheduler.instanceName", "RuoyiScheduler");
prop.put("org.quartz.scheduler.instanceId", "AUTO");
// 线程池配置
prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
prop.put("org.quartz.threadPool.threadCount", "20");
prop.put("org.quartz.threadPool.threadPriority", "5");
// JobStore配置
prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
// 集群配置
prop.put("org.quartz.jobStore.isClustered", "true");
prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000");
prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1");
prop.put("org.quartz.jobStore.txIsolationLevelSerializable", "true");
prop.put("org.quartz.jobStore.misfireThreshold", "12000");
prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
factory.setQuartzProperties(prop);
factory.setSchedulerName("RuoyiScheduler");
// 延时启动
factory.setStartupDelay(1);
factory.setApplicationContextSchedulerContextKey("applicationContextKey");
// 可选,QuartzScheduler
// 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
factory.setOverwriteExistingJobs(true);
// 设置自动启动,默认为true
factory.setAutoStartup(true);
return factory;
}
}
package com.jeespring.common.config;
import com.jeespring.common.filter.LogoutFilter;
import com.jeespring.common.filter.OnlineSessionFilter;
import com.jeespring.common.redis.RedisUtils;
import com.jeespring.common.security.shiro.session.CacheSessionDAO;
import com.jeespring.common.security.shiro.session.SessionManager;
import com.jeespring.modules.sys.dao.OnlineSessionDAO;
import com.jeespring.modules.sys.dao.OnlineSessionFactory;
import com.jeespring.modules.sys.security.FormAuthenticationFilter;
import com.jeespring.modules.sys.security.SystemAuthorizingRealm;
import net.sf.ehcache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.DelegatingFilterProxy;
import com.jeespring.common.filter.SyncOnlineSessionFilter;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;
/**
* shiro的控制类
* 下面方法的顺序不能乱
* Created by zhao.weiwei
* create on 2017/1/11 10:59
* the email is zhao.weiwei@jyall.com.
*/
@Component
public class ShiroConfig {
/**
* 日志对象
*/
private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
@Autowired
public OnlineSessionDAO sessionDAO;
@Autowired
public OnlineSessionFactory sessionFactory;
// Session超时时间,单位为毫秒(默认30分钟)
@Value("${shiro.session.expireTime}")
private int expireTime;
//启动shiro redis缓存,单点登录
//@Value("${shiro.redis}")
//private String shiroRedis;
// 相隔多久检查一次session的有效性,单位毫秒,默认就是10分钟
@Value("${shiro.session.validationInterval}")
private int validationInterval;
// 验证码开关
@Value("${shiro.user.captchaEbabled}")
private boolean captchaEbabled;
// 验证码类型
@Value("${shiro.user.captchaType}")
private String captchaType;
// 设置Cookie的域名
@Value("${shiro.cookie.domain}")
private String domain;
// 设置cookie的有效访问路径
@Value("${shiro.cookie.path}")
private String path;
// 设置HttpOnly属性
@Value("${shiro.cookie.httpOnly}")
private boolean httpOnly;
// 设置Cookie的过期时间,秒为单位
@Value("${shiro.cookie.maxAge}")
private int maxAge;
// 登录地址
@Value("${shiro.user.loginUrl}")
private String loginUrl="/admin/login";
// 权限认证失败地址
@Value("${shiro.user.unauthorizedUrl}")
private String unauthorizedUrl;
/**
* 全局的环境变量的设置
* shiro的拦截
*
* @param environment
* @param adminPath
* @return
*/
@Bean(name = "shiroFilterChainDefinitions")
public String shiroFilterChainDefinitions(Environment environment
, @Value("${adminPath}") String adminPath
, @Value("${frontPath}") String frontPath) {
Global.resolver = new RelaxedPropertyResolver(environment);
StringBuilder string=new StringBuilder();
string.append("/static/** = anon\n");
string.append("/staticViews/** = anon\n");
string.append("/jeeSpringStatic/** = anon\n");
string.append("/userfiles/** = anon\n");
string.append("/rest/** = anon\n");
string.append(frontPath+"/** = anon\n");
string.append( adminPath + "/basic = basic\n");
string.append( adminPath + "/login = authc\n");
string.append( adminPath + "/loginBase = anon\n");
string.append( adminPath + "/logout = logout\n");
string.append( adminPath + "/register = anon\n");
string.append( adminPath + "/sys/register/registerUser = anon\n");
string.append( adminPath + "/sys/user/validateLoginName = anon\n");
string.append( adminPath + "/sys/user/validateMobile = anon\n");
string.append( adminPath + "/** = user\n");
string.append( "/ReportServer/** = user");
return string.toString();
}
@Bean(name = "basicHttpAuthenticationFilter")
public BasicHttpAuthenticationFilter casFilter(@Value("${adminPath:/a}") String adminPath) {
BasicHttpAuthenticationFilter basicHttpAuthenticationFilter = new BasicHttpAuthenticationFilter();
basicHttpAuthenticationFilter.setLoginUrl(adminPath + "/login");
return basicHttpAuthenticationFilter;
}
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean(
@Value("${adminPath:/a}") String adminPath,
BasicHttpAuthenticationFilter basicHttpAuthenticationFilter,
FormAuthenticationFilter formAuthenticationFilter,
DefaultWebSecurityManager securityManager,
@Qualifier("shiroFilterChainDefinitions") String shiroFilterChainDefinitions) {
Map<String, Filter> filters = new HashMap<>();
filters.put("basic", basicHttpAuthenticationFilter);
filters.put("authc", formAuthenticationFilter);
filters.put("syncOnlineSession", syncOnlineSessionFilter());
//filters.put("onlineSession", onlineSessionFilter());
filters.put("logout", logoutFilter());
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
bean.setFilters(filters);
bean.setSecurityManager(securityManager);
bean.setLoginUrl(adminPath + "/login");
bean.setSuccessUrl(adminPath + "?login");
// Shiro过滤器配置
bean.setFilterChainDefinitions(shiroFilterChainDefinitions);
return bean;
}
@Bean(name = "shiroCacheManager")
public EhCacheManager shiroCacheManager(CacheManager manager) {
EhCacheManager ehCacheManager = new EhCacheManager();
ehCacheManager.setCacheManager(manager);
return ehCacheManager;
}
//@Bean(name = "redisCacheManager")
public RedisCacheManager redisCacheManager(String redisHostName,String reidsPassword,int reidsPort,int expireTimeShiro) {
RedisCacheManager redisCacheManager= new RedisCacheManager();
RedisManager redisManager= new RedisManager();
redisManager.setHost(redisHostName);
redisManager.setPassword(reidsPassword);
redisManager.setPort(reidsPort);
redisManager.setExpire(expireTimeShiro);
redisCacheManager.setRedisManager(redisManager);
return redisCacheManager;
}
@Bean(name = "sessionManager")
public SessionManager sessionManager(CacheSessionDAO dao) {
SessionManager sessionManager = new SessionManager();
sessionManager.setSessionDAO(dao);
// 设置全局session超时时间
sessionManager.setGlobalSessionTimeout(86400000);
// 相隔多久检查一次session的有效性,单位毫秒,默认就是10分钟
sessionManager.setSessionValidationInterval(1800000);
sessionManager.setSessionValidationSchedulerEnabled(true);
sessionManager.setSessionIdCookie(new SimpleCookie("com.jeespring.session.id"));
sessionManager.setSessionIdCookieEnabled(true);
// 删除过期的session
sessionManager.setDeleteInvalidSessions(true);
// 去掉 JSESSIONID
sessionManager.setSessionIdUrlRewritingEnabled(false);
// 是否定时检查session
sessionManager.setSessionValidationSchedulerEnabled(true);
// 自定义SessionDao
//sessionManager.setSessionDAO(sessionDAO());
// 自定义sessionFactory
//sessionManager.setSessionFactory(sessionFactory());
return sessionManager;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager defaultWebSecurityManager(
SystemAuthorizingRealm systemAuthorizingRealm,
SessionManager sessionManager,
EhCacheManager ehCacheManager,
@Value("${spring.redis.run}") String redisRun,
@Value("${spring.redis.hostName}") String redisHostName,
@Value("${spring.redis.password}") String reidsPassword,
@Value("${spring.redis.port}") int redisPort,
@Value("${spring.redis.expireTimeShiro}") int expireTimeShiro,
@Value("${shiro.redis}") String shiroRedis
) {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setSessionManager(sessionManager);
if("true".equals(redisRun) && "true".equals(shiroRedis)){
try{
// 加入缓存管理器
defaultWebSecurityManager.setCacheManager(redisCacheManager(redisHostName,reidsPassword,redisPort,expireTimeShiro));
} catch (Exception e) {
logger.error("RedisUtils run:"+RedisUtils.RUN_MESSAGE+e.getMessage(), RedisUtils.RUN_MESSAGE+e.getMessage());
defaultWebSecurityManager.setCacheManager(ehCacheManager);
}
}else{
// 加入缓存管理器
defaultWebSecurityManager.setCacheManager(ehCacheManager);
}
defaultWebSecurityManager.setRealm(systemAuthorizingRealm);
return defaultWebSecurityManager;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
DefaultWebSecurityManager defaultWebSecurityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(defaultWebSecurityManager);
return authorizationAttributeSourceAdvisor;
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
filterRegistration.addInitParameter("targetFilterLifecycle", "true");
filterRegistration.setEnabled(true);
filterRegistration.addUrlPatterns("/*");
return filterRegistration;
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
@DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
return defaultAdvisorAutoProxyCreator;
}
/**
* 自定义在线用户处理过滤器
*/
public OnlineSessionFilter onlineSessionFilter()
{
OnlineSessionFilter onlineSessionFilter = new OnlineSessionFilter();
//onlineSessionFilter.setLoginUrl(loginUrl);
return onlineSessionFilter;
}
/**
* 自定义在线用户同步过滤器
*/
@Bean
public SyncOnlineSessionFilter syncOnlineSessionFilter()
{
SyncOnlineSessionFilter syncOnlineSessionFilter = new SyncOnlineSessionFilter();
return syncOnlineSessionFilter;
}
public LogoutFilter logoutFilter()
{
LogoutFilter logoutFilter = new LogoutFilter();
logoutFilter.setLoginUrl(loginUrl);
return logoutFilter;
}
}
package com.jeespring.common.constant;
/**
* 通用常量信息
*
* @author JeeSpring
*/
public class Constants
{
/**
* UTF-8 字符集
*/
public static final String UTF8 = "UTF-8";
/**
* 通用成功标识
*/
public static final String SUCCESS = "0";
/**
* 通用失败标识
*/
public static final String FAIL = "1";
/**
* 登录成功
*/
public static final String LOGIN_SUCCESS = "Success";
/**
* 注销
*/
public static final String LOGOUT = "Logout";
/**
* 登录失败
*/
public static final String LOGIN_FAIL = "Error";
/**
* 自动去除表前缀
*/
public static String AUTO_REOMVE_PRE = "true";
/**
* 当前记录起始索引
*/
public static String PAGE_NUM = "pageNum";
/**
* 每页显示记录数
*/
public static String PAGE_SIZE = "pageSize";
/**
* 排序列
*/
public static String ORDER_BY_COLUMN = "orderByColumn";
/**
* 排序的方向 "desc" 或者 "asc".
*/
public static String IS_ASC = "isAsc";
}
package com.jeespring.common.constant;
/**
* 任务调度通用常量
*
* @author JeeSpring
*/
public interface ScheduleConstants
{
public static final String TASK_CLASS_NAME = "__TASK_CLASS_NAME__";
public static final String TASK_PROPERTIES = "__TASK_PROPERTIES__";
/** 默认 */
public static final String MISFIRE_DEFAULT = "0";
/** 立即触发执行 */
public static final String MISFIRE_IGNORE_MISFIRES = "1";
/** 触发一次执行 */
public static final String MISFIRE_FIRE_AND_PROCEED = "2";
/** 不触发立即执行 */
public static final String MISFIRE_DO_NOTHING = "3";
public enum Status
{
/**
* 正常
*/
NORMAL("0"),
/**
* 暂停
*/
PAUSE("1");
private String value;
private Status(String value)
{
this.value = value;
}
public String getValue()
{
return value;
}
}
}
package com.jeespring.common.constant;
/**
* Shiro通用常量
*
* @author JeeSpring
*/
public interface ShiroConstants
{
/**
* 当前登录的用户
*/
public static final String CURRENT_USER = "currentUser";
/**
* 用户名
*/
public static final String CURRENT_USERNAME = "username";
/**
* 消息key
*/
public static String MESSAGE = "message";
/**
* 错误key
*/
public static String ERROR = "errorMsg";
/**
* 编码格式
*/
public static String ENCODING = "UTF-8";
/**
* 当前在线会话
*/
public String ONLINE_SESSION = "online_session";
/**
* 验证码key
*/
public static final String CURRENT_CAPTCHA = "captcha";
/**
* 验证码开关
*/
public static final String CURRENT_EBABLED = "captchaEbabled";
/**
* 验证码开关
*/
public static final String CURRENT_TYPE = "captchaType";
/**
* 验证码
*/
public static final String CURRENT_VALIDATECODE = "validateCode";
/**
* 验证码错误
*/
public static final String CAPTCHA_ERROR = "captchaError";
}
package com.jeespring.common.druid;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
/**
*
* 描述:如果不使用代码手动初始化DataSource的话,监控界面的SQL监控会没有数据("是spring boot的bug???")
* @author chhliu
* 创建时间:2017年2月9日 下午10:33:08
* @version 1.2.0
*/
@Configuration
public class DruidConfiguration {
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.datasource.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.filters}")
private String filters;
@Value("${spring.datasource.connectionProperties}")
private String connectionProperties;
@Value("${spring.datasource.useGlobalDataSourceStat}")
private boolean useGlobalDataSourceStat;
@Bean //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
System.err.println("druid configuration initialization filter: "+ e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
}
\ No newline at end of file
package com.jeespring.common.druid;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import com.alibaba.druid.support.http.WebStatFilter;
/**
* Druid的StatFilter
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年3月17日
*/
@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
initParams={
@WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源
})
public class DruidStatFilter extends WebStatFilter {
}
\ No newline at end of file
package com.jeespring.common.druid;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import com.alibaba.druid.support.http.StatViewServlet;
/**
* StatViewServlet
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年3月17日
*/
@SuppressWarnings("serial")
@WebServlet(urlPatterns = "/druid/*",
initParams={
@WebInitParam(name="allow",value="192.168.16.110,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问)
@WebInitParam(name="deny",value="192.168.16.111"),// IP黑名单 (存在共同时,deny优先于allow)
//WebInitParam(name="loginUsername",value="shanhy"),// 用户名
//WebInitParam(name="loginPassword",value="shanhypwd"),// 密码
@WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
})
public class DruidStatViewServlet extends StatViewServlet {
}
\ No newline at end of file
package com.jeespring.common.exception.job;
/**
* 计划策略异常
*
* @author JeeSpring
*/
public class TaskException extends Exception
{
private static final long serialVersionUID = 1L;
private Code code;
public TaskException(String msg, Code code)
{
this(msg, code, null);
}
public TaskException(String msg, Code code, Exception nestedEx)
{
super(msg, nestedEx);
this.code = code;
}
public Code getCode()
{
return code;
}
public enum Code
{
TASK_EXISTS, NO_TASK_EXISTS, TASK_ALREADY_STARTED, UNKNOWN, CONFIG_ERROR, TASK_NODE_NOT_AVAILABLE
}
}
\ No newline at end of file
package com.jeespring.common.filter;
import com.ckfinder.connector.FileUploadFilter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
/**
* Created by zhao.weiwei
* create on 2017/1/10 12:23
* the email is zhao.weiwei@jyall.com.
*/
@WebFilter(urlPatterns = "/static/ckfinder/core/connector/java/connector.java", initParams = {
@WebInitParam(name = "sessionCookieName", value = "JSESSIONID"),
@WebInitParam(name = "sessionParameterName", value = "jsessionid")
})
public class JeesiteFileUploadFilter extends FileUploadFilter {
}
package com.jeespring.common.filter;
import com.jeespring.common.security.ShiroUtils;
import com.jeespring.common.utils.StringUtils;
import com.jeespring.modules.monitor.entity.OnlineSession;
import com.jeespring.modules.sys.dao.OnlineSessionDAO;
import com.jeespring.modules.sys.entity.SysUserOnline;
import com.jeespring.modules.sys.entity.User;
import com.jeespring.modules.sys.service.SysUserOnlineService;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* 退出过滤器
*
* @author JeeSpring
*/
public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter
{
private SysUserOnlineService sysUserOnlineService;
private static final Logger log = LoggerFactory.getLogger(LogoutFilter.class);
/**
* 退出后重定向的地址
*/
private String loginUrl="/admin/login";
public String getLoginUrl()
{
return loginUrl;
}
public void setLoginUrl(String loginUrl)
{
this.loginUrl = loginUrl;
}
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception
{
try
{
Subject subject = getSubject(request, response);
String redirectUrl = getRedirectUrl(request, response, subject);
try
{
User user = ShiroUtils.getUser();
if (StringUtils.isNotNull(user))
{
String loginName = user.getLoginName();
SysUserOnline sysUserOnline=new SysUserOnline();
sysUserOnline.setLoginName(user.getName());
if(sysUserOnlineService==null){
ServletContext context = request.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
sysUserOnlineService = ctx.getBean(SysUserOnlineService.class);
}
if(sysUserOnlineService!=null){
sysUserOnline= sysUserOnlineService.get(subject.getSession().getId().toString());
if(sysUserOnline!=null){
sysUserOnline.setStatus(OnlineSession.OnlineStatus.off_line.toString());
sysUserOnlineService.save(sysUserOnline);
}
}
// 记录用户退出日志
//SystemLogUtils.log(loginName, Constants.LOGOUT, MessageUtils.message("user.logout.success"));
}
// 退出登录
subject.logout();
}
catch (SessionException ise)
{
log.error("logout fail.", ise);
}
issueRedirect(request, response, redirectUrl);
}
catch (Exception e)
{
log.error("Encountered session exception during logout. This can generally safely be ignored.", e);
}
return false;
}
/**
* 退出跳转URL
*/
@Override
protected String getRedirectUrl(ServletRequest request, ServletResponse response, Subject subject)
{
String url = getLoginUrl();
if (StringUtils.isNotEmpty(url))
{
return url;
}
return super.getRedirectUrl(request, response, subject);
}
}
package com.jeespring.common.filter;
import com.jeespring.common.constant.ShiroConstants;
import com.jeespring.common.security.ShiroUtils;
import com.jeespring.common.utils.IpUtils;
import com.jeespring.common.utils.ServletUtils;
import com.jeespring.modules.sys.dao.OnlineSessionDAO;
import com.jeespring.modules.sys.entity.User;
import com.jeespring.modules.sys.service.SysUserOnlineService;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import com.jeespring.modules.monitor.entity.OnlineSession;
/**
* 自定义访问控制
*
* @author JeeSpring
*/
public class OnlineSessionFilter //extends AccessControlFilter
{
/**
* 强制退出后重定向的地址
*/
@Value("${shiro.user.loginUrl}")
private String loginUrl="/admin/login";
/**
* 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false;
*/
//@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
throws Exception
{
Subject subject = getSubject(request, response);
if (subject == null || subject.getSession() == null)
{
return true;
}
//Session session = onlineSessionDAO.readSession(subject.getSession().getId());
Session session =subject.getSession();
//&& session instanceof OnlineSession
if (session != null)
{
//OnlineSession onlineSession = (OnlineSession) session;
OnlineSession onlineSession = new OnlineSession();
onlineSession.setId(subject.getSession().getId().toString());
request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession);
// 把user对象设置进去
boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == "";
if (isGuest == true)
{
User user = ShiroUtils.getUser();
if (user != null)
{
onlineSession.setUserId(user.getId());
onlineSession.setLoginName(user.getLoginName());
if(user.getOffice()!=null) {
onlineSession.setDeptName(user.getOffice().getName());
}
onlineSession.markAttributeChanged();
UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
// 获取客户端操作系统
String os = userAgent.getOperatingSystem().getName();
// 获取客户端浏览器
String browser = userAgent.getBrowser().getName();
onlineSession.setHost(IpUtils.getIpAddr((HttpServletRequest)request));
onlineSession.setBrowser(browser);
onlineSession.setOs(os);
}
}
if (onlineSession.getStatus() == OnlineSession.OnlineStatus.off_line)
{
return false;
}
}
return true;
}
/**
* 表示当访问拒绝时是否已经处理了;如果返回true表示需要继续处理;如果返回false表示该拦截器实例已经处理了,将直接返回即可。
*/
//@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception
{
Subject subject = getSubject(request, response);
if (subject != null)
{
subject.logout();
}
//saveRequestAndRedirectToLogin(request, response);
return true;
}
// 跳转到登录页
//@Override
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException
{
WebUtils.issueRedirect(request, response, loginUrl);
}
/**
* 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false;
*/
protected Subject getSubject(ServletRequest request, ServletResponse response) {
return SecurityUtils.getSubject();
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.filter;
import com.jeespring.common.utils.SpringContextHolder;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter;
/**
* 页面高速缓存过滤器
* @author 黄炳桂 516821420@qq.com
* @version 2013-8-5
*/
public class PageCachingFilter extends SimplePageCachingFilter {
private CacheManager cacheManager = SpringContextHolder.getBean(CacheManager.class);
@Override
protected CacheManager getCacheManager() {
this.cacheName = "pageCachingFilter";
return cacheManager;
}
}
package com.jeespring.common.filter;
import com.jeespring.common.constant.ShiroConstants;
import com.jeespring.common.redis.RedisUtils;
import com.jeespring.common.security.ShiroUtils;
import com.jeespring.common.utils.IpUtils;
import com.jeespring.common.utils.ServletUtils;
import com.jeespring.modules.monitor.entity.OnlineSession;
import com.jeespring.modules.sys.dao.OnlineSessionDAO;
import com.jeespring.modules.sys.entity.User;
import com.jeespring.modules.sys.service.SysUserOnlineService;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 同步Session数据到Db
*
* @author JeeSpring
*/
public class SyncOnlineSessionFilter extends PathMatchingFilter
{
/**
* 日志对象
*/
private static Logger logger = LoggerFactory.getLogger(SyncOnlineSessionFilter.class);
@Autowired
private SysUserOnlineService sysUserOnlineService;
/**
* 强制退出后重定向的地址
*/
@Value("${shiro.user.loginUrl}")
private String loginUrl;
/**
* 同步会话数据到DB 一次请求最多同步一次 防止过多处理 需要放到Shiro过滤器之前
*
* @param request
* @param response
* @return
* @throws Exception
*/
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception
{
try {
OnlineSessionFilter onlineSessionFilter=new OnlineSessionFilter();
onlineSessionFilter.isAccessAllowed(request,response,null);
//isAccessAllowed(request, response);
OnlineSession session = (OnlineSession) request.getAttribute(ShiroConstants.ONLINE_SESSION);
// 如果session stop了 也不同步
// session停止时间,如果stopTimestamp不为null,则代表已停止
if (session != null && session.getUserId() != null && session.getStopTimestamp() == null)
{
sysUserOnlineService.syncToDb(session);
}
return true;
}catch (Exception e){
logger.error("SyncOnlineSessionFilter preHandle error:", e.getMessage());
return true;
}
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment