44323
2024-04-23 16b704d18a875d1fb63827aaa507790ba2bef5be
guns-management/src/main/java/com/stylefeng/guns/modular/code/controller/UserController.java
@@ -1,35 +1,37 @@
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.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.Tip;
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.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.constant.state.ManagerStatus;
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.LogObjectHolder;
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.Host;
import com.stylefeng.guns.modular.system.dto.TreeBean;
import com.stylefeng.guns.modular.system.factory.UserFactory;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.modular.system.service.IBannerService;
import com.stylefeng.guns.modular.system.service.IEncyclopedicKnowledgeService;
import com.stylefeng.guns.modular.system.service.ISysDataTypeService;
import com.stylefeng.guns.modular.system.service.IUserService;
import com.stylefeng.guns.modular.system.service.*;
import com.stylefeng.guns.modular.system.transfer.UserDto;
import com.stylefeng.guns.modular.system.util.ResultUtil;
import com.stylefeng.guns.modular.system.warpper.UserWarpper;
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;
@@ -37,22 +39,21 @@
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import sun.security.util.Password;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.crypto.Data;
import java.util.*;
import static com.stylefeng.guns.core.support.HttpKit.getIp;
@@ -73,17 +74,53 @@
    @Autowired
    private IBannerService bannerService;
    @Autowired
    private IEncyclopedicKnowledgeService knowledgeService;
    @Autowired
    private ISysDataTypeService typeService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private UserMapper userMapper;
    @ApiOperation(value = "拿token", tags = {"登录"})
//    @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,
@@ -140,20 +177,62 @@
        }
    }
    @GetMapping(value = "/tt")
    @RequestMapping (value = "/tt")
    @ApiOperation(value = "tt", tags = {"登录"})
    @ResponseBody
    public void tt() {
        System.err.println(ShiroKit.getUser().getName());
    }
    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(Model model) {
    public ResultUtil loginVali(String username,String password,Model model) {
        model.addAttribute("updatePaw", false);
        String username = "admin";
        String password = "123456";
//        String username = "admin";
//        String password = "123456";
        //验证验证码是否正确
//        if (KaptchaUtil.getKaptchaOnOff()) {
@@ -167,6 +246,12 @@
        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天没更新了,请先修改密码!");
@@ -204,7 +289,12 @@
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
        token.setRememberMe(false);
//        currentUser.login(token);
        try {
            currentUser.login(token);
        }catch (Exception ignored){
        }
        ShiroUser shiroUser = ShiroKit.getUser();
//        super.getSession().setAttribute("shiroUser", shiroUser);
@@ -215,12 +305,80 @@
        ShiroKit.getSession().setAttribute("sessionFlag", true);
        System.out.println(ShiroKit.getUser().getName());
        return ResultUtil.success("1");
        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 = {"后台-系统设置"})
@@ -229,21 +387,30 @@
        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.setSalt(ShiroKit.getRandomSalt(5));
        user.setPassword(ShiroKit.md5(user.getPassword(), user.getSalt()));
        user.setStatus(ManagerStatus.OK.getCode());
        user.setCreatetime(new Date());
//        user.setVersion(1);
        this.userService.insert(UserFactory.createUser(user));
        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("添加成功");
@@ -253,11 +420,13 @@
    @ApiOperation(value = "查询管理员", tags = {"后台-系统设置"})
    @GetMapping("/list")
    @ResponseBody
    public Object list(String account, @RequestParam()int pageNo, @RequestParam()int pageSize,@RequestParam("1=平台管理员 2=员工") int version) {
        int index = (pageNo-1)*pageSize;
        int size = pageSize;
        List<Map<String, Object>> users = userService.getUsers(account,index,size,version);
        return users;
    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);
    }
@@ -285,6 +454,7 @@
    @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);
@@ -303,8 +473,19 @@
        User oldUser = userService.selectById(user.getId());
            this.userService.updateById(UserFactory.editUser(user, oldUser));
        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("修改成功");
    }
@@ -315,11 +496,15 @@
    @BussinessLog(value = "冻结-解冻-删除", key = "account", dict = UserDict.class)
    @ApiOperation(value = "冻结-解冻-删除", tags = {"后台-系统设置"})
    @ResponseBody
    public ResultUtil frozen(@RequestParam Integer userId,@RequestParam("1:解冻  2:冻结  3:删除") Integer status ) throws NoPermissionException {
        User user = userService.selectById(userId);
    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);
        String res = "";
        switch (status) {
            case 1:
                res = "解冻";
@@ -331,82 +516,42 @@
                res = "删除";
                break;
        }
        }
        return ResultUtil.success(res+"成功");
    }
    @ResponseBody
    @GetMapping ("/text")
    @ApiOperation(value = "3系统公告....", tags = {"后台-基础信息管理"})
    public List<Banner> text(){
        Integer [] ids = {3,4,5};
        return     bannerService.selectList(new EntityWrapper<Banner>().in("position",ids));
    @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(Banner banner){
            bannerService.insertOrUpdate(banner);
            return ResultUtil.success("保存成功");
    }
//    @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("保存成功");
//
//    }
    @ResponseBody
    @GetMapping ("/know/list")
    @ApiOperation(value = "列表", tags = {"后台-知识百科"})
    public List<EncyclopedicKnowledge> list(Integer type, String title,@RequestParam int pageNo,@RequestParam int pageSize){
        int index = (pageNo-1)*pageSize;
        int size = pageSize;
     return  knowledgeService.list(type,title,index,size);
    }
    @ResponseBody
    @GetMapping ("/know/select")
    @ApiOperation(value = "类型下拉框", tags = {"后台-知识百科"})
    public List<SysDataType> select(){
        return  typeService.getSysDataType(1);
    }
    @ResponseBody
    @PostMapping ("/know/add")
    @ApiOperation(value = "添加", tags = {"后台-知识百科"})
    public ResultUtil add(EncyclopedicKnowledge knowledge){
        knowledge.setInsertTime(new Date());
        knowledgeService.insert(knowledge);
        return ResultUtil.success("添加成功");
    }
    @ResponseBody
    @GetMapping  ("/know/pre/edit")
    @ApiOperation(value = "编辑获取信息", tags = {"后台-知识百科"})
    public EncyclopedicKnowledge preedit(Integer id){
        return knowledgeService.selectById(id);
    }
    @ResponseBody
    @PutMapping ("/know/edit")
    @ApiOperation(value = "修改", tags = {"后台-知识百科"})
    public ResultUtil edit(EncyclopedicKnowledge knowledge){
        knowledgeService.updateById(knowledge);
        return ResultUtil.success("修改成功");
    }
    @Autowired
    private  ISysDataTypeService dataTypeService;
    @ResponseBody
    @DeleteMapping  ("/know/delete")
    @ApiOperation(value = "编辑获取信息", tags = {"后台-知识百科"})
    public ResultUtil delete(Integer id){
         knowledgeService.deleteById(id);
         return ResultUtil.success("删除成功");
    }