上下文实现

First Post:

Last Update:

Word Count:
189

Read Time:
1 min

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class UserContext {
//本地线程变量
private static final ThreadLocal<Holder> holder = ThreadLocal.withInitial(Holder::new);
//正则匹配资源路径
private static final Pattern RESOURCE_URI_PATTERN = Pattern.compile("^/api/resource/.+$");

@Data
public static class Holder {
private User user;
}

/**
* 设置当前用户
*
* @param user
*/
public static void setCurrentUser(User user) {
Holder holder = UserContext.holder.get();
holder.setUser(user);
}

/**
* 获取当前用户
*
* @return
*/
public static User getCurrentUser() {
return holder.get().getUser();
}

/**
* 判断当前用户的权限是否允许该资源
*
* @param authorityEnum 权限枚举
* @return
*/
public static boolean permission(AuthorityEnum authorityEnum) {
//检索对象是否为空
Objects.requireNonNull(authorityEnum, "权限枚举不能为null");
User user = holder.get().getUser();
return user.getAuthority() == authorityEnum.getAuthority();
}

public static boolean permission() {
User user = holder.get().getUser();
return !Objects.equals(user.getAuthority(), AuthorityEnum.GENERAL_USER.getAuthority());
}

public static void clear() {
//删除对应value对象
holder.remove();
}
}