1
zyy
2 days ago 9bb3ab4a3fb0b1d20dcc87979a19ca9625a4bfc8
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package com.yami.trading.admin.controller.sys;
 
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.trading.admin.controller.service.SysUserOperService;
import com.yami.trading.common.annotation.SysLog;
import com.yami.trading.common.domain.Result;
import com.yami.trading.common.exception.YamiShopBindException;
import com.yami.trading.common.util.DateUtils;
import com.yami.trading.common.util.GoogleAuthenticator;
import com.yami.trading.common.util.IPHelper;
import com.yami.trading.common.util.PageParam;
import com.yami.trading.security.common.util.SecurityUtils;
import com.yami.trading.security.common.enums.SysTypeEnum;
import com.yami.trading.security.common.manager.PasswordManager;
import com.yami.trading.security.common.manager.TokenStore;
import com.yami.trading.sys.constant.Constant;
import com.yami.trading.sys.dto.*;
import com.yami.trading.sys.model.SysRole;
import com.yami.trading.sys.model.SysUser;
import com.yami.trading.sys.model.UnbindingGoogleAuthModel;
import com.yami.trading.sys.service.SysRoleService;
import com.yami.trading.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
 
import javax.validation.Valid;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 系统用户
 */
@RestController
@CrossOrigin
@RequestMapping("/sys/user")
@Api(tags = "系统用户")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private PasswordManager passwordManager;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    SysUserOperService sysUserOperService;
 
    /**
     * 所有用户列表
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('sys:user:page')")
    @ApiOperation("用户列表")
    public ResponseEntity<IPage<SysUser>> page(String username, PageParam<SysUser> page) {
        IPage<SysUser> sysUserPage = sysUserService.page(page, new LambdaQueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(username), SysUser::getUsername, username).orderByDesc(SysUser::getCreateTime));
        Map<Long, SysRole> sysRoleMap = sysRoleService.list().stream().collect(Collectors.toMap(SysRole::getRoleId, SysRole -> SysRole));
        List<SysUser> users=new ArrayList<>();
        for (SysUser sysUser : sysUserPage.getRecords()) {
            List<Long> roleIds = sysRoleService.listRoleIdByUserId(sysUser.getUserId());
            List<String> roleNames = new ArrayList<>();
            if (sysUser.getUsername().equals("admin")){
                roleNames.add("超级管理员");
            }
            roleIds.forEach(rid -> {
                if (sysRoleMap.containsKey(rid)) {
                    roleNames.add(sysRoleMap.get(rid).getRoleName());
                }
            });
            sysUser.setRoleName(roleNames);
            if (!sysUser.getUsername().equals("root")){
                users.add(sysUser);
            }
        }
        sysUserPage.setRecords(users);
        return ResponseEntity.ok(sysUserPage);
    }
 
    /**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    @ApiOperation("获取登录的用户信息")
    public ResponseEntity<SysUserInfoDto> info() {
        SysUser sysUser = sysUserService.getSysUserById(SecurityUtils.getSysUser().getUserId());
        SysUserInfoDto sysUserInfoDto = new SysUserInfoDto();
        BeanUtils.copyProperties(sysUser, sysUserInfoDto);
        List<Long> roleIds = sysRoleService.listRoleIdByUserId(sysUser.getUserId());
        Map<Long, SysRole> sysRoleMap = sysRoleService.list().stream().collect(Collectors.toMap(SysRole::getRoleId, SysRole -> SysRole));
        List<String> roleNames = new ArrayList<>();
        if (sysUser.getUsername().equals("admin")||sysUser.getUsername().equals("root")){
            roleNames.add("超级管理员");
        }
        roleIds.forEach(rid -> {
            if (sysRoleMap.containsKey(rid)) {
                roleNames.add(sysRoleMap.get(rid).getRoleName());
            }
        });
        sysUserInfoDto.setRoleName(roleNames);
        return ResponseEntity.ok(sysUserInfoDto);
    }
 
    /**
     * 修改密码
     */
    @SysLog("修改密码")
    @PostMapping("/password")
    @ApiOperation(value = "修改密码")
    public ResponseEntity<String> password(@RequestBody @Valid UpdatePasswordDto param) {
        // 开源版代码,禁止用户修改admin 的账号密码
        // 正式使用时,删除此部分代码即可
        if (Objects.equals(1L, param.getId()) && StrUtil.isNotBlank(param.getNewPassword())) {
            throw new YamiShopBindException("禁止修改admin的账号密码");
        }
        SysUser sysUser = sysUserService.getSysUserById(param.getId());
        if (sysUser==null){
            throw  new YamiShopBindException("参数错误!");
        }
        String password = passwordManager.decryptPassword(param.getPassword());
        if (!passwordEncoder.matches(password, sysUser.getPassword())) {
            return ResponseEntity.badRequest().body("原密码不正确");
        }
        //新密码
        String newPassword = passwordEncoder.encode(passwordManager.decryptPassword(param.getNewPassword()));
//        更新密码
        sysUserService.updatePasswordByUserId(sysUser.getUserId(), newPassword);
        tokenStore.deleteAllToken(String.valueOf(SysTypeEnum.ADMIN.value()), String.valueOf(sysUser.getUserId()));
 
        //
        Long userId = SecurityUtils.getSysUser().getUserId();
        SysUser sysUser2 = sysUserService.getById(userId);
 
        String context = MessageFormat.format("{0},ip:{1},时间[{2}],修改系统用户密码:[{3}]",
                new Object[]{
                        sysUser2.getUsername(),
                        IPHelper.getIpAddr(),
                        DateUtils.dateToStr(new Date(), DateUtils.DF_yyyyMMddHHmmss),
                        sysUser.getUsername()
                });
 
        sysUserOperService.saveLog(sysUser2,sysUser2.getUsername(),context);
        //
 
        return ResponseEntity.ok().build();
    }
 
    /**
     * 修改资金密码
     */
    @SysLog("修改资金密码")
    @PostMapping("/updateSafePassword")
    @ApiOperation(value = "修改资金密码")
    public ResponseEntity<String> updateSafePassword(@RequestBody @Valid UpdateSafePasswordDto param) {
        SysUser sysUser = sysUserService.getSysUserById(param.getId());
        if (sysUser == null) {
            throw new YamiShopBindException("参数错误!");
        }
        String safePassword = passwordManager.decryptPassword(param.getSafePassword());
        sysUser.setSafePassword(passwordEncoder.encode(safePassword));
        sysUserService.updateById(sysUser);
 
        //
        Long userId = SecurityUtils.getSysUser().getUserId();
        SysUser sysUser2 = sysUserService.getById(userId);
 
        String context = MessageFormat.format("{0},ip:{1},时间[{2}],修改系统用户资金密码:[{3}]",
                new Object[]{
                        sysUser2.getUsername(),
                        IPHelper.getIpAddr(),
                        DateUtils.dateToStr(new Date(), DateUtils.DF_yyyyMMddHHmmss),
                        sysUser.getUsername()
                });
 
        sysUserOperService.saveLog(sysUser2,sysUser2.getUsername(),context);
        //
 
        return ResponseEntity.ok().build();
    }
 
    /**
     * 绑定谷歌验证码
     */
    @SysLog("绑定谷歌验证码")
    @PostMapping("/bindGoogleAuth")
    @ApiOperation(value = "绑定谷歌验证码")
    public Result<String> updateGoogleAuth(@RequestBody @Valid UpdateGoogleAuthDto param) {
        SysUser sysUser = sysUserService.getSysUserById(param.getId());
        if (sysUser == null) {
            throw new YamiShopBindException("参数错误!");
        }
        SysUser rootSysUser = sysUserService.getSysUserById(SecurityUtils.getSysUser().getUserId());
        long t = System.currentTimeMillis();
        GoogleAuthenticator ga = new GoogleAuthenticator();
        ga.setWindowSize(5);
        if (sysUserService.checkSuperGoogleAuthCode(param.getRootGoogleAuthCode())) {
            if (sysUser.isGoogleAuthBind()) {
                throw new YamiShopBindException("谷歌验证码已绑定!");
            }
            boolean userFlag = ga.check_code(param.getSecret(), Long.valueOf(param.getGoogleAuthCode()), t);
            if (!userFlag) {
                throw new YamiShopBindException("谷歌验证码错误!");
            }
            sysUser.setGoogleAuthBind(true);
            sysUser.setGoogleAuthSecret(param.getSecret());
            sysUser.setUpdateTime(new Date());
            sysUserService.updateById(sysUser);
 
            //
            Long userId = SecurityUtils.getSysUser().getUserId();
            SysUser sysUser2 = sysUserService.getById(userId);
 
            String context = MessageFormat.format("{0},ip:{1},时间[{2}],修改系统用户-绑定谷歌密码:[{3}]",
                    new Object[]{
                            sysUser2.getUsername(),
                            IPHelper.getIpAddr(),
                            DateUtils.dateToStr(new Date(), DateUtils.DF_yyyyMMddHHmmss),
                            sysUser.getUsername()
                    });
 
            sysUserOperService.saveLog(sysUser2,sysUser2.getUsername(),context);
            //
 
        } else {
            throw new YamiShopBindException("超级谷歌验证码错误!");
        }
        return Result.succeed();
    }
 
 
 
    @SysLog("解绑谷歌验证码")
    @PostMapping("/unbindingGoogleAuth")
    @ApiOperation(value = "解绑谷歌验证码")
    public Result unbindingGoogleAuth(@RequestBody @Valid UnbindingGoogleAuthModel param) {
        SysUser sysUser = sysUserService.getSysUserById(param.getId());
        if (sysUser == null) {
            throw new YamiShopBindException("参数错误!");
        }
        GoogleAuthenticator ga = new GoogleAuthenticator();
        ga.setWindowSize(5);
        if (sysUserService.checkSuperGoogleAuthCode(param.getRootGoogleAuthCode())) {
            if (!sysUser.isGoogleAuthBind()) {
                throw new YamiShopBindException("谷歌验证码未绑定,无需解绑!");
            }
            sysUser.setGoogleAuthBind(false);
            sysUser.setGoogleAuthSecret("");
            sysUser.setUpdateTime(new Date());
            sysUserService.updateById(sysUser);
 
            //
            Long userId = SecurityUtils.getSysUser().getUserId();
            SysUser sysUser2 = sysUserService.getById(userId);
 
            String context = MessageFormat.format("{0},ip:{1},时间[{2}],修改系统用户-解绑谷歌密码:[{3}]",
                    new Object[]{
                            sysUser2.getUsername(),
                            IPHelper.getIpAddr(),
                            DateUtils.dateToStr(new Date(), DateUtils.DF_yyyyMMddHHmmss),
                            sysUser.getUsername()
                    });
 
            sysUserOperService.saveLog(sysUser2,sysUser2.getUsername(),context);
            //
        } else {
            throw new YamiShopBindException("超级谷歌验证码错误!");
        }
        return Result.succeed();
    }
 
    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    @PreAuthorize("@pms.hasPermission('sys:user:info')")
    public ResponseEntity<SysUser> info(@PathVariable("userId") Long userId) {
        SysUser user = sysUserService.getSysUserById(userId);
        user.setUserId(null);
//        if (!Objects.equals(user.getShopId(), SecurityUtils.getSysUser().getShopId())) {
//            throw new YamiShopBindException("没有权限获取该用户信息");
//        }
        //获取用户所属的角色列表
        List<Long> roleIdList = sysRoleService.listRoleIdByUserId(userId);
        user.setRoleIdList(roleIdList);
        return ResponseEntity.ok(user);
    }
 
    /**
     * 保存用户
     */
    @SysLog("保存用户")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('sys:user:save')")
    @ApiOperation("保存用户")
    public Result save(@Valid @RequestBody SysUserDto user) {
        String username = user.getUsername();
        SysUser dbUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));
        if (dbUser != null) {
            throw new YamiShopBindException("该用户已存在!");
        }
        SysUser sysUser = new SysUser();
        sysUser.setPassword(passwordEncoder.encode(passwordManager.decryptPassword(user.getPassword())));
        sysUser.setRemarks(user.getRemarks());
        sysUser.setSafePassword(passwordEncoder.encode(passwordManager.decryptPassword(user.getSafePassword())));
        sysUser.setEmail(user.getEmail());
        sysUser.setRoleIdList(user.getRoleIdList());
        sysUser.setMobile(user.getMobile());
        sysUser.setUsername(username);
        sysUser.setStatus(user.getStatus());
        sysUserService.saveUserAndUserRole(sysUser);
 
        //
        Long userId = SecurityUtils.getSysUser().getUserId();
        SysUser sysUser2 = sysUserService.getById(userId);
 
        String context = MessageFormat.format("{0},ip:{1},时间[{2}],修改系统用户-保存用户:[{3}]",
                new Object[]{
                        sysUser2.getUsername(),
                        IPHelper.getIpAddr(),
                        DateUtils.dateToStr(new Date(), DateUtils.DF_yyyyMMddHHmmss),
                        JSONObject.toJSONString(sysUser)
                });
 
        sysUserOperService.saveLog(sysUser2,sysUser2.getUsername(),context);
        return Result.succeed();
    }
 
    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('sys:user:update')")
    @ApiOperation("修改用户")
    public Result update(@Valid @RequestBody UpdateSysUserDto dto) {
        SysUser dbUser = sysUserService.getSysUserById(dto.getId());
        if (dbUser == null) {
            throw new YamiShopBindException("参数错误!");
        }
//        SysUser dbUserNameInfo = sysUserService.getByUserName(dto.getUsername());
//        if (dbUserNameInfo != null && !Objects.equals(dbUserNameInfo.getUserId(),dto.getUserId())) {
//            return ResponseEntity.badRequest().body("该用户已存在");
//        }
        // 开源版代码,禁止用户修改admin 的账号密码密码
        // 正式使用时,删除此部分代码即可
        boolean is = Objects.equals(1L, dbUser.getUserId()) && !StrUtil.equals("admin", dbUser.getUsername());
        if (is) {
            throw new YamiShopBindException("禁止修改admin的账号密码");
        }
        if (Objects.equals(1L, dbUser.getUserId()) && dbUser.getStatus() == 0) {
            throw new YamiShopBindException("admin用户不可以被禁用");
        }
        dbUser.setPassword(passwordEncoder.encode(passwordManager.decryptPassword(dto.getPassword())));
        dbUser.setSafePassword(passwordEncoder.encode(passwordManager.decryptPassword(dto.getSafePassword())));
        dbUser.setRemarks(dto.getRemarks());
        dbUser.setEmail(dto.getEmail());
        dbUser.setRoleIdList(dto.getRoleIdList());
        dbUser.setStatus(dto.getStatus());
        dbUser.setMobile(dto.getMobile());
        dbUser.setRemarks(dto.getRemarks());
        sysUserService.updateUserAndUserRole(dbUser);
 
        Long userId = SecurityUtils.getSysUser().getUserId();
        SysUser sysUser2 = sysUserService.getById(userId);
 
        String context = MessageFormat.format("{0},ip:{1},时间[{2}],修改系统用户-修改用户:[{3}]",
                new Object[]{
                        sysUser2.getUsername(),
                        IPHelper.getIpAddr(),
                        DateUtils.dateToStr(new Date(), DateUtils.DF_yyyyMMddHHmmss),
                        JSONObject.toJSONString(dbUser)
                });
        sysUserOperService.saveLog(sysUser2,sysUser2.getUsername(),context);
        return Result.succeed();
    }
 
    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('sys:user:delete')")
    public Result delete(@RequestBody Long[] userIds) {
        if (userIds.length == 0) {
            throw new YamiShopBindException("请选择需要删除的用户");
        }
        if (ArrayUtil.contains(userIds, Constant.SUPER_ADMIN_ID)||ArrayUtil.contains(userIds, Constant.SUPER_ROOT_ID)) {
 
            throw new YamiShopBindException("系统管理员不能删除");
        }
        if (ArrayUtil.contains(userIds, SecurityUtils.getSysUser().getUserId())) {
            throw new YamiShopBindException("当前用户不能删除");
        }
        sysUserService.deleteBatch(userIds, SecurityUtils.getSysUser().getShopId());
        Long userId = SecurityUtils.getSysUser().getUserId();
        SysUser sysUser2 = sysUserService.getById(userId);
 
        String context = MessageFormat.format("{0},ip:{1},时间[{2}],修改系统用户-删除用户:[{3}]",
                new Object[]{
                        sysUser2.getUsername(),
                        IPHelper.getIpAddr(),
                        DateUtils.dateToStr(new Date(), DateUtils.DF_yyyyMMddHHmmss),
                        JSONObject.toJSONString(userIds)
                });
        sysUserOperService.saveLog(sysUser2,sysUser2.getUsername(),context);
        return Result.succeed();
    }
}