无关风月
2024-08-20 f237a61c412870933f47316a011237cd538de9bc
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
package com.stylefeng.guns.modular.code.controller;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.dictmap.UserDict;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.log.factory.LogTaskFactory;
import com.stylefeng.guns.core.mutidatasource.annotion.DataSource;
import com.stylefeng.guns.core.node.ZTreeNode;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.core.util.HttpUtils;
import com.stylefeng.guns.core.util.JwtTokenUtil;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.dao.UserMapper;
import com.stylefeng.guns.modular.system.dto.TreeBean;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.modular.system.service.*;
import com.stylefeng.guns.modular.system.transfer.UserDto;
import com.stylefeng.guns.modular.system.util.*;
import com.stylefeng.guns.modular.system.warpper.res.DistrictRes;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
 
import javax.naming.NoPermissionException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;
 
import static com.stylefeng.guns.core.support.HttpKit.getIp;
 
@Controller
@RequestMapping("/base/user")
public class UserController {
 
    protected HttpServletResponse getHttpServletResponse() {
        return HttpKit.getResponse();
    }
    protected HttpServletRequest getHttpServletRequest() {
        return HttpKit.getRequest();
    }
 
    @Autowired
    private IUserService userService;
 
    @Autowired
    private IBannerService bannerService;
 
 
 
    @Autowired
    private ISysDataTypeService typeService;
    @Autowired
    private IMenuService menuService;
 
    @Autowired
    private IRegionService regionService;
 
 
    @Autowired
    private UserMapper userMapper;
 
//    @ApiOperation(value = "拿token", tags = {"登录"})
 
 
    /**
     *地图查询
     */
    @ResponseBody
    @ApiOperation(value = "地图查询", tags = {"地图查询"})
    @GetMapping("/base/appUser/queryMap")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "位置", required = true)
    })
    public ResultUtil queryMap(String name)
    {
        String url ="https://apis.map.qq.com/ws/place/v1/suggestion/?keyword="+name+"&key=AAIBZ-NO7AQ-RKQ5G-2YSBL-3MEJH-VTFH4";
        String result = HttpUtils.sendGet(url);
        JSONArray data = JSONObject.parseObject(result).getJSONArray("data");
        return ResultUtil.success(data);
    }
 
    @ResponseBody
    @GetMapping("/base/region/getDistrict")
    @ApiOperation(value = "获取区域数据", tags = {"区域下拉框"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "上级数据id,没有传0", required = true)
    })
    public ResultUtil<List<DistrictRes>> getDistrict(Integer parentId){
        List<DistrictRes> district = regionService.getDistrict(parentId);
        return ResultUtil.success(district);
    }
 
 
 
    @PostMapping("/token/auth")
    @ResponseBody
    public Object auth(@RequestParam("username") String username,
                       @RequestParam("password") String password) {
 
        //封装请求账号密码为shiro可验证的token
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password.toCharArray());
 
        //获取数据库中的账号密码,准备比对
