最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Mybatis-plus通過添加攔截器實現(xiàn)簡單數(shù)據(jù)權(quán)限

 更新時間:2023年08月30日 09:20:25   作者:野風(fēng)r  
系統(tǒng)需要根據(jù)用戶所屬的公司,來做一下數(shù)據(jù)權(quán)限控制,具體一點,就是通過表中的company_id進行權(quán)限控制,項目使用的是mybatis-plus,所以通過添加攔截器的方式,修改查詢sql,實現(xiàn)數(shù)據(jù)權(quán)限,本文就通過代碼給大家詳細的講解一下,需要的朋友可以參考下

1 配置文件中的配置

# 數(shù)據(jù)權(quán)限配置  
data-permission:  
  # 不再數(shù)據(jù)權(quán)限的表,目前主要是公司信息表,和一些關(guān)聯(lián)表  
  not-control-tables: role_menu,user_company,user_role  
  # 權(quán)限控制表,即基于哪個表的數(shù)據(jù)來做權(quán)限區(qū)分,目前是公司信息表  
  base-table: company_info  
  # 特殊的uri,不進行數(shù)據(jù)權(quán)限控制  
  not-control-uri: /checkCompany-post

2 在權(quán)限處理時,將請求 uri 放入到內(nèi)存中

/**  
 * 自定義權(quán)限處理  
 */  
@Component  
@Slf4j  
public class CustomAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {  
    @Override  
    public AuthorizationDecision check(  
            Supplier<Authentication> authentication,  
            RequestAuthorizationContext requestAuthorizationContext  
    ) {  
	   // …… 
        HttpServletRequest request = requestAuthorizationContext.getRequest();  
        String method = request.getMethod();  
        String path = request.getRequestURI();  
        // 將當(dāng)前的請求的信息,放入到user中,用戶后面的數(shù)據(jù)權(quán)限  
        LoginUser loginUser = (LoginUser) authentication.get().getPrincipal();  
        loginUser.setUri(path + "-" + method.toLowerCase());  
	  // ……
    }
}

另外,用戶在的登錄系統(tǒng)之后,有一個選擇公司的動作,這時將用戶選擇的公司信息放入緩存中:

// ……
// 緩存用戶選擇的公司  
RBucket<String> bucket = redissonClient.getBucket(OPERATION_COMPANY + loginUserId);  
bucket.set(companyId, Duration.ofHours(2));
// ……

3 攔截器中的配置

import cn.hutool.core.util.ObjectUtil;  
import cn.hutool.core.util.StrUtil;  
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;  
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;  
import lombok.Data;  
import lombok.extern.slf4j.Slf4j;  
import net.sf.jsqlparser.JSQLParserException;  
import net.sf.jsqlparser.expression.Expression;  
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;  
import net.sf.jsqlparser.parser.CCJSqlParserUtil;  
import net.sf.jsqlparser.statement.select.PlainSelect;  
import net.sf.jsqlparser.statement.select.Select;  
import org.apache.ibatis.executor.Executor;  
import org.apache.ibatis.mapping.BoundSql;  
import org.apache.ibatis.mapping.MappedStatement;  
import org.apache.ibatis.session.ResultHandler;  
import org.apache.ibatis.session.RowBounds;  
import org.redisson.api.RBucket;  
import org.redisson.api.RedissonClient;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.beans.factory.annotation.Value;  
import org.springframework.security.core.Authentication;  
import org.springframework.security.core.context.SecurityContextHolder;  
import org.springframework.stereotype.Component;  
import java.sql.SQLException;  
import java.util.Arrays;  
import java.util.List;  
/**  
 * 數(shù)據(jù)權(quán)限控制  
 */  
