import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.web.context.ContextLoader;
/**
*
* We construct data security layer,Generally speaking:
* When the wms start, we detect the security metadata and put it into WMSSecurityContext
* A request arrive,if there is an Annotation EnbableDataSewcurity upon the method,we register(mistake) method info into WMSSecurityContext
* Before data access,we will check if the "data access session" need in an "security environment".
* If yes,we alternative sql.then post to db.
* please see detail information about alternative sql in class DataPermissionSqlUtil
*
* */
public class DataPermissionBeforeAdvice implements MethodBeforeAdvice { //logger for class DataPermissionBeforeAdvice
private static final Logger logger = Logger.getLogger(DataPermissionBeforeAdvice.class); @Override
public void before(Method method, Object[] args, Object target) throws Throwable {
boolean shouldExecuteDataSecurity = checkIfNeedExecuteDataSecurity();
if (shouldExecuteDataSecurity) {
executeDataSecurity(method, args, target, shouldExecuteDataSecurity);
}
} /**
* check if the "session" need an security context.
* */
private boolean checkIfNeedExecuteDataSecurity() {
boolean shouldExecuteDataSecurity = false ;
String dataSecurityMethodSignature = WMSSecurityContext.getDataSecurityMethodSignature().get();
if (dataSecurityMethodSignature != null) { // 确定调用方法拥有 @EnableDataSecurity注解标识
// web.xml文件中已经启用数据权限
String enableDataSecurity = ContextLoader.getCurrentWebApplicationContext().getServletContext().getInitParameter("EnableDataSecurity");
if (enableDataSecurity != null && "true".equals(enableDataSecurity)) {
shouldExecuteDataSecurity = true;
}
}
return shouldExecuteDataSecurity;
} /**
* retrieve security metadata ,and alternative sql(s).
* */
@SuppressWarnings("rawtypes")
private void executeDataSecurity(Method method, Object[] args,
Object target, boolean shouldExecuteDataSecurity) throws Throwable {
if (target instanceof JdbcOperations) {
if (logger.isDebugEnabled()) {
logger.debug("exeute data security begin.");
}
// do alternative sql operation
if (shouldExecuteDataSecurity) {
Class[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
Class paramterType = parameterTypes[i];
if ("String".equals(paramterType.getSimpleName())) {
String sql = (String) args[i];
String sqlByDataPermission = DataPermissionSqlUtil.alternateSqlByDataPermission(sql);
if (logger.isDebugEnabled()) {
logger.debug("sql after data permission: " + sqlByDataPermission);
}
args[i] = sqlByDataPermission;
} else if ("String[]".equals(paramterType.getSimpleName())) {
String[] sqls = (String[]) args[i];
for (int j = 0; j < sqls.length; j++) {
String sql = sqls[j];
String sqlByDataPermission = DataPermissionSqlUtil.alternateSqlByDataPermission(sql);
sqls[j] = sqlByDataPermission;
}
args[i] = sqls;
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("exeute data security end.");
}
}
} }
import java.io.StringReader;
import java.util.List; import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.replace.Replace;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.update.Update;
import net.sf.jsqlparser.util.TablesNamesFinder; import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger; /**
* Handy class for alternative SQL with data authority and user context
*/
public class DataPermissionSqlUtil { //logger for class DataPermissionSqlUtil
private static final Logger logger =
Logger.getLogger(DataPermissionSqlUtil.class); private static CCJSqlParserManager pm = new CCJSqlParserManager(); /**
* calculate subquery by table name
* */
public static String alternateSqlByDataPermission(String sql) throws Exception { if (logger.isDebugEnabled()) {
logger.debug("alternateSqlByDataPermission begin...");
} List<String> tableNames = getTableNames(sql);
// if sql is not SELECT type
// return sql directly
if (null == tableNames) {
return sql;
}
for (String tablename : tableNames) {
// calculate alternative SQL
String subquery = getSubqueryByTableName(tablename);
if (logger.isDebugEnabled()) {
logger.debug("table name is : " + tablename + " subquery is : " + subquery);
}
// replace table name to subquery
sql = sql.replaceAll(tablename, subquery);
// 只替换第一个表名(主表),关联表名 不替换
break;
}
return sql;
} /**
* detect table names from given table
* ATTENTION : WE WILL SKIP SCALAR SUBQUERY IN PROJECTION CLAUSE
* */
private static List<String> getTableNames(String sql) throws Exception {
List<String> tablenames = null;
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
Statement statement = pm.parse(new StringReader(sql));
if (statement instanceof Select) {
tablenames = tablesNamesFinder.getTableList((Select) statement);
} else if (statement instanceof Update) {
return null;
} else if (statement instanceof Delete) {
return null;
} else if (statement instanceof Replace) {
return null;
} else if (statement instanceof Insert) {
return null;
}
return tablenames;
} private static String getSubqueryByTableName(String tableName) throws Exception {
String subquery = null;
String relatedFromClause = processFromConstriant(tableName); // 拼接关联表查询字段 控制权限
String experiyWhereClause = processExperiyConstriant(tableName); // 拼接Status字段控制启用 禁用,指定状态字段
String domainWhereClause = processDomainConstriant(tableName); // 根据员工登录 控制只能看到当前登录机构的数据,指定机构字段
String dataPermissionWhereClause = processDataPermissionConstriant(tableName); // 数据权限控制 if(StringUtils.isEmpty(experiyWhereClause) && StringUtils.isEmpty(domainWhereClause) && StringUtils.isEmpty(dataPermissionWhereClause)) {
return tableName;
} else {
StringBuilder querySb = new StringBuilder()
.append(" ( ").append(SqlConstants.SQL_SELECT).append(" ").append(DataSecurityHelper.getMainTableAlias(tableName)).append(" * ")
.append(SqlConstants.SQL_FROM).append(" ").append(tableName).append(" ");
if(StringUtils.isNotBlank(relatedFromClause)) {
querySb.append(relatedFromClause).append(" ");
}
querySb.append(SqlConstants.SQL_WHERE).append(" ");
if(StringUtils.isNotBlank(experiyWhereClause)) {
querySb.append(experiyWhereClause).append(" ").append(SqlConstants.SQL_AND);
}
if(StringUtils.isNotBlank(domainWhereClause)) {
querySb.append(domainWhereClause).append(" ").append(SqlConstants.SQL_AND);
}
if(StringUtils.isNotBlank(dataPermissionWhereClause)) {
querySb.append(dataPermissionWhereClause).append(" ").append(SqlConstants.SQL_AND);
}
querySb = StringUtil.deleteLastSequence(querySb,SqlConstants.SQL_AND);
querySb.append(" ) ");
subquery = querySb.toString();
}
return subquery;
} /**
* filter related from table column data
* lifeng
* */
private static String processFromConstriant(String tableName) {
String relatedFromClause = DataSecurityHelper.buildRelatedConstriantSql(tableName);
return relatedFromClause;
} /**
* filter expiry data
* */
private static String processExperiyConstriant(String tableName) {
String experiyWhereClause = DataSecurityHelper.buildExpiryConstriantSql(tableName);
return experiyWhereClause;
} /**
* filter domain data
* */
private static String processDomainConstriant(String tableName) {
String domainWhereClause = DataSecurityHelper.buildDomainConstriantSql(tableName);
return domainWhereClause;
} /**
* filter permission data
* */
private static String processDataPermissionConstriant(String tableName) {
String dataPermissionWhereClause = DataSecurityHelper.buildDataAuthorityConstriantSql(tableName);
return dataPermissionWhereClause;
} }

applicationContext-security.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"> <mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.yundaex.wms" /> <!-- Base package to scan the mongo repositories, where we create de DAOS to access data and domain objects -->
<mongo:repositories base-package="com.yundaex.wms.security.mongo" /> <bean id="dataPermissionBeforeAdvice" class="com.yundaex.common.security.advice.DataPermissionBeforeAdvice" /> <aop:config proxy-target-class="true">
<aop:pointcut expression="execution(public * org.springframework.jdbc.core.JdbcTemplate.*(..)) and !execution(public * org.springframework.jdbc.core.JdbcTemplate.queryForList(*))" id="jdbcTemplatePointcut"/>
<aop:advisor advice-ref="dataPermissionBeforeAdvice" pointcut-ref="jdbcTemplatePointcut"/>
</aop:config> <bean id="mongoRoleDao" class="com.yundaex.wms.security.mongo.impl.MongoRoleDaoImpl">
</bean> <bean id="mongoFunctionAuthorityDao" class="com.yundaex.wms.security.mongo.impl.MongoFunctionAuthorityDaoImpl">
</bean> <bean id="mongoUserDao" class="com.yundaex.wms.security.mongo.impl.MongoUserDaoImpl"></bean> </beans>

web.xml