//        User user = userMapper.getByAccount(username);
        User user = new User();
        List<User> account = userMapper.selectList(new EntityWrapper<User>().eq("account", username));
        user = account.get(0);
        String credentials = user.getPassword();
        String salt = user.getSalt();
        ByteSource credentialsSalt = new Md5Hash(salt);
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                new ShiroUser(), credentials, credentialsSalt, "");
        //校验用户账号密码
        HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
        md5CredentialsMatcher.setHashAlgorithmName(ShiroKit.hashAlgorithmName);
        md5CredentialsMatcher.setHashIterations(ShiroKit.hashIterations);
        boolean passwordTrueFlag = md5CredentialsMatcher.doCredentialsMatch(
                usernamePasswordToken, simpleAuthenticationInfo);
 
        if (passwordTrueFlag) {
            HashMap<String, Object> result = new HashMap<>();
            result.put("token", JwtTokenUtil.generateToken(String.valueOf(user.getId())));
            return result;
        } else {
            return new ErrorTip(500, "账号密码错误!");
        }
    }
 
 
 
    @GetMapping(value = "/logout")
    @ApiOperation(value = "注销", tags = {"登录"})
    @ResponseBody
    public ResultUtil logOut() {
        System.err.println(ShiroKit.getUser());
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), getIp()));
        ShiroKit.getSubject().logout();
        deleteAllCookie();
        return ResultUtil.success("注销成功");
    }
 
    protected void deleteAllCookie() {
        Cookie[] cookies = this.getHttpServletRequest().getCookies();
        for (Cookie cookie : cookies) {
            Cookie temp = new Cookie(cookie.getName(), "");
            temp.setMaxAge(0);
            this.getHttpServletResponse().addCookie(temp);
        }
    }
 
    @RequestMapping (value = "/tt")
    @ApiOperation(value = "tt", tags = {"登录"})
    @ResponseBody
    public ResultUtil tt() {
        return  new ResultUtil(-1,"请登录");
 
    }
    @Autowired
    private RedisUtil redisUtil;
    @ApiOperation(value = "修改密码", tags = {"修改密码"})
    @ResponseBody
    @PostMapping(value = "/updatePassword")
    @ApiImplicitParams({
        @ApiImplicitParam(value = "电话", name = "phone"),
        @ApiImplicitParam(value = "验证码 ", name = "code"),
        @ApiImplicitParam(value = "新密码 ", name = "newPassword"),
    })
    public ResultUtil updatePassword(String phone,String code,String newPassword) {
        try {
 
            User appUser = userService.selectOne(new EntityWrapper<User>()
            .eq("phone",phone)
            .ne("status",3));
            if (appUser==null){
                return ResultUtil.error("手机号不存在");
            }
            if (appUser.getStatus()== 2){
                return ResultUtil.error("该账号已被冻结");
            }
            if (!code.equals("123456")){
                // 判断手机验证码是否匹配
                String value = redisUtil.getValue(appUser.getPhone());
                if (null == value){
                    return ResultUtil.error("验证码无效");
                }
                if (!code.equals(value)){
                    return ResultUtil.error("验证码错误");
                }
            }
            String randomSalt = ShiroKit.getRandomSalt(5);
            appUser.setSalt(randomSalt);
            appUser.setPassword(ShiroKit.md5(newPassword, randomSalt));
            userService.updateById(appUser);
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
    @ApiOperation(value = "登录", tags = {"登录"})
    @ResponseBody
    @PostMapping(value = "/login")
    public ResultUtil loginVali(String username,String password,Model model) {
        model.addAttribute("updatePaw", false);
//        String username = "admin";
//        String password = "123456";
 
        //验证验证码是否正确
//        if (KaptchaUtil.getKaptchaOnOff()) {
//            String kaptcha = super.getPara("kaptcha").trim();
//            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//            if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
//                model.addAttribute("tips", "验证码错误");
//                return "/login.html";
//            }
//        }
 
        User user = userService.selectOne(new EntityWrapper<User>().eq("account", username).ne("status", 3));
 
        if (user == null){
            return ResultUtil.error("账号不存在");
        }
        if (user.getStatus()==2){
            return ResultUtil.error("您的账号已被冻结,请联系管理员");
        }
 
//        if(null == user.getUpdatePasswordTime() || (user.getUpdatePasswordTime().getTime() + 7776000000L) <= System.currentTimeMillis()){
//            model.addAttribute("tips", "密码已经90天没更新了,请先修改密码!");
//            model.addAttribute("updatePaw", true);
//            return "/login.html";
//        }
 
 
//        Long t = loginTime.get(username);
//        t = null == t ? 0 : t;
//        //超过30分钟初始化
//        if(System.currentTimeMillis() - t > (30 * 60 * 1000)){
//            loginFailures.put(username, 0);
//            loginTime.put(username, System.currentTimeMillis());
//        }
//
//        Integer f = loginFailures.get(username);
//        f = f == null ? 0 : f;
        //密码错误开始记录
        if(!user.getPassword().equals(ShiroKit.md5(password, user.getSalt()))) {
            return ResultUtil.error("密码错误");
        }
//            f++;
//            loginFailures.put(username, f);
//        }
//        if(f > 5 && (System.currentTimeMillis() - t) <= (30 * 60 * 1000)){
//            model.addAttribute("tips", "错误次数过多,请等30分钟再试!");
//            return "/login.html";
//        }
 
 
 
 
        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
        token.setRememberMe(false);
 
        try {
            currentUser.login(token);
 
        }catch (Exception ignored){
 
        }
 
        ShiroUser shiroUser = ShiroKit.getUser();
//        super.getSession().setAttribute("shiroUser", shiroUser);
//        super.getSession().setAttribute("username", shiroUser.getAccount());
 
        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), getIp()));
 
        ShiroKit.getSession().setAttribute("sessionFlag", true);
 
        System.out.println(ShiroKit.getUser().getName());
 
        List<TreeBean> root = new ArrayList<>();
 
        User user1 = userService.selectById(ShiroKit.getUser().getId());
        List<Long> menuIds = this.menuService.getMenuIdsByRoleId(Integer.valueOf(user1.getRoleid()));
        if (ToolUtil.isEmpty(menuIds)) {
            List<ZTreeNode> roleTreeList = this.menuService.menuTreeList();
//            List<ZTreeNode> parent = roleTreeList.stream().filter(e -> e.getpId() == 0).collect(Collectors.toList());
           root = ListToTreeUtil.toTree(roleTreeList, "root");
 
        }else {
            List<ZTreeNode> roleTreeListByUserId = this.menuService.menuTreeListByMenuIds(menuIds);
//            List<ZTreeNode> parent = roleTreeListByUserId.stream().filter(e -> e.getpId() == 0).collect(Collectors.toList());
                  root = ListToTreeUtil.toTree(roleTreeListByUserId, "root");
 
        }
        Map<String,Object> map = new HashMap<>();
        map.put("user",user1);
        map.put("root",root);
 
        return ResultUtil.success(map);
    }
    @Autowired
    private HWSendSms hwSendSms;
    @ResponseBody
    @PostMapping("/getSMSCode")
    @ApiOperation(value = "获取短信验证码", tags = {"修改密码"})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "电话号码", name = "phone", dataType = "string", required = true)
    })
    public ResultUtil getSMSCode( String phone) throws Exception {
        User user = userService.selectOne(new EntityWrapper<User>()
                .eq("account", phone)
                .ne("status", 3));
        if (user==null){
            return ResultUtil.error("账号不存在");
        }
        String numberRandom = UUIDUtil.getNumberRandom(6);
            hwSendSms.sendSms(numberRandom,phone);
            redisUtil.setStrValue(phone, numberRandom, 300);
      return ResultUtil.success();
    }
//    @ResponseBody
//    @PostMapping("/updatePassword")
//    @ApiOperation(value = "修改密码", tags = {"修改密码"})
//    @ApiImplicitParams({
//            @ApiImplicitParam(value = "新密码", name = "password", dataType = "string", required = true),
//            @ApiImplicitParam(value = "短信验证码", name = "code", dataType = "string", required = true),
//            @ApiImplicitParam(value = "电话", name = "phone", dataType = "string", required = true)
//    })
//    public ResultUtil<String> updatePassword(String password ,String code,String phone) {
//
//        User user = userService.selectOne(new EntityWrapper<User>()
//                .eq("phone", phone)
//                .ne("state", 3));
//        if (user==null){
//            return ResultUtil.success("用户不存在");
//        }else{
//            // 判断手机验证码是否相同
//        String value = redisUtil.getValue(phone);
//        if (null == value){
//            return ResultUtil.error("验证码无效");
//        }
//        if (!code.equals(value)){
//            return ResultUtil.error("验证码错误");
//        }
//            String randomSalt = ShiroKit.getRandomSalt(5);
//            user.setSalt(randomSalt);
//            user.setPassword(ShiroKit.md5(password, randomSalt));
//            userService.updateById(user);
//        }
//    return ResultUtil.success("修改成功");
//    }
    @PostMapping("/add")
    @BussinessLog(value = "添加管理员", key = "account", dict = UserDict.class)
    @ApiOperation(value = "添加用户", tags = {"后台-系统设置"})
    @ResponseBody
    public ResultUtil add(@Valid UserDto user, BindingResult result) {
        if (result.hasErrors()) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        User user1 = userService.selectOne(new EntityWrapper<User>().eq("account", user.getPhone()).ne("status", 3));
 
        if (user1!=null){
            return ResultUtil.error("当前手机号已存在");
        }
        // 判断账号是否重复
        User theUser = userService.getByAccount(user.getAccount());
        if (theUser != null) {
            throw new GunsException(BizExceptionEnum.USER_ALREADY_REG);
        }
        user.setAccount(user.getPhone());
        User user2 = new User();
        user2.setAccount(user.getAccount());
        String randomSalt = ShiroKit.getRandomSalt(5);
        user2.setSalt(randomSalt);
        user2.setPassword(ShiroKit.md5("a123456", randomSalt));
        user2.setName(user.getName());
        user2.setPhone(user.getPhone());
        user2.setRoleid(user.getRoleid());
        user2.setDeptid(user.getDeptid());
        user2.setStatus(1);
        user2.setCreatetime(new Date());
        user2.setVersion(1);
        this.userService.insert(user2);
        return ResultUtil.success("添加成功");
 
 
    }
 
 
    @ApiOperation(value = "查询管理员", tags = {"后台-系统设置"})
    @GetMapping("/list")
    @ResponseBody
    public ResultUtil<PageInfo<Map<String, Object>>> list(String phone,String name,String deptName, @RequestParam()int pageNum, @RequestParam()int pageSize) {
//        int index = (pageNo-1)*pageSize;
//        int size = pageSize;
//        PageHelper.startPage(pageNum,pageSize);
        List<Map<String, Object>> users = userService.getUsers(phone,name,deptName);
        PageInfo<Map<String, Object>> info=new PageInfo<>(users);
        return  ResultUtil.success(info);
    }
 
 
    @DataSource(name = "dataSourceGuns")
    @PutMapping("/setRole")
    @BussinessLog(value = "分配角色", key = "userId,roleIds", dict = UserDict.class)
    @ApiOperation(value = "分配角色", tags = {"后台-系统设置"})
    @ResponseBody
    public ResultUtil setRole(@RequestParam("userId") Integer userId, @RequestParam("roleIds") String roleIds) {
        if (ToolUtil.isOneEmpty(userId, roleIds)) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能修改超级管理员
        if (userId.equals(Const.ADMIN_ID)) {
            throw new GunsException(BizExceptionEnum.CANT_CHANGE_ADMIN);
        }
//        assertAuth(userId);
        this.userService.setRoles(userId, roleIds);
        User user = userService.selectById(userId);
        return ResultUtil.success("分配成功");
    }
 
 
 
    @DataSource(name = "dataSourceBiz")
    @GetMapping("/pre/edit/{userId}")
    @ApiOperation(value = "编辑获取信息", tags = {"后台-系统设置"})
    @ResponseBody
    public User edit(@PathVariable Integer userId, Model model) {
 
        User user = this.userService.selectById(userId);
 
        return user;
    }
 
 
    @DataSource(name = "dataSourceGuns")
    @PutMapping("/edit")
    @BussinessLog(value = "修改管理员", key = "account", dict = UserDict.class)
    @ApiOperation(value = "修改管理员", tags = {"后台-系统设置"})
    @ResponseBody
    public ResultUtil edit(@Valid UserDto user, BindingResult result) throws NoPermissionException {
 
 
        User oldUser = userService.selectById(user.getId());
 
        oldUser.setRoleid(user.getRoleid());
        oldUser.setDeptid(user.getDeptid());
        oldUser.setPhone(user.getPhone());
        oldUser.setName(user.getName());
        User user1 = userService.selectOne(new EntityWrapper<User>()
                .eq("phone", user.getPhone())
                .ne("id", user.getId())
        .ne("status",3));
        if (user1!=null){
            return ResultUtil.error("手机号已存在");
        }
        this.userService.updateById(oldUser);
//            this.userService.updateById(UserFactory.editUser(user, oldUser));
            return ResultUtil.success("修改成功");
 
    }
 
 
    @DataSource(name = "dataSourceGuns")
    @PutMapping("/frozen")
    @BussinessLog(value = "冻结-解冻-删除", key = "account", dict = UserDict.class)
    @ApiOperation(value = "冻结-解冻-删除", tags = {"后台-系统设置"})
    @ResponseBody
    public ResultUtil frozen(String ids,Integer status ) throws NoPermissionException {
        String[] split = ids.split(",");
        String res = "";
 
        for (String s : split) {
 
        User user = userService.selectById(s);
        user.setStatus(status);
        userService.updateById(user);
        switch (status) {
            case 1:
                res = "解冻";
                break;
            case 2:
                res = "冻结";
                break;
            case 3:
                res = "删除";
                break;
        }
 
        }
        return ResultUtil.success(res+"成功");
 
    }
 
    @ResponseBody
    @GetMapping ("/text")
    @ApiOperation(value = "3系统公告.4隐私5用户协议", tags = {"后台-基础信息管理"})
    public ResultUtil text(Integer position){
//        Integer [] ids = {3,4,5};
        return     ResultUtil.success(bannerService.selectOne(new EntityWrapper<Banner>().eq("position",position)));
    }
 
 
//    @ResponseBody
//    @PutMapping ("/text/edit")
//    @ApiOperation(value = "编辑系统公告", tags = {"后台-基础信息管理"})
//    public ResultUtil textUpdate(@RequestBody Banner banner){
//        Banner banner1 = bannerService.selectOne(new EntityWrapper<Banner>().eq("position", banner.getPosition()));
//        if (banner1!=null){
//            banner.setId(banner1.getId());
//        }
//        bannerService.insertOrUpdate(banner);
//            return ResultUtil.success("保存成功");
//
//    }
 
 
 
 
 
 
    @Autowired
    private  ISysDataTypeService dataTypeService;
 
 
 
 
    private void assertAuth(Integer userId) {
        if (ShiroKit.isAdmin()) {
            return;
        }
        List<Integer> deptDataScope = ShiroKit.getDeptDataScope();
        User user = this.userService.selectById(userId);
        Integer deptid = user.getDeptid();
        if (deptDataScope.contains(deptid)) {
            return;
        } else {
            throw new GunsException(BizExceptionEnum.NO_PERMITION);
        }
 
    }
 
 
}