MyBatisPlus數(shù)據(jù)權(quán)限控制實(shí)現(xiàn)的三種方式
一、場(chǎng)景
在數(shù)據(jù)權(quán)限控制時(shí),希望是全局的,比如每個(gè)sql都根據(jù)當(dāng)前登錄人查詢(xún),因此希望每個(gè)sql都在最后拼接 “create_user = ‘admin’”
二、實(shí)現(xiàn)方式(提供兩種,自行選擇)
注意:每張表都必須保證create_user 的字段存在,否則要重寫(xiě)ignoreTable方法
2.1 模仿租戶(hù)實(shí)現(xiàn)方式
@Bean
public MybatisPlusInterceptor paginationInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
paginationInnerInterceptor.setDbType(DbType.MYSQL);
paginationInnerInterceptor.setMaxLimit(1000L);
paginationInnerInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
interceptor.addInnerInterceptor(new CustomLineInnerInterceptor(new com.szls.config.DataPermissionHandler() {
@Override
public Expression getCreateUser() {
//這里直接寫(xiě)死admin,實(shí)際按需獲取
return new StringValue("admin");
}
@Override
public String getCreateUserColumn() {
return DataPermissionHandler.super.getCreateUserColumn();
}
@Override
public boolean ignoreTable(String tableName) {
//這是案例,多表需要過(guò)濾時(shí),可從配置文件或者static代碼塊中獲取
List<String> ignoreTables = Collections.singletonList("sys_model_relation");
//判斷當(dāng)前表是否在過(guò)濾列表中
return ignoreTables.stream().anyMatch(tableName::equalsIgnoreCase);
}
}));
return interceptor;
}
/**
* @description:
* @author: SmallNorth_Lee
* @date: 2024/5/7 15:29
* @version: 1.0
*/
public interface DataPermissionHandler {
/**
* 獲取用戶(hù) ID 值表達(dá)式,只支持單個(gè) ID 值
* <p>
*
* @return 用戶(hù) ID 值表達(dá)式
*/
Expression getCreateUser();
/**
* 獲取用戶(hù)字段名
* <p>
* 默認(rèn)字段名叫: create_user
*
* @return 用戶(hù)字段名
*/
default String getCreateUserColumn() {
return "create_user";
}
/**
* 根據(jù)表名判斷是否忽略拼接多用戶(hù)條件
* <p>
* 默認(rèn)都要進(jìn)行解析并拼接多用戶(hù)條件
*
* @param tableName 表名
* @return 是否忽略, true:表示忽略,false:需要解析并拼接多用戶(hù)條件
*/
default boolean ignoreTable(String tableName) {
return false;
}
/**
* 忽略插入用戶(hù)字段邏輯
*
* @param columns 插入字段
* @param createUserColumn 用戶(hù) ID 字段
* @return
*/
default boolean ignoreInsert(List<Column> columns, String createUserColumn) {
return columns.stream().map(Column::getColumnName).anyMatch(i -> i.equalsIgnoreCase(createUserColumn));
}
}
/**
* @description:
* @author: SmallNorth_Lee
* @date: 2024/5/7 14:14
* @version: 1.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class CustomLineInnerInterceptor extends BaseMultiTableInnerInterceptor implements InnerInterceptor {
private DataPermissionHandler dataPermissionHandler;
@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
if (InterceptorIgnoreHelper.willIgnoreTenantLine(ms.getId())) {
return;
}
PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
mpBs.sql(parserSingle(mpBs.sql(), null));
}
@Override
public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
MappedStatement ms = mpSh.mappedStatement();
SqlCommandType sct = ms.getSqlCommandType();
if (sct == SqlCommandType.INSERT || sct == SqlCommandType.UPDATE || sct == SqlCommandType.DELETE) {
if (InterceptorIgnoreHelper.willIgnoreTenantLine(ms.getId())) {
return;
}
PluginUtils.MPBoundSql mpBs = mpSh.mPBoundSql();
mpBs.sql(parserMulti(mpBs.sql(), null));
}
}
@Override
protected void processSelect(Select select, int index, String sql, Object obj) {
final String whereSegment = (String) obj;
processSelectBody(select.getSelectBody(), whereSegment);
List<WithItem> withItemsList = select.getWithItemsList();
if (!CollectionUtils.isEmpty(withItemsList)) {
withItemsList.forEach(withItem -> processSelectBody(withItem, whereSegment));
}
}
@Override
protected void processInsert(Insert insert, int index, String sql, Object obj) {
if (dataPermissionHandler.ignoreTable(insert.getTable().getName())) {
// 過(guò)濾退出執(zhí)行
return;
}
List<Column> columns = insert.getColumns();
if (CollectionUtils.isEmpty(columns)) {
// 針對(duì)不給列名的insert 不處理
return;
}
String createUserColumn = dataPermissionHandler.getCreateUserColumn();
if (dataPermissionHandler.ignoreInsert(columns, createUserColumn)) {
// 針對(duì)已給出租戶(hù)列的insert 不處理
return;
}
columns.add(new Column(createUserColumn));
// fixed gitee pulls/141 duplicate update
List<Expression> duplicateUpdateColumns = insert.getDuplicateUpdateExpressionList();
if (CollectionUtils.isNotEmpty(duplicateUpdateColumns)) {
EqualsTo equalsTo = new EqualsTo();
equalsTo.setLeftExpression(new StringValue(createUserColumn));
equalsTo.setRightExpression(dataPermissionHandler.getCreateUser());
duplicateUpdateColumns.add(equalsTo);
}
Select select = insert.getSelect();
if (select != null && (select.getSelectBody() instanceof PlainSelect)) { //fix github issue 4998 修復(fù)升級(jí)到4.5版本的問(wèn)題
this.processInsertSelect(select.getSelectBody(), (String) obj);
} else if (insert.getItemsList() != null) {
// fixed github pull/295
ItemsList itemsList = insert.getItemsList();
Expression createUser = dataPermissionHandler.getCreateUser();
if (itemsList instanceof MultiExpressionList) {
((MultiExpressionList) itemsList).getExpressionLists().forEach(el -> el.getExpressions().add(createUser));
} else {
List<Expression> expressions = ((ExpressionList) itemsList).getExpressions();
if (CollectionUtils.isNotEmpty(expressions)) {//fix github issue 4998 jsqlparse 4.5 批量insert ItemsList不是MultiExpressionList 了,需要特殊處理
int len = expressions.size();
for (int i = 0; i < len; i++) {
Expression expression = expressions.get(i);
if (expression instanceof RowConstructor) {
((RowConstructor) expression).getExprList().getExpressions().add(createUser);
} else if (expression instanceof Parenthesis) {
RowConstructor rowConstructor = new RowConstructor()
.withExprList(new ExpressionList(((Parenthesis) expression).getExpression(), createUser));
expressions.set(i, rowConstructor);
} else {
if (len - 1 == i) { // (?,?) 只有最后一個(gè)expre的時(shí)候才拼接tenantId
expressions.add(createUser);
}
}
}
} else {
expressions.add(createUser);
}
}
} else {
throw ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId");
}
}
/**
* update 語(yǔ)句處理
*/
@Override
protected void processUpdate(Update update, int index, String sql, Object obj) {
final Table table = update.getTable();
if (dataPermissionHandler.ignoreTable(table.getName())) {
// 過(guò)濾退出執(zhí)行
return;
}
ArrayList<UpdateSet> sets = update.getUpdateSets();
if (!CollectionUtils.isEmpty(sets)) {
sets.forEach(us -> us.getExpressions().forEach(ex -> {
if (ex instanceof SubSelect) {
processSelectBody(((SubSelect) ex).getSelectBody(), (String) obj);
}
}));
}
update.setWhere(this.andExpression(table, update.getWhere(), (String) obj));
}
/**
* delete 語(yǔ)句處理
*/
@Override
protected void processDelete(Delete delete, int index, String sql, Object obj) {
if (dataPermissionHandler.ignoreTable(delete.getTable().getName())) {
// 過(guò)濾退出執(zhí)行
return;
}
delete.setWhere(this.andExpression(delete.getTable(), delete.getWhere(), (String) obj));
}
/**
* 處理 insert into select
* <p>
* 進(jìn)入這里表示需要 insert 的表啟用了多租戶(hù),則 select 的表都啟動(dòng)了
*
* @param selectBody SelectBody
*/
protected void processInsertSelect(SelectBody selectBody, final String whereSegment) {
PlainSelect plainSelect = (PlainSelect) selectBody;
FromItem fromItem = plainSelect.getFromItem();
if (fromItem instanceof Table) {
// fixed gitee pulls/141 duplicate update
processPlainSelect(plainSelect, whereSegment);
appendSelectItem(plainSelect.getSelectItems());
} else if (fromItem instanceof SubSelect) {
SubSelect subSelect = (SubSelect) fromItem;
appendSelectItem(plainSelect.getSelectItems());
processInsertSelect(subSelect.getSelectBody(), whereSegment);
}
}
/**
* 追加 SelectItem
*
* @param selectItems SelectItem
*/
protected void appendSelectItem(List<SelectItem> selectItems) {
if (CollectionUtils.isEmpty(selectItems)) {
return;
}
if (selectItems.size() == 1) {
SelectItem item = selectItems.get(0);
if (item instanceof AllColumns || item instanceof AllTableColumns) {
return;
}
}
selectItems.add(new SelectExpressionItem(new Column(dataPermissionHandler.getCreateUserColumn())));
}
/**
* 租戶(hù)字段別名設(shè)置
* <p>tenantId 或 tableAlias.tenantId</p>
*
* @param table 表對(duì)象
* @return 字段
*/
protected Column getAliasColumn(Table table) {
StringBuilder column = new StringBuilder();
// todo 該起別名就要起別名,禁止修改此處邏輯
if (table.getAlias() != null) {
column.append(table.getAlias().getName()).append(StringPool.DOT);
}
column.append(dataPermissionHandler.getCreateUserColumn());
return new Column(column.toString());
}
@Override
public void setProperties(Properties properties) {
PropertyMapper.newInstance(properties).whenNotBlank("dataPermissionHandler",
ClassUtils::newInstance, this::setDataPermissionHandler);
}
/**
* 構(gòu)建租戶(hù)條件表達(dá)式
*
* @param table 表對(duì)象
* @param where 當(dāng)前where條件
* @param whereSegment 所屬M(fèi)apper對(duì)象全路徑(在原租戶(hù)攔截器功能中,這個(gè)參數(shù)并不需要參與相關(guān)判斷)
* @return 租戶(hù)條件表達(dá)式
* @see BaseMultiTableInnerInterceptor#buildTableExpression(Table, Expression, String)
*/
@Override
public Expression buildTableExpression(final Table table, final Expression where, final String whereSegment) {
if (dataPermissionHandler.ignoreTable(table.getName())) {
return null;
}
return new EqualsTo(getAliasColumn(table), dataPermissionHandler.getCreateUser());
}
}
2.2 使用DataPermissionInterceptor和MultiDataPermissionHandler
interceptor.addInnerInterceptor(new DataPermissionInterceptor(new MultiDataPermissionHandler() {
@Override
public Expression getSqlSegment(Table table, Expression where, String mappedStatementId) {
Column aliasColumn = getAliasColumn(table);
if (null == aliasColumn) {
return null;
}
return new EqualsTo(getAliasColumn(table), new StringValue(AuthUtils.getUser()));
}
}));
protected Column getAliasColumn(Table table) {
//這是案例,多表需要過(guò)濾時(shí),可從配置文件或者static代碼塊中獲取
List<String> ignoreTables = Collections.singletonList("sys_model_relation");
//判斷當(dāng)前表是否在過(guò)濾列表中
boolean match = ignoreTables.stream().anyMatch(table.getName()::equalsIgnoreCase);
if (match) {
return null;
}
StringBuilder column = new StringBuilder();
// todo 該起別名就要起別名,禁止修改此處邏輯
if (table.getAlias() != null) {
column.append(table.getAlias().getName()).append(StringPool.DOT);
}
column.append("create_user");
return new Column(column.toString());
}到此這篇關(guān)于MyBatisPlus數(shù)據(jù)權(quán)限控制實(shí)現(xiàn)的三種方式的文章就介紹到這了,更多相關(guān)MyBatisPlus權(quán)限控制內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring boot GC實(shí)現(xiàn)過(guò)程原理解析
這篇文章主要介紹了Spring boot GC實(shí)現(xiàn)過(guò)程原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
java編程FinalReference與Finalizer原理示例詳解
這篇文章主要為大家介紹了java編程FinalReference與Finalizer的核心原理以及示例源碼的分析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-01-01
SpringBoot+SseEmitter和Vue3+EventSource實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)推送
本文主要介紹了SpringBoot+SseEmitter和Vue3+EventSource實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)推送,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-03-03
基于apache poi根據(jù)模板導(dǎo)出excel的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇基于apache poi根據(jù)模板導(dǎo)出excel的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06
Java工具類(lèi)實(shí)現(xiàn)高效編寫(xiě)報(bào)表
對(duì)于報(bào)表數(shù)據(jù)大部分情況下使用寫(xiě)sql的方式為大屏/報(bào)表提供數(shù)據(jù)來(lái)源,但是對(duì)于某些復(fù)雜情況下僅僅使用sql無(wú)法實(shí)現(xiàn),這篇文章主要介紹了Java工具類(lèi)實(shí)現(xiàn)高效編寫(xiě)報(bào)表2022-11-11
Maven之遠(yuǎn)程倉(cāng)庫(kù)的配置詳解
這篇文章主要介紹了Maven之遠(yuǎn)程倉(cāng)庫(kù)的配置詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
screw?Maven插件方式運(yùn)行時(shí)在編譯打包時(shí)跳過(guò)執(zhí)行的問(wèn)題解決方法
這篇文章主要介紹了screw?Maven插件方式運(yùn)行時(shí)在編譯打包時(shí)跳過(guò)執(zhí)行的問(wèn)題解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03