    <!-- Enable data security -->
<context-param>
<param-name>EnableDataSecurity</param-name>
<param-value>true</param-value>
</context-param>

查询时根据权限更改sql的更多相关文章

  1. IN 查询时出现ORA-01795:列表中的最大表达式数为1000解决方法

    问题描写叙述: SQL进行IN查询时出现:java.sql.SQLException: ORA-01795: 列表中的最大表达式数为 1000 解决的方法: 问题原因是:SQL进行IN查询时.IN中的 ...

  2. sql 关于查询时 出现的 从数据类型 varchar 转换为 numeric 时出错 的解决方法。

    出现这种问题 一般是查询时出现了 varchar 转 numeric 时出了错  或varchar字段运算造成的 解决方法: 让不能转的数不转换就可以了 sql的函数有个isNumeric(参数) 用 ...

  3. 一对一关联查询时使用relation连贯操作查询后,调用getLastSql()方法输出的sql语句

    如题: 一对一关联查询时使用relation连贯操作查询后,调用getLastSql()方法输出的sql语句不是一条关联查询语句. 例如: $list = $db->relation(true) ...

  4. PL/SQL Developer 使用中文条件查询时无数据的解决方法

    PL/SQL Developer 使用中文条件查询时无数据,这是由于字符集的不一致导致的. 执行以下sql命令:select userenv('language') from dual; 显示:SIM ...

