提交 | 用户 | 时间
|
722af2
|
1 |
package com.dl.common.helper; |
X |
2 |
|
|
3 |
import cn.dev33.satoken.context.SaHolder; |
|
4 |
import cn.dev33.satoken.context.model.SaStorage; |
|
5 |
import cn.hutool.core.util.ObjectUtil; |
|
6 |
import com.baomidou.mybatisplus.core.plugins.IgnoreStrategy; |
|
7 |
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper; |
|
8 |
import lombok.AccessLevel; |
|
9 |
import lombok.NoArgsConstructor; |
|
10 |
|
|
11 |
import java.util.HashMap; |
|
12 |
import java.util.Map; |
|
13 |
import java.util.function.Supplier; |
|
14 |
|
|
15 |
/** |
|
16 |
* 数据权限助手 |
|
17 |
* |
|
18 |
* @author Lion Li |
|
19 |
* @version 3.5.0 |
|
20 |
*/ |
|
21 |
@NoArgsConstructor(access = AccessLevel.PRIVATE) |
|
22 |
@SuppressWarnings("unchecked cast") |
|
23 |
public class DataPermissionHelper { |
|
24 |
|
|
25 |
private static final String DATA_PERMISSION_KEY = "data:permission"; |
|
26 |
|
|
27 |
public static <T> T getVariable(String key) { |
|
28 |
Map<String, Object> context = getContext(); |
|
29 |
return (T) context.get(key); |
|
30 |
} |
|
31 |
|
|
32 |
|
|
33 |
public static void setVariable(String key, Object value) { |
|
34 |
Map<String, Object> context = getContext(); |
|
35 |
context.put(key, value); |
|
36 |
} |
|
37 |
|
|
38 |
public static Map<String, Object> getContext() { |
|
39 |
SaStorage saStorage = SaHolder.getStorage(); |
|
40 |
Object attribute = saStorage.get(DATA_PERMISSION_KEY); |
|
41 |
if (ObjectUtil.isNull(attribute)) { |
|
42 |
saStorage.set(DATA_PERMISSION_KEY, new HashMap<>()); |
|
43 |
attribute = saStorage.get(DATA_PERMISSION_KEY); |
|
44 |
} |
|
45 |
if (attribute instanceof Map) { |
|
46 |
return (Map<String, Object>) attribute; |
|
47 |
} |
|
48 |
throw new NullPointerException("data permission context type exception"); |
|
49 |
} |
|
50 |
|
|
51 |
/** |
|
52 |
* 开启忽略数据权限(开启后需手动调用 {@link #disableIgnore()} 关闭) |
|
53 |
*/ |
|
54 |
public static void enableIgnore() { |
|
55 |
InterceptorIgnoreHelper.handle(IgnoreStrategy.builder().dataPermission(true).build()); |
|
56 |
} |
|
57 |
|
|
58 |
/** |
|
59 |
* 关闭忽略数据权限 |
|
60 |
*/ |
|
61 |
public static void disableIgnore() { |
|
62 |
InterceptorIgnoreHelper.clearIgnoreStrategy(); |
|
63 |
} |
|
64 |
|
|
65 |
/** |
|
66 |
* 在忽略数据权限中执行 |
|
67 |
* |
|
68 |
* @param handle 处理执行方法 |
|
69 |
*/ |
|
70 |
public static void ignore(Runnable handle) { |
|
71 |
enableIgnore(); |
|
72 |
try { |
|
73 |
handle.run(); |
|
74 |
} finally { |
|
75 |
disableIgnore(); |
|
76 |
} |
|
77 |
} |
|
78 |
|
|
79 |
/** |
|
80 |
* 在忽略数据权限中执行 |
|
81 |
* |
|
82 |
* @param handle 处理执行方法 |
|
83 |
*/ |
|
84 |
public static <T> T ignore(Supplier<T> handle) { |
|
85 |
enableIgnore(); |
|
86 |
try { |
|
87 |
return handle.get(); |
|
88 |
} finally { |
|
89 |
disableIgnore(); |
|
90 |
} |
|
91 |
} |
|
92 |
|
|
93 |
} |