2021与蓝度共同重构项目,服务端
liuhaonan
2022-09-23 0f5b61e7faf30dce9281c913fae59aa9d05c61c4
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package com.sandu.ximon.admin.service;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Snowflake;
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.object.BaseConditionVO;
import com.sandu.common.service.impl.BaseServiceImpl;
import com.sandu.common.util.SpringContextHolder;
import com.sandu.ximon.admin.param.AdminParam;
import com.sandu.ximon.admin.param.PwdParam;
import com.sandu.ximon.admin.param.UserPwsParm;
import com.sandu.ximon.admin.security.SecurityUtils;
import com.sandu.ximon.admin.security.authcode.MD5Util;
import com.sandu.ximon.admin.utils.StoreOperationRecordsUtils;
import com.sandu.ximon.dao.bo.AdminBo;
import com.sandu.ximon.dao.bo.MenuNode;
import com.sandu.ximon.dao.domain.*;
import com.sandu.ximon.dao.enums.AdministratorEnums;
import com.sandu.ximon.dao.enums.OrderByEnums;
import com.sandu.ximon.dao.mapper.AdminMapper;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * @author chenjiantian
 * @date 2021/11/24 11:02
 */
@Service
@AllArgsConstructor
public class AdminService extends BaseServiceImpl<AdminMapper, Admin> {
 
    private final PasswordEncoder passwordEncoder;
    private final AdminRoleRelationService adminRoleRelationService;
    private final RoleService roleService;
    private AdminMapper adminMapper;
    private Snowflake snowflake;
 