  5. oracle中使用sql查询时字段为空则赋值默认

    转至:http://www.th7.cn/db/Oracle/201501/86125.shtml oracle 通过 nvl( )函数sql 查询时为 空值 赋默认值 oracle 函数介绍之nvl ...

  6. 警惕 MySql 更新 sql 的 WHERE 从句中的 IN() 子查询时出现的性能陷阱

    警惕 MySql 更新 sql 的 WHERE 从句中的 IN() 子查询时出现的性能陷阱 以下文章来源:https://blog.csdn.net/defonds/article/details/4 ...

  7. [转]关于oracle sql语句查询时表名和字段名要加双引号的问题

    oracle初学者一般会遇到这个问题.   用navicat可视化创建了表,可是就是不能查到!   后来发现②语句可以查询到 ①select * from user; 但是,我们如果给user加上双引 ...

  8. SQL字段类型bit 查询时注意

    sql 查询时  字段=1 或 字段=0 c# 里也是

  9. SQL Server查询时添加一列连续的自增列

    SQL Server查询时添加一列连续的自增列 在SQL Server数据库中表信息会用到Identity关键字来设置自增列.但是当有数据被删除的话,自增列就不连续了.如果想查询出这个表的信息,并添加 ...

随机推荐

  1. 洛谷【P1100】高低位交换

    二进制前置技能:https://www.cnblogs.com/AKMer/p/9698694.html 题目传送门:https://www.luogu.org/problemnew/show/P11 ...

  2. 我的日志app企划书1.0版本

    因为个人的工作习惯,想要做一个app,是关于工作(生活)日志的. 目前有几个预想的功能吧. 1.按天展示自己的每日安排. 2.每到周末展示自己的周末安排. 1的需要: 是由于,每天总有那么一点两点的细 ...

  3. Hyperledger fablic 0.6 在centos7环境下的安装与部署

    原文:http://blog.csdn.net/zhaoliang1131/article/details/54617274 Hyperledger Fabric超级账本 项目约定共同遵守的 基本原则 ...

  4. java blob 文件上传下载

    1.文件上传 pojo中为byte[] 类型,数据库中对应为blob类型. 主要代码: FileInputStream fis = null; fis = new FileInputStream(ne ...

  5. wpf staticresource 是不允许向前引用(forward reference)的

    不允许向前引用(forward reference)在C/C++中中很常见,即在语法上,未定义变量.类之前,不能使用. 没想到wpf中的wpf staticresource也遵循这种规则.资源字典中, ...

  6. 一 Akka学习 - actor

    (引用 http://shiyanjun.cn/archives/1168.html) 一: 什么是Akka? Akka是JAVA虚拟机JVM平台上构建高并发.分布式和容错应用的工具包和运行时,是一个 ...

  7. 【原】spring jar 下载

    作者:david_zhang@sh [转载时请以超链接形式标明文章] 链接:http://www.cnblogs.com/david-zhang-index/p/8098965.html 1.进入官网 ...

  8. C笔试题(二)

    /* 现在有一个数组 我们可以定义数组的子数组 如 数组 1 3 4 2 5 8 7 它的子数组可以是 1 3 4 3 4 2 5 等等 请写一个算法 找一个子数组 这个子数组递增不减少 并且是满足递 ...

  9. js中的Number方法

    1.Number.toExponential(fractionDigits) 把number转换成一个指数形式的字符串.可选参数控制其小数点后的数字位数.它必须在0~20之间. 例如: documen ...

  10. 菜鸟攻城狮3(Holle World)

    1.创建一个HolleWorld.java文本文件 2.代码:public class HolleWorld { public static void main(String[] args) { Sy ...