public Object login(User user,HttpSession session) throws Exception {
        String username = user.getUsername();
        String password = user.getPassword();
        if(!checkLock(session, username)) {
            throw new CustomException(StatusCode.ERROR_CODE,"该账号已被锁定");
        }
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)) {
            throw new CustomException(StatusCode.ERROR_CODE, "用户名和密码不能为空!");
        }
        User  u = getByUsername(username);
        if (u == null) {
            throw new CustomException(StatusCode.ERROR_CODE, "用户名不存在!");
        }
        if(!MD5Util.checkpassword(password, u.getPassword())) {
            //新增登录失败记录
            addFailNum(session, username);
            throw new CustomException(StatusCode.ERROR_CODE, "用户名或密码错误!");
        }
      //清空登录失败记录
        cleanFailNum(session, username);
 
    ......
}
/**
     * 校验用户登录失败次数
     * @param session
     * @param username
     * @return
     */
    public boolean checkLock(HttpSession session,String username) {
        Object o = session.getServletContext().getAttribute(username);
        if(o==null) {
            return true;
        }
        HashMap<String,Object> map  = (HashMap<String, Object>) o;
        int num  = (int) map.get("num");
        Date date = (Date) map.get("lastDate");
        long timeDifference = ((new Date().getTime()-date.getTime())/60/1000);
        if(num>=3&&timeDifference<30) {
            return false;
        }
        return true;
    }
    /**
     * 新增用户登录失败次数
     * @param session
     * @param username
     */
    public void addFailNum(HttpSession session, String username) {
        Object o = session.getServletContext().getAttribute(username);
        HashMap<String,Object> map = null;
        int num= 0;
        if(o==null) {
            map = new HashMap<String,Object>();
        }else {
            map  = (HashMap<String, Object>) o;
             num  = (int) map.get("num");
             Date date = (Date) map.get("lastDate");
             long timeDifference = ((new Date().getTime()-date.getTime())/60/1000);
             if(timeDifference>=30) {
                 num=0;
             }
        }
        map.put("num", num+1);
        map.put("lastDate", new Date());
        session.getServletContext().setAttribute(username, map);
    }
    /**
     * 清理用户登录失败的记录
     * @param session
     * @param username
     */
    public void cleanFailNum(HttpSession session, String username) {
        session.getServletContext().removeAttribute(username);
    }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