@Data  
@Component  
@Slf4j  
public class DataPermissionInterceptor implements InnerInterceptor {  
    @Autowired  
    private RedissonClient redissonClient;  
    @Value("${data-permission.not-control-tables}")  
    public String notControlTables;  
    @Value("${data-permission.base-table}")  
    public String baseTable;  
    @Value("${data-permission.not-control-uri}")  
    public String notControlUri;  
    @Override  
    public boolean willDoQuery(  
            Executor executor,  
            MappedStatement ms,  
            Object parameter,  
            RowBounds rowBounds,  
            ResultHandler resultHandler,  
            BoundSql boundSql  
    ) throws SQLException {  
        return InnerInterceptor.super.willDoQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);  
    }  
    @Override  
    public void beforeQuery(  
            Executor executor,  
            MappedStatement ms,  
            Object parameter,  
            RowBounds rowBounds,  
            ResultHandler resultHandler,  
            BoundSql boundSql  
    ) throws SQLException {  
        log.debug("數(shù)據(jù)權(quán)限處理……");  
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();  
        if (ObjectUtil.isNull(authentication)) {  
            log.debug("數(shù)據(jù)權(quán)限處理, 未登錄!");  
            return;  
        }  
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();  
        LoginUser loginUser = (LoginUser) principal;  
        String username = loginUser.getUsername();  
        // 如果是系統(tǒng)管理員,不需做作權(quán)限處理  
        if (SYSTEM_ADMINISTRATOR_ACCOUNT.equals(username)) {  
            log.debug("數(shù)據(jù)權(quán)限處理,當(dāng)前為管理員,不需要處理數(shù)據(jù)權(quán)限。");  
            return;  
        }  
        String uri = loginUser.getUri();  
        log.debug("數(shù)據(jù)權(quán)限處理,當(dāng)前uri為:{}", uri);  
        if (notControlUri.contains(uri)) {  
            log.debug("數(shù)據(jù)權(quán)限處理,當(dāng)前uri,不需要處理數(shù)據(jù)權(quán)限。");  
            return;  
        }  
        String sql = boundSql.getSql();  
        Select select;  
        try {  
            select = (Select) CCJSqlParserUtil.parse(sql);  
        } catch (JSQLParserException e) {  
            throw new RuntimeException(e);  
        }  
        // 系統(tǒng)自動生成的sql,一般都是單表查詢,所以這里暫時不考慮復(fù)雜的情況  
        PlainSelect plainSelect = (PlainSelect) select.getSelectBody();  
        net.sf.jsqlparser.schema.Table table = (net.sf.jsqlparser.schema.Table) plainSelect.getFromItem();  
        String tableName = table.getName();  
        // 排除一些不需要控制的表  
        List<String> notControlTablesList = Arrays.asList(notControlTables.split(","));  
        if (notControlTablesList.contains(tableName.toLowerCase())) {  
            log.debug("數(shù)據(jù)權(quán)限處理,當(dāng)前表不做權(quán)限控制,table is {}", tableName);  
            return;  
        }  
        String userId = loginUser.getUser().getPkId();  
        RBucket<String> bucket = redissonClient.getBucket(OPERATION_COMPANY + userId);  
        String companyId = bucket.get();  
        if (StrUtil.isBlank(companyId)) {  
            throw new BaseException("公司id不存在!");  
        }  
        // 處理SQL語句  
        // 基礎(chǔ)表,根據(jù)主鍵進行控制  
        log.debug("數(shù)據(jù)權(quán)限處理,處理之前的sql為: {}", sql);  
        Expression where = plainSelect.getWhere();  
        Expression envCondition;  
        try {  
            if (baseTable.equals(tableName.toLowerCase())) {  
                envCondition = CCJSqlParserUtil.parseCondExpression("PK_ID = " + companyId);  
            } else {  
                envCondition = CCJSqlParserUtil.parseCondExpression("COMPANY_ID = " + companyId);  
            }  
        } catch (JSQLParserException e) {  
            throw new RuntimeException(e);  
        }  
        if (where == null) {  
            plainSelect.setWhere(envCondition);  
        } else {  
            AndExpression andExpression = new AndExpression(where, envCondition);  
            plainSelect.setWhere(andExpression);  
        }  
        sql = plainSelect.toString();  
        log.debug("數(shù)據(jù)權(quán)限處理,處理之后的sql為: {}", sql);  
        PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);  
        mpBs.sql(sql);  
    }  
}

4 啟用插件

  
@Configuration  
@MapperScan("xxx.xxx.xx.mapper")  
public class MybatisPlusConfig {  
    @Autowired  
    private DataPermissionInterceptor dataPermissionInterceptor;  
    /**  
     * 新的分頁插件,一緩和二緩遵循mybatis的規(guī)則,需要設(shè)置 MybatisConfiguration#useDeprecatedExecutor = false 避免緩存出現(xiàn)問題(該屬性會在舊插件移除后一同移除)  
     */    @Bean  
    public MybatisPlusInterceptor mybatisPlusInterceptor() {  
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();  
        interceptor.addInnerInterceptor(dataPermissionInterceptor);  
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));  
        return interceptor;  
    }  
}