    public Admin findByUserName(String username) {
        return getOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getUsername, username).last("limit 1"));
    }
 
    @Transactional(rollbackFor = Exception.class)
    public boolean register(AdminParam param) {
        Admin admin = findByUserName(param.getUsername());
        if (admin != null) {
            throw new BusinessException("当前账号" + param.getUsername() + "已经存在");
        }
        Admin save = new Admin();
        save.setId(snowflake.nextId());
        save.setUsername(param.getUsername());
        save.setPassword(passwordEncoder.encode(param.getPassword()));
        save.setNickName(param.getNickName());
        save.setMobile(param.getMobile());
        save.setNote(param.getNote());
        if (!save(save)) {
            throw new BusinessException("注册管理员失败");
        }
 
        Role role = roleService.getById(param.getRoleId());
        if (role == null) {
            throw new BusinessException("角色不存在");
        }
        if (RoleLevelStatus.SUPER.getCode().equals(role.getLevel())) {
            throw new BusinessException("无法添加超级管理员");
        }
 
        AdminRoleRelation adminRoleRelation = new AdminRoleRelation();
        adminRoleRelation.setAdminId(save.getId());
        adminRoleRelation.setRoleId(param.getRoleId());
        if (!adminRoleRelationService.save(adminRoleRelation)) {
            throw new BusinessException("添加管理员角色失败");
        }
 
        /**
         * 添加管理员日志记录开始
         */
        String content = "新注册管理员:" + param.getUsername();
        StoreOperationRecordsUtils.storeOperationData(null, null, "添加管理员", content);
        /**
         * 添加管理员日志记录结束
         */
        return true;
    }
 
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAdmin(Long adminId, AdminParam param) {
        Admin admin = getById(adminId);
        if (admin == null) {
            throw new BusinessException("找不到管理员");
        }
        List<Role> roles = roleService.listByAdminId(admin.getId());
        if (CollectionUtil.isEmpty(roles)) {
            throw new BusinessException("当前用户没有角色");
        }
        List<Integer> levels = roles.stream().map(Role::getLevel).collect(Collectors.toList());
        int min = Collections.min(levels);
        roleService.assertLevels(min);
 
        Admin update = new Admin();
        update.setId(adminId);
        update.setPassword(passwordEncoder.encode(param.getPassword()));
        update.setNickName(param.getNickName());
        update.setMobile(param.getMobile());
        update.setNote(param.getNote());
        if (!updateById(update)) {
            throw new BusinessException("编辑管理员失败");
        }
 
        adminRoleRelationService.remove(Wrappers.lambdaQuery(AdminRoleRelation.class).eq(AdminRoleRelation::getAdminId, admin.getId()));
        AdminRoleRelation adminRoleRelation = new AdminRoleRelation();
        adminRoleRelation.setAdminId(adminId);
        adminRoleRelation.setRoleId(param.getRoleId());
        if (!adminRoleRelationService.save(adminRoleRelation)) {
            throw new BusinessException("添加管理员角色失败");
        }
 
        return true;
    }
 
    /**
     * 修改当前登录用户密码
     *
     * @param param
     * @return
     */
    public boolean updateMyPassword(PwdParam param) {
        Long userId = SecurityUtils.getUserId();
        Admin admin = getById(userId);
        if (admin == null) {
            throw new BusinessException("用户不存在");
        }
        //判断旧密码与数据库是否一致
        if (passwordEncoder.matches(param.getOldPass(), admin.getPassword())) {
            //加密新密码
            admin.setId(userId);
            admin.setPassword(passwordEncoder.encode(param.getNewPass()));
            return updateById(admin);
        } else {
            throw new BusinessException("旧密码不正确,请重新确认密码!");
        }
    }
 
    /**
     * 修改管理员的密码
     *
     * @param param
     * @return
     */
    public boolean updateAdminPassword(UserPwsParm param) {
        Admin admin = getOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getId, param.getUserid()));
        if (admin == null) {
            throw new BusinessException("用户不存在");
        }
 
        //加密新密码
        admin.setPassword(passwordEncoder.encode(param.getNewPass()));
        return updateById(admin);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAdmin(Long adminId) {
        boolean flag = false;
        Admin admin = getById(adminId);
        if (admin == null) {
            throw new BusinessException("找不到管理员");
        }
        if (!AdministratorEnums.ADMIN.getCode().equals(SecurityUtils.getUserDetails().getAdministratorType())) {
            throw new BusinessException("只有超级管理员才能删除用户");
        }
 
        //管理员角色关系表
        AdminRoleRelationService adminRoleRelationService = SpringContextHolder.getBean(AdminRoleRelationService.class);
        //有用户必定有用户与角色的关系数据
        AdminRoleRelation one = adminRoleRelationService.getOne(Wrappers.lambdaQuery(AdminRoleRelation.class).eq(AdminRoleRelation::getAdminId, admin.getId()));
        Role role = SpringContextHolder.getBean(RoleService.class).getOne(Wrappers.lambdaQuery(Role.class).eq(Role::getId, one.getRoleId()));
        if (role == null) {
            throw new BusinessException("数据异常!");
        }
 
        if (role.getLevel().equals(RoleLevelStatus.SUPER.getCode())) {
            throw new BusinessException("超级管理员无法删除");
        } else {
            //删用户
            if (removeById(adminId)) {
                //删角色关系表信息
                flag = adminRoleRelationService.removeById(one);
                //删除失败回滚数据
                if (!flag) {
                    throw new BusinessException("删除管理员用户失败!");
                }
            }
        }
 
        /**
         * 删除管理员 日志记录开始
         */
        String content = "删除管理员:" + admin.getUsername() + "用户id:" + admin;
        StoreOperationRecordsUtils.storeOperationData(null, null, "删除管理员", content);
        /**
         * 删除管理员 日志记录结束
         */
 
        return flag;
    }
 
    /**
     * 修改超级管理员、管理员用户头像
     *
     * @param userId
     * @param IconUrl
     * @return
     */
    public boolean updateIcon(Long userId, String IconUrl) {
        Admin one = getOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getId, userId));
        if (one == null) {
            throw new BusinessException("用户不存在");
        }
        one.setIcon(IconUrl);
        return updateById(one);
    }
 
    public List<AdminBo> listAdmin(BaseConditionVO baseConditionVO, String keyword, Integer order, Integer seq) {
        //排序字段
        String orderByResult = OrderByEnums.ADMIN_ID.getCode();
        //正序、倒叙
        String orderBySeq = OrderByEnums.ASC.getCode();
        if (order != null) {
            switch (order) {
                case 1:
                    orderByResult = OrderByEnums.ADMIN_ID.getCode();
                    break;
                case 2:
                    orderByResult = OrderByEnums.ADMIN_CREATE_TIME.getCode();
                    break;
                case 3:
                    orderByResult = OrderByEnums.ADMIN_LOGIN_TIME.getCode();
                    break;
                default:
            }
        }
        if (seq != null) {
            switch (seq) {
                case 1:
                    orderBySeq = OrderByEnums.ASC.getCode();
                    break;
                case 2:
                    orderBySeq = OrderByEnums.DESC.getCode();
                    break;
                default:
                    break;
            }
        }
        //排序方式
        String orderBy = orderByResult + " " + orderBySeq;
 
        if (baseConditionVO != null) {
            PageHelper.startPage(baseConditionVO.getPageNo(), baseConditionVO.getPageSize(), orderBy);
        }
 
        return adminMapper.listAdmin(keyword);
    }
 
    /**
     * 获取用户权限列表地
     */
    public List<MenuNode> getUserPermissionList() {
        List<MenuNode> resultList;
        //通过用户UserID获取用户角色
        AdminRoleRelation one = SpringContextHolder.getBean(AdminRoleRelationService.class).
                getOne(Wrappers.lambdaQuery(AdminRoleRelation.class).eq(AdminRoleRelation::getAdminId, SecurityUtils.getUserId()));
        //判空
        if (one == null) {
            throw new BusinessException("该用户未绑定角色");
        }
 
        //通过RoleID获取MeunId列表
        List<RoleMenuRelation> menuIdList = SpringContextHolder.getBean(RoleMenuRelationService.class)
                .list(Wrappers.lambdaQuery(RoleMenuRelation.class).eq(RoleMenuRelation::getRoleId, one.getRoleId()));
 
        //判空
        if (menuIdList.isEmpty()) {
            return new ArrayList<>();
        }
        List<Long> menuIds = new ArrayList<>(menuIdList.size());
        for (RoleMenuRelation bean : menuIdList) {
            menuIds.add(bean.getMenuId());
        }
 
        resultList = SpringContextHolder.getBean(MenuService.class).getUserPermissionListById(menuIds);
 
        return resultList;
    }
 
 
    /**
     * 生成key
     *
     * @param userId
     * @return
     */
    public String creatUserKey(Long userId, Integer type) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空!");
        }
        //0:充重置key,1:获取key
        if (type == null || (type != 0 && type != 1)) {
            type = 1;
        }
 
        ClientService clientService = SpringContextHolder.getBean(ClientService.class);
        Client client = clientService.getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getId, userId));
        if (client == null) {
            throw new BusinessException("用户不存在,请重新确认!");
        }
 
        /**
         * key操作日志
         */
        String content = "操作用户key:" + SecurityUtils.getUsername() + "  被操作用户id:" + userId;
 
 
        //获取
        if (type == 1) {
            content += "操作类型:获取key";
            StoreOperationRecordsUtils.storeOperationData(null, null, "操作用户key", content);
            return "用户的便捷登录key为:" + client.getUserKey();
        } else {
            //更新
            String md5 = MD5Util.md5("uesrId:" + userId + "_AdministratorType:" + 2 + "time:" + System.currentTimeMillis());
            client.setUserKey(md5);
            boolean flag = clientService.updateById(client);
            if (flag) {
                content += "操作类型:生成key,新的key为:" + md5;
                StoreOperationRecordsUtils.storeOperationData(null, null, "操作用户key", content);
                return "生成便捷登录key成功,该用户key为:" + md5 + ",请妥善保管!";
            } else {
                throw new BusinessException("生成便捷登录key失败!");
            }
        }
    }
}