xuefei
2020-12-10 eeeb7233935ea9b10e99043bdbf740ef86c9bf20
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package cn.cetc54.platform.core.common.utils;
 
import cn.cetc54.platform.core.common.constant.CommonConstant;
import cn.cetc54.platform.core.common.exception.PlatformException;
import cn.cetc54.platform.core.common.vo.PermissionDTO;
import cn.cetc54.platform.core.entity.Department;
import cn.cetc54.platform.core.entity.Role;
import cn.cetc54.platform.core.entity.User;
import cn.cetc54.platform.core.service.DepartmentService;
import cn.cetc54.platform.core.service.UserService;
import cn.cetc54.platform.core.service.mybatis.IUserRoleService;
import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
 
import java.util.*;
import java.util.concurrent.TimeUnit;
 
/**
 * @author
 */
@Component
public class SecurityUtil {
 
    @Autowired
    private UserService userService;
 
    @Autowired
    private IUserRoleService iUserRoleService;
 
    @Autowired
    private DepartmentService departmentService;
 
    @Autowired
    private StringRedisTemplate redisTemplate;
 
    /**
     * 获取当前登录用户
     * @return
     */
    public User getCurrUser(){
 
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if("anonymousUser".equals(principal.toString())){
            throw new PlatformException("未检测到登录用户");
        }
        UserDetails user = (UserDetails) principal;
        return userService.findByUsername(user.getUsername());
    }
 
    /**
     * 获取当前用户数据权限 null代表具有所有权限 包含值为-1的数据代表无任何权限
     */
    public List<String> getDeparmentIds(){
 
        List<String> deparmentIds = new ArrayList<>();
        User u = getCurrUser();
        // 读取缓存
        String key = "userRole::depIds:" + u.getId();
        String v = redisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(v)){
            deparmentIds = new Gson().fromJson(v, new TypeToken<List<String>>(){}.getType());
            return deparmentIds;
        }
        // 当前用户拥有角色
        List<Role> roles = iUserRoleService.findByUserId(u.getId());
        // 判断有无全部数据的角色
        Boolean flagAll = false;
        for(Role r : roles){
            if(r.getDataType()==null||r.getDataType().equals(CommonConstant.DATA_TYPE_ALL)){
                flagAll = true;
                break;
            }
        }
        // 包含全部权限返回null
        if(flagAll){
            return null;
        }
        // 每个角色判断 求并集
        for(Role r : roles) {
            if (r.getDataType().equals(CommonConstant.DATA_TYPE_UNDER)) {
                // 本部门及以下
                if (StrUtil.isBlank(u.getDepartmentId())) {
                    // 用户无部门
                    deparmentIds.add("-1");
                } else {
                    // 递归获取自己与子级
                    List<String> ids = new ArrayList<>();
                    getRecursion(u.getDepartmentId(), ids);
                    deparmentIds.addAll(ids);
                }
            } else if (r.getDataType().equals(CommonConstant.DATA_TYPE_SAME)) {
                // 本部门
                if (StrUtil.isBlank(u.getDepartmentId())) {
                    // 用户无部门
                    deparmentIds.add("-1");
                } else {
                    deparmentIds.add(u.getDepartmentId());
                }
            } else if (r.getDataType().equals(CommonConstant.DATA_TYPE_CUSTOM)) {
                // 自定义
                List<String> depIds = iUserRoleService.findDepIdsByUserId(u.getId());
                if (depIds == null || depIds.size() == 0) {
                    deparmentIds.add("-1");
                } else {
                    deparmentIds.addAll(depIds);
                }
            }
        }
        // 去重
        LinkedHashSet<String> set = new LinkedHashSet<>(deparmentIds.size());
        set.addAll(deparmentIds);
        deparmentIds.clear();
        deparmentIds.addAll(set);
        // 缓存
        redisTemplate.opsForValue().set(key, new Gson().toJson(deparmentIds), 15L, TimeUnit.DAYS);
        return deparmentIds;
    }
 
    private void getRecursion(String departmentId, List<String> ids){
 
        Department department = departmentService.get(departmentId);
        ids.add(department.getId());
        if(department.getIsParent()!=null&&department.getIsParent()){
            // 获取其下级
            List<Department> departments = departmentService.findByParentIdAndStatusOrderBySortOrder(departmentId, CommonConstant.STATUS_NORMAL);
            departments.forEach(d->{
                getRecursion(d.getId(), ids);
            });
        }
    }
 
    /**
     * 通过用户名获取用户拥有权限
     * @param username
     */
    public List<GrantedAuthority> getCurrUserPerms(String username){
 
        List<GrantedAuthority> authorities = new ArrayList<>();
        User user = userService.findByUsername(username);
        if(user==null||user.getPermissions()==null||user.getPermissions().isEmpty()){
            return authorities;
        }
        for(PermissionDTO p : user.getPermissions()){
            authorities.add(new SimpleGrantedAuthority(p.getTitle()));
        }
        return authorities;
    }
}