到此這篇關(guān)于Mybatis-plus通過添加攔截器實現(xiàn)簡單數(shù)據(jù)權(quán)限的文章就介紹到這了,更多相關(guān)Mybatis-plus實現(xiàn)簡單數(shù)據(jù)權(quán)限內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • JDBC編程的詳細步驟

    JDBC編程的詳細步驟

    這篇文章主要介紹了JDBC編程的詳細步驟,文中有非常詳細的代碼示例,對正在學(xué)習(xí)JDBC編程的小伙伴們有很好的幫助,需要的朋友可以參考下
    2021-05-05
  • Spring Boot中使用jdbctemplate 操作MYSQL數(shù)據(jù)庫實例

    Spring Boot中使用jdbctemplate 操作MYSQL數(shù)據(jù)庫實例

    本篇文章主要介紹了Spring Boot中使用jdbctemplate 操作MYSQL數(shù)據(jù)庫實例,具有一定的參考價值,有興趣的可以了解一下。
    2017-04-04
  • 基于IDEA的Maven工程創(chuàng)建方式

    基于IDEA的Maven工程創(chuàng)建方式

    文章介紹了Maven工程的GAVP屬性(GroupId、ArtifactId、Version、Packaging)及其格式規(guī)范,說明了Idea構(gòu)建JavaSE/JavaEE工程的方法,并概述了Maven標(biāo)準(zhǔn)項目結(jié)構(gòu)的作用與目錄劃分
    2025-07-07
  • Java異常分類以及幾種處理機制分析講解

    Java異常分類以及幾種處理機制分析講解

    在Java的廣闊宇宙中,有一群特殊的“超級英雄”,它們在代碼世界中穿梭,守護著程序的正常運行——它們就是“異?!?這些英雄們,各司其職,保護著程序免受錯誤的侵?jǐn)_,今天,我們將深入這個神秘的世界,全面解析異常的分類,掌握異常的處理機制
    2024-07-07
  • idea中acitviti使用acitBPM插件出現(xiàn)亂碼問題及解決方法

    idea中acitviti使用acitBPM插件出現(xiàn)亂碼問題及解決方法

    這篇文章主要介紹了idea中acitviti使用acitBPM插件出現(xiàn)亂碼問題及解決方法,通過將File Encodings內(nèi)容設(shè)置為UTF-8,本文通過圖文展示,需要的朋友可以參考下
    2021-06-06
  • 深入理解Thread.sleep(0)的作用

    深入理解Thread.sleep(0)的作用

    本文主要介紹了深入理解Thread.sleep(0)的作用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-09-09
  • java之生產(chǎn)故障定位Arthas問題

    java之生產(chǎn)故障定位Arthas問題

    這篇文章主要介紹了java之生產(chǎn)故障定位Arthas問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • Mybatis核心配置文件、默認(rèn)類型別名、Mybatis獲取參數(shù)值的兩種方式(實例代碼)

    Mybatis核心配置文件、默認(rèn)類型別名、Mybatis獲取參數(shù)值的兩種方式(實例代碼)

    這篇文章主要介紹了Mybatis核心配置文件、默認(rèn)類型別名、Mybatis獲取參數(shù)值的兩種方式,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2024-03-03
  • Java?Stream函數(shù)式編程管道流結(jié)果處理

    Java?Stream函數(shù)式編程管道流結(jié)果處理

    這篇文章主要為大家介紹了Java?Stream函數(shù)式編程管道流結(jié)果處理的示例過程解析需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步
    2022-03-03
  • Spring Boot 中的默認(rèn)異常處理機制解析(如 /error 接口)

    Spring Boot 中的默認(rèn)異常處理機制解析(如 /error 接口)

    SpringBoot通過/error接口默認(rèn)處理異常,使用BasicErrorController返回結(jié)構(gòu)化JSON或HTML錯誤頁面,支持自定義ErrorAttributes、ControllerAdvice及錯誤模板,配置項可調(diào)整錯誤路徑和格式,本文給大家介紹Spring Boot 中的默認(rèn)異常處理機制解析,感興趣的朋友一起看看吧
    2025-07-07

最新評論

荥阳市| 万源市| 宁乡县| 二手房| 海林市| 兰西县| 额济纳旗| 大连市| 东港市| 陈巴尔虎旗| 邵阳市| 连城县| 昆山市| 繁峙县| 吴旗县| 泰和县| 图木舒克市| 平果县| 渝北区| 泸溪县| 大安市| 阳朔县| 章丘市| 莫力| 夏邑县| 苍山县| 正镶白旗| 犍为县| 清原| 仙居县| 武宣县| 大丰市| 红安县| 虎林市| 定南县| 德惠市| 莲花县| 青海省| 正镶白旗| 沈阳市| 无为县|