2021与蓝度共同重构项目,服务端
MercuryZ
2022-06-23 d0817418a1c0fc3d637cb3cb2a2fb7f8c1a42d0b
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package com.sandu.ximon.admin.service;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.UserInfo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.sandu.common.enums.RoleLevelStatus;
import com.sandu.common.execption.BusinessException;
import com.sandu.common.execption.EntityExistException;
import com.sandu.common.service.impl.BaseServiceImpl;
import com.sandu.common.util.BeanConvertUtil;
import com.sandu.ximon.admin.param.RoleParam;
import com.sandu.ximon.admin.security.SecurityUtils;
import com.sandu.ximon.dao.domain.*;
import com.sandu.ximon.dao.enums.AdministratorEnums;
import com.sandu.ximon.dao.mapper.MenuMapper;
import com.sandu.ximon.dao.mapper.RoleMapper;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author chenjiantian
 * @date 2021/4/25 19:15
 */
@Service
@AllArgsConstructor
public class RoleService extends BaseServiceImpl<RoleMapper, Role> {
 
    private final AdminRoleRelationService adminRoleRelationService;
    private final ClientRoleRelationService clientRoleRelationService;
    private final RoleMenuRelationService roleMenuRelationService;
    private final MenuService menuService;
    private final MenuMapper menuMapper;
 
 
    /**
     * 获取指定管理员的spring security权限认证列表
     */
    public Collection<GrantedAuthority> mapToGrantedAuthorities(Long adminId, boolean flag) {
        List<Role> roles;
        if (flag) {
            // 获取管理员的角色id
            roles = listByAdminId(adminId);
        } else {
            roles = listByClientId(adminId);
        }
 
        if (CollectionUtil.isEmpty(roles)) {
            throw new BusinessException("当前用户没有角色");
        }
        List<Long> roleIdList = roles.stream().map(Role::getId).collect(Collectors.toList());
        List<Long> menuIdList = roleMenuRelationService.list(Wrappers.lambdaQuery(RoleMenuRelation.class).in(RoleMenuRelation::getRoleId, roleIdList).select(RoleMenuRelation::getMenuId))
                .stream().map(RoleMenuRelation::getMenuId).distinct().collect(Collectors.toList());
 
        Set<String> menuPermissions = new HashSet<>();
        // 菜单权限
        if (CollectionUtil.isNotEmpty(menuIdList)) {
            List<Menu> menus = menuService.listByIds(menuIdList);
            Set<String> collect = menus.stream().filter(menu -> StrUtil.isNotBlank(menu.getPermission())).map(Menu::getPermission).collect(Collectors.toSet());
            menuPermissions.addAll(collect);
        }
 
        // 角色专属权限
        Set<String> rolePermissions = roles.stream().filter(role -> StrUtil.isNotBlank(role.getPermission())).map(Role::getPermission).collect(Collectors.toSet());
 
        menuPermissions.addAll(rolePermissions);
 
        return menuPermissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }
 
 
    /**
     * 获取某个管理员的角色列表
     */
    public List<Role> listByAdminId(Long adminId) {
        // 获取管理员的角色id
        List<AdminRoleRelation> list = adminRoleRelationService.list(Wrappers.lambdaQuery(AdminRoleRelation.class)
                .eq(AdminRoleRelation::getAdminId, adminId).select(AdminRoleRelation::getRoleId));
        List<Long> roleIdList = list.stream().map(AdminRoleRelation::getRoleId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(roleIdList)) {
            return null;
        }
        return listByIds(roleIdList);
    }
 
    /**
     * 获取某个普通用户的角色列表
     */
    public List<Role> listByClientId(Long clientId) {
        // 获取普通用户的角色id
        List<ClientRoleRelation> list = clientRoleRelationService.list(Wrappers.lambdaQuery(ClientRoleRelation.class).eq(ClientRoleRelation::getClientId, clientId).select(ClientRoleRelation::getRoleId));
        List<Long> roleIdList = list.stream().map(ClientRoleRelation::getRoleId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(roleIdList)) {
            return null;
        }
        return listByIds(roleIdList);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public boolean addRole(RoleParam param) {
        if (param.getMenuIdList().isEmpty()) {
            throw new BusinessException("权限参数异常");
        }
        Role role = new Role();
        role.setName(param.getName());
        role.setRemark(param.getRemark());
        //设置角色权限等级
        if (param.getLevel() != null) {
            if (param.getLevel().equals(RoleLevelStatus.SUPER.getCode())) {
                throw new BusinessException("无法添加超级管理员角色");
            } else if (param.getLevel().equals(RoleLevelStatus.COMMON.getCode())) {
                role.setLevel(RoleLevelStatus.COMMON.getCode());
            } else if (param.getLevel().equals(RoleLevelStatus.NORMAL.getCode())) {
                role.setLevel(RoleLevelStatus.NORMAL.getCode());
            } else if (param.getLevel().equals(RoleLevelStatus.NORMAL2.getCode())) {
                role.setLevel(RoleLevelStatus.NORMAL2.getCode());
            } else {
                role.setLevel(RoleLevelStatus.NORMAL.getCode());
            }
        } else {
            role.setLevel(RoleLevelStatus.NORMAL.getCode());
        }
 
        if (!save(role)) {
            throw new BusinessException("添加角色失败");
        }
 
        roleMenuRelationService.addRoleMenuList(role.getId(), param.getMenuIdList());
 
        return true;
    }
 
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRole(Long roleId, RoleParam param) {
        Role role = getById(roleId);
        if (role == null) {
            throw new BusinessException("找不到角色信息");
        }
        //判断是有权限修改
        assertLevels(role.getLevel());
 
        role.setName(param.getName());
        role.setRemark(param.getRemark());
 
        if (!role.getLevel().equals(RoleLevelStatus.SUPER.getCode())) {
            //设置角色权限等级
            if (param.getLevel() != null) {
                if (param.getLevel().equals(RoleLevelStatus.SUPER.getCode())) {
                    throw new BusinessException("无法修改成超级管理员角色");
                } else if (param.getLevel().equals(RoleLevelStatus.COMMON.getCode())) {
                    role.setLevel(RoleLevelStatus.COMMON.getCode());
                } else if (param.getLevel().equals(RoleLevelStatus.NORMAL.getCode())) {
                    role.setLevel(RoleLevelStatus.NORMAL.getCode());
                } else if (param.getLevel().equals(RoleLevelStatus.NORMAL2.getCode())) {
                    role.setLevel(RoleLevelStatus.NORMAL2.getCode());
                } else {
                    role.setLevel(RoleLevelStatus.NORMAL.getCode());
                }
            } else {
                role.setLevel(RoleLevelStatus.NORMAL.getCode());
            }
        } else if (!param.getLevel().equals(RoleLevelStatus.SUPER.getCode())) {
            throw new BusinessException("超级管理员角色等级无法修改!");
        }
 
 
        if (!updateById(role)) {
            throw new BusinessException("编辑角色失败");
        }
        roleMenuRelationService.remove(Wrappers.lambdaQuery(RoleMenuRelation.class).eq(RoleMenuRelation::getRoleId, roleId));
 
        roleMenuRelationService.addRoleMenuList(role.getId(), param.getMenuIdList());
        return true;
    }
 
 
    /**
     * 判断当前角色能不能操作目标用户 不行的话直接抛出异常
     *
     * @param roleLevel 目标用户的最高角色等级
     * @return 操作人的最高角色等级
     */
    public int assertLevels(Integer roleLevel) {
        Long userId = SecurityUtils.getUserId();
        List<Role> roles = listByAdminId(userId);
        if (CollectionUtil.isEmpty(roles)) {
            throw new BusinessException("当前用户没有角色");
        }
        List<Integer> levels = roles.stream().map(Role::getLevel).collect(Collectors.toList());
        int min = Collections.min(levels);
        if (roleLevel != null) {
            if (roleLevel < min) {
                throw new BusinessException("权限不足,你的角色级别:" + min + ",低于操作的角色级别:" + roleLevel);
            }
        }
        return min;
    }
 
    public boolean delRole(Long roleId) {
        Role role = getById(roleId);
        if (role == null) {
            throw new BusinessException("找不到角色");
        }
        //超级管理员不能删除
        if (RoleLevelStatus.SUPER.getCode().equals(role.getLevel())) {
            throw new BusinessException("当前角色为超级管理员,无法删除");
        }
 
        assertLevels(role.getLevel());
        List<AdminRoleRelation> list = adminRoleRelationService.list(Wrappers.lambdaQuery(AdminRoleRelation.class).eq(AdminRoleRelation::getRoleId, role));
        if (CollectionUtil.isNotEmpty(list)) {
            throw new BusinessException("当前角色有管理员使用,无法删除");
        }
        List<ClientRoleRelation> listClient = clientRoleRelationService.list(Wrappers.lambdaQuery(ClientRoleRelation.class).eq(ClientRoleRelation::getRoleId, role));
        if (CollectionUtil.isNotEmpty(listClient)) {
            throw new BusinessException("当前角色有用户使用,无法删除");
        }
        roleMenuRelationService.remove(Wrappers.lambdaQuery(RoleMenuRelation.class).eq(RoleMenuRelation::getRoleId, roleId));
        return removeById(roleId);
    }
 
    public List<RoleDetail> listRole(int pageNo, int pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<Long> roleIdList = list().stream().map(Role::getId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(roleIdList)) {
            return null;
        }
 
        List<RoleDetail> list = baseMapper.listRole(roleIdList);
 
        return list;
    }
}