UserController.java 10.8 KB
package com.bsth.controller.sys;

import com.bsth.common.Constants;
import com.bsth.common.ResponseCode;
import com.bsth.controller.BaseController;
import com.bsth.controller.sys.dto.CompanyData;
import com.bsth.controller.sys.util.RSAUtils;
import com.bsth.entity.sys.CompanyAuthority;
import com.bsth.entity.sys.SysUser;
import com.bsth.security.util.SecurityUtils;
import com.bsth.service.sys.CompanyAuthorityService;
import com.bsth.service.sys.SysUserService;
import com.google.common.collect.ArrayListMultimap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("user")
public class UserController extends BaseController<SysUser, Integer> {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    SysUserService sysUserService;

    @Autowired
    CompanyAuthorityService companyAuthorityService;

    @RequestMapping(value = "/login/jCryptionKey")
    public Map<String, Object> jCryptionKey(HttpServletRequest request) {
        //公匙返回页面
        Map<String, Object> rs = new HashMap<>();
        rs.put("publickey", RSAUtils.generateBase64PublicKey());
        return rs;
    }

    //需要验证码的账号
    public static Map<String, Integer> captchaMap = new HashMap<>();

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, Object> login(HttpServletRequest request, @RequestParam String data, String captcha) {

        Map<String, Object> rs = new HashMap<>();
        rs.put("status", ResponseCode.ERROR);
        String userName="";
        String password="";
        try {
            HttpSession session = request.getSession();
            rs.put("captcha", session.getAttribute("captcha"));

            if (captchaMap.get(userName) != null && captchaMap.get(userName) >= 3) {
                //校验验证码
                String verCode = (String) session
                        .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

                if (StringUtils.isBlank(captcha))
                    return put(rs, "msg", "请输入验证码");

                if (!verCode.equals(captcha))
                    return put(rs, "msg", "验证码有误,请刷新后重新输入");
            }

            //解密RSA
            try {
                String userpwd=RSAUtils.decryptBase64(data);

                userName=userpwd.split("1q2a3d")[0];
                password=userpwd.split("1q2a3d")[1];
                logger.info(userName);
                logger.info(password);
            } catch (RuntimeException e) {
                return put(rs, "msg", "decrypt RSA fail!可能页面已过期,尝试刷新页面。");
            }

            SysUser user = sysUserService.findByUserName(userName);
            if (null == user)
                return put(rs, "msg", "不存在的用户");

            if (!user.isEnabled())
                return put(rs, "msg", "该用户已被锁定,请联系管理员");

            // 校验密码
            boolean matchStatus = new BCryptPasswordEncoder(4).matches(password, user.getPassword());
            if (!matchStatus) {
                rs.put("msg", "密码有误");

                Integer captchSize = captchaMap.get(userName);
                if (null == captchSize)
                    captchSize = 0;

                captchSize++;
                captchaMap.put(userName, captchSize);
                return rs;
            }

            // 登录
            SecurityUtils.login(user, request);
            //session里写入用户名,webSocket连接时标识身份用
            session.setAttribute(Constants.SESSION_USERNAME, user.getUserName());

            //获取公司权限数据
            List<CompanyAuthority> cmyAuths = companyAuthorityService.findByUser(user);
            session.setAttribute(Constants.COMPANY_AUTHORITYS, cmyAuths);

            captchaMap.remove(userName);
            rs.put("status", ResponseCode.SUCCESS);
        } catch (Exception e) {
            logger.error("", e);
            rs.put("msg", "服务器出现异常,请联系管理员");
        }
        return rs;
    }

    @RequestMapping(value = "/change_user", method = RequestMethod.POST)
    public Map<String, Object> changeUser(HttpServletRequest request, @RequestParam String userName,
                                          @RequestParam String password) {

        Map<String, Object> rs = new HashMap<>();
        rs.put("status", ResponseCode.ERROR);
        try {
            HttpSession session = request.getSession();

            SysUser user = sysUserService.findByUserName(userName);
            if (null == user)
                return put(rs, "msg", "不存在的用户");

            if (!user.isEnabled())
                return put(rs, "msg", "该用户已被锁定,请联系管理员");

            // 校验密码
            boolean matchStatus = new BCryptPasswordEncoder(4).matches(password, user.getPassword());
            if (!matchStatus)
                return put(rs, "msg", "密码有误");

            // 登录
            SecurityUtils.login(user, request);
            //session里写入用户名,webSocket连接时标识身份用
            session.setAttribute(Constants.SESSION_USERNAME, user.getUserName());

            //获取公司权限数据
            List<CompanyAuthority> cmyAuths = companyAuthorityService.findByUser(user);
            session.setAttribute(Constants.COMPANY_AUTHORITYS, cmyAuths);
            rs.put("status", ResponseCode.SUCCESS);
        } catch (Exception e) {
            logger.error("", e);
            rs.put("msg", "服务器出现异常,请联系管理员");
        }
        return rs;
    }

    /**
     * 返回当前用户的公司权限数据,用于构建页面级联下拉框
     *
     * @return
     */
    @RequestMapping("companyData")
    public List<CompanyData> companyData(HttpServletRequest request) {
        List<CompanyData> rs = new ArrayList<>();
        CompanyData companyData;

        ArrayListMultimap<String, CompanyAuthority> map = ArrayListMultimap.create();
        List<CompanyAuthority> cmyAuths = (List<CompanyAuthority>) request.getSession().getAttribute(Constants.COMPANY_AUTHORITYS);

        for (CompanyAuthority cAuth : cmyAuths) {
            map.put(cAuth.getCompanyCode() + "_" + cAuth.getCompanyName(), cAuth);
        }

        Set<String> keys = map.keySet();
        String[] temps;
        for (String k : keys) {
            temps = k.split("_");

            companyData = new CompanyData();
            companyData.setCompanyCode(temps[0]);
            companyData.setCompanyName(temps[1]);
            companyData.setChildren(new ArrayList<CompanyData.ChildrenCompany>());

            cmyAuths = map.get(k);
            for (CompanyAuthority c : cmyAuths) {
                companyData.getChildren().add(new CompanyData.ChildrenCompany(c.getSubCompanyCode(), c.getSubCompanyName()));
            }

            rs.add(companyData);
        }

        return rs;
    }

    @RequestMapping(value = "/login/captchaStatus")
    public int captchaStatus(String userName) {
        Integer size = captchaMap.get(userName);
        return size == null ? 0 : size;
    }

    public Map<String, Object> put(Map<String, Object> rs, String key, Object val) {
        rs.put(key, val);
        return rs;
    }

    /**
     * @Title: loginFailure @Description: TODO(查询登录失败的详细信息) @param @param
     * request @return String 返回类型 @throws
     */
    @RequestMapping("/loginFailure")
    public String loginFailure(HttpServletRequest request) {
        String msg = "";
        HttpSession session = request.getSession();

        Object obj = session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");

        if (obj instanceof BadCredentialsException)
            msg = "登录失败,用户名或密码错误.";
        else if (obj instanceof SessionAuthenticationException)
            msg = "登录失败,当前策略不允许重复登录.";
        session.removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        return msg;
    }

    @RequestMapping("/currentUser")
    public SysUser currentUser() {
        return SecurityUtils.getCurrentUser();
    }

    /**
     * @param id      用户ID
     * @param enabled 状态
     * @return
     * @Title changeEnabled
     * @Description: TODO(改变用户状态)
     */
    @RequestMapping("/changeEnabled")
    public int changeEnabled(@RequestParam int id, @RequestParam int enabled) {
        return sysUserService.changeEnabled(id, enabled);
    }

    /**
     * @param oldPWD  原始密码
     * @param newPWD  新密码
     * @param cnewPWD 确认新密码
     * @return
     * @Title changePWD
     * @Description: TODO(修改密码)
     */
    @RequestMapping(value = "/changePWD", method = RequestMethod.POST)
    public String changePWD(@RequestParam String oldPWD, @RequestParam String newPWD, @RequestParam String cnewPWD) {
        SysUser sysUser = SecurityUtils.getCurrentUser();
        String msg = "";
        if (new BCryptPasswordEncoder(4).matches(oldPWD, sysUser.getPassword())) {
            if (oldPWD.equals(newPWD)) {
                msg = "新密码不能跟原始密码一样!";
            } else {
                if (newPWD.equals(cnewPWD)) {
                    sysUserService.changePWD(sysUser.getId(), newPWD);
                    msg = "修改成功!";
                } else {
                    msg = "新密码两次输入不一致!";
                }
            }
        } else {
            msg = "原始密码错误!";
        }
        return msg;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Map<String, Object> register(SysUser u) {
        return sysUserService.register(u);
    }

    @RequestMapping(value = "/all_distinct")
    public List<SysUser> findAll_distinct() {
        return sysUserService.findAll_distinct();
    }
}