国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

Springboot+mybatis-plus+注解實現(xiàn)數(shù)據(jù)權(quán)限隔離

瀏覽:23日期:2023-02-27 15:48:03
目錄1.創(chuàng)建注解2. 具體實現(xiàn)1.創(chuàng)建注解

當(dāng)此注解打在類上,不需要傳參,該類下所有查詢接口開啟數(shù)據(jù)隔離;打在方法上默認(rèn)開啟數(shù)據(jù)隔離,傳參為false則該方法關(guān)閉驗證

/** * 數(shù)據(jù)權(quán)限驗證注解 * @author xiaohua * @date 2021/6/23 */@Documented@Target({METHOD, ANNOTATION_TYPE, TYPE})@Retention(RUNTIME)public @interface DataPermission { /** * 是否要進行數(shù)據(jù)權(quán)限隔離 */ boolean isPermi() default true;}2. 具體實現(xiàn)

@Component@Intercepts({@Signature(type = StatementHandler.class, method = 'prepare', args = {Connection.class, Integer.class})})public class DataPermissionInterceptor implements Interceptor { private static final Logger logger = LoggerFactory.getLogger(DataPermissionInterceptor.class); @Autowired private TokenService tokenService; //掃描的包路徑(根據(jù)自己的項目路徑來),這里是取的配置里的包路徑 @Value('${permission.package-path}') private String packagePath; private final static String DEPT_ID = 'dept_id'; private final static String USER_ID = 'create_user'; private static List<String> classNames; @Override public Object intercept(Invocation invocation) throws Throwable {try { LoginInfo user = tokenService.getLoginInfo(); if (user == null){return invocation.proceed(); } List<Long> deptIds = (List<Long>) Convert.toList(user.getDataScope()); if (deptIds == null){deptIds = new ArrayList<>(); } //反射掃包會比較慢,這里做了個懶加載 if (classNames == null) {synchronized (LazyInit.class){ if (classNames == null){//掃描指定包路徑下所有包含指定注解的類Set<Class<?>> classSet = ClassUtil.scanPackageByAnnotation(packagePath, DataPermission.class);if (classSet == null && classSet.size() == 0){ classNames = new ArrayList<>();} else { //取得類全名 classNames = classSet.stream().map(Class::getName).collect(Collectors.toList());} }} } // 拿到mybatis的一些對象 StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget()); MetaObject metaObject = SystemMetaObject.forObject(statementHandler); MappedStatement mappedStatement = (MappedStatement) metaObject.getValue('delegate.mappedStatement'); // mappedStatement.getId()為執(zhí)行的mapper方法的全路徑名,newId為執(zhí)行的mapper方法的類全名 String newId = mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')); // 如果不是指定的方法,直接結(jié)束攔截 if (!classNames.contains(newId)) {return invocation.proceed(); } String newName = mappedStatement.getId().substring(mappedStatement.getId().lastIndexOf('.') + 1, mappedStatement.getId().length()); //是否開啟數(shù)據(jù)權(quán)限 boolean isPermi = true; Class<?> clazz = Class.forName(newId); //遍歷方法 for (Method method : clazz.getDeclaredMethods()) {//方法是否含有DataPermission注解,如果含有注解則將數(shù)據(jù)結(jié)果過濾if (method.isAnnotationPresent(DataPermission.class) && newName.equals(method.getName())) { DataPermission dataPermission = method.getAnnotation(DataPermission.class); if (dataPermission != null) {//不驗證if (!dataPermission.isPermi()) { isPermi = false;} else { //開啟驗證 isPermi = true;} }} } if (isPermi){// 獲取到原始sql語句String sql = statementHandler.getBoundSql().getSql();// 解析并返回新的SQL語句,只處理查詢sqlif (mappedStatement.getSqlCommandType().toString().equals('SELECT')) { // String newSql = getNewSql(sql,deptIds,user.getUserId()); sql = getSql(sql,deptIds,user.getUserId());}// 修改sqlmetaObject.setValue('delegate.boundSql.sql', sql); } return invocation.proceed();} catch (Exception e){ logger.error('數(shù)據(jù)權(quán)限隔離異常:', e); return invocation.proceed();} } /** * 解析SQL語句,并返回新的SQL語句 * 注意,該方法使用了JSqlParser來操作SQL,該依賴包Mybatis-plus已經(jīng)集成了。如果要單獨使用,請先自行導(dǎo)入依賴 * * @param sql 原SQL * @return 新SQL */ private String getSql(String sql,List<Long> deptIds,Long userId) {try { String condition = ''; String permissionSql = '('; if (deptIds.size() > 0){for (Long deptId : deptIds) { if ('('.equals(permissionSql)){permissionSql = permissionSql + deptId; } else {permissionSql = permissionSql + ',' + deptId; }}permissionSql = permissionSql + ')';// 修改原語句condition = DEPT_ID +' in ' + permissionSql; } else {condition = USER_ID +' = ' + userId; } if (StringUtils.isBlank(condition)){return sql; } Select select = (Select)CCJSqlParserUtil.parse(sql); PlainSelect plainSelect = (PlainSelect)select.getSelectBody(); //取得原SQL的where條件 final Expression expression = plainSelect.getWhere(); //增加新的where條件 final Expression envCondition = CCJSqlParserUtil.parseCondExpression(condition); if (expression == null) {plainSelect.setWhere(envCondition); } else {AndExpression andExpression = new AndExpression(expression, envCondition);plainSelect.setWhere(andExpression); } return plainSelect.toString();} catch (JSQLParserException e) { logger.error('解析原SQL并構(gòu)建新SQL錯誤:' + e); return sql;} }

到此這篇關(guān)于Springboot+mybatis-plus+注解實現(xiàn)數(shù)據(jù)權(quán)限隔離的文章就介紹到這了,更多相關(guān)Springboot+mybatis-plus+注解實現(xiàn)數(shù)據(jù)權(quán)限隔離內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 铅山县| 枣阳市| 潮安县| 兴化市| 图木舒克市| 商都县| 宜兰县| 许昌县| 高邮市| 城步| 牡丹江市| 鱼台县| 麻阳| 阿鲁科尔沁旗| 大石桥市| 三江| 高清| 凤山市| 无极县| 仙游县| 景德镇市| 叙永县| 彭州市| 德保县| 河池市| 龙海市| 邢台县| 巴塘县| 虎林市| 乌兰县| 南召县| 讷河市| 常德市| 石林| 宜都市| 榕江县| 洛阳市| 高州市| 华坪县| 苗栗县| 海城市|