⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 privilege.java

📁 源码/软件简介: 云网论坛1.1RC国际版是采用JSP开发的集论坛、CMS(网站内容管理系统)、博客、聊天室、商城、交友、语音灌水等于一体的门户式社区。拥有CWBBS ( Cloud Web BBS
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
            try {
                loginSaveDate = ParamUtil.getInt(req, "loginSaveDate");
            } catch (Exception e) {
            }
            int maxAge = -1;
            if (loginSaveDate == LOGIN_SAVE_NONE)
                maxAge = -1;
            else if (loginSaveDate == LOGIN_SAVE_DAY)
                maxAge = 60 * 60 * 24;
            else if (loginSaveDate == LOGIN_SAVE_MONTH)
                maxAge = 60 * 60 * 24 * 30;
            else if (loginSaveDate == LOGIN_SAVE_YEAR)
                maxAge = 60 * 60 * 24 * 365;
            // COOKIE都有一个有效期,有效期默认值为-1,这表示没有保存该COOKIE,当该浏览器退出时,该COOKIE立即失效.
            String c = this.encodeCookie(user.getName(), user.getPwdMd5());
            CookieBean cookiebean = new CookieBean();
            cookiebean.addCookie(res, COOKIE_CWBBS_AUTH, c, "/", maxAge);
            // 使用cookiebean.setCookieMaxAge不会产生效果,因为setCookieMaxAge从request中取COOKIE,然后设其到期值,但是此时request中尚没有发送过来的cookie
            // cookiebean.setCookieMaxAge(req, res, NAME, maxAge);
        }
        return isvalid;
    }

    /**
     * 验证码是否合法
     * @param req HttpServletRequest
     * @return boolean
     */
    public boolean isValidateCodeRight(HttpServletRequest request) {
        // 检测验证码
        String validateCode = ParamUtil.get(request, "validateCode");
        HttpSession session = request.getSession(true);
        String sessionCode = StrUtil.getNullStr((String) session.getAttribute(
                "validateCode"));
        if (!validateCode.equals(sessionCode))
            return false;
        else
            return true;
    }

    public boolean isValidateCodeRight(HttpServletRequest request, FileUpload fu) {
        // 检测验证码
        String validateCode = StrUtil.getNullString(fu.getFieldValue("validateCode"));
        HttpSession session = request.getSession(true);
        String sessionCode = StrUtil.getNullStr((String) session.getAttribute(
                "validateCode"));
        if (!validateCode.equals(sessionCode))
            return false;
        else
            return true;
    }

    /**
     * 此处需修改为加密COOKIE
     * @param req HttpServletRequest
     * @param res HttpServletResponse
     * @return boolean
     * @throws WrongPasswordException
     * @throws InvalidNameException
     * @throws ErrMsgException
     */
    public boolean login(HttpServletRequest req, HttpServletResponse res) throws
            WrongPasswordException, InvalidNameException, ErrMsgException {
        // 检测验证码
        Config cfg = new Config();
        if (cfg.getBooleanProperty("forum.loginUseValidateCode")) {
            if (!isValidateCodeRight(req))
                throw new ErrMsgException(LoadString(req, "err_validate_code"));
        }

        // 验证IP
        IPMonitor im = new IPMonitor();
        if (!im.isValid(req, StrUtil.getIp(req))) {
            throw new ErrMsgException(im.getMessage());
        }

        boolean isvalid = false;
        String name = ParamUtil.get(req, "name");
        if (name.equals("")) {
            throw new InvalidNameException(req);
        }
        String pwd = (String) req.getParameter("pwd");
        if (pwd == null) {
            throw new WrongPasswordException(req);
        }

        UserDb user = new UserDb();
        user = user.getUser(name);
        if (!user.isLoaded())
            throw new InvalidNameException(req);
        // 检查密码是否相符
        String MD5pwd = "";
        try {
            MD5pwd = SecurityUtil.MD5(pwd);
        } catch (Exception e) {
            logger.error("login MD5 exception: " +
                         e.getMessage());
        }
        if (!user.getPwdMd5().equals(MD5pwd))
            throw new WrongPasswordException(req);
        if (!user.isValid())
            throw new ErrMsgException(LoadString(req, "err_invalid"));
            // throw new ErrMsgException("对不起,您已被屏蔽!");
        // 检查是否被关进了监狱
        Prision prision = new Prision();
        if (prision.isUserArrested(name)) {
            Calendar cal = prision.getReleaseDate(name);
            String s = LoadString(req, "err_prision");
            s = s.replaceFirst("\\$d", ForumSkin.formatDate(req, cal.getTime()));
            throw new ErrMsgException(s); // "您已被关押在社区监狱中,释放日期为" + DateUtil.format(cal, "yy-MM-dd") + ",不能登录!");
        }

        // 取得登录前的用户名
        String oldname = getUser(req);

        // 判断是否已登录,即重复登录
        if (oldname.equals(name)) {
            return true;
        }

        isvalid = doLogin(req, res, user);

        return isvalid;
    }

    private static String encodeCookie(String username, String password) {
        StringBuffer buf = new StringBuffer();
        if (username != null && password != null) {
            byte[] bytes = (username + ENCODE_DELIMETER + password).getBytes();
            int b;

            for (int n = 0; n < bytes.length; n++) {
                b = bytes[n] ^ (ENCODE_XORMASK + n);
                buf.append((char) (ENCODE_CHAR_OFFSET1 + (b & 0x0F)));
                buf.append((char) (ENCODE_CHAR_OFFSET2 + ((b >> 4) & 0x0F)));
            }
        }
        return buf.toString();
    }

    private static String[] decodeCookie(String cookieVal) {
        // check that the cookie value isn't null or zero-length
        if (cookieVal == null || cookieVal.length() <= 0) {
            return null;
        }

        // unrafel the cookie value
        char[] chars = cookieVal.toCharArray();
        byte[] bytes = new byte[chars.length / 2];
        int b;
        for (int n = 0, m = 0; n < bytes.length; n++) {
            b = chars[m++] - ENCODE_CHAR_OFFSET1;
            b |= (chars[m++] - ENCODE_CHAR_OFFSET2) << 4;
            bytes[n] = (byte) (b ^ (ENCODE_XORMASK + n));
        }
        cookieVal = new String(bytes);
        int pos = cookieVal.indexOf(ENCODE_DELIMETER);
        String username = (pos < 0) ? "" : cookieVal.substring(0, pos);
        String password = (pos < 0) ? "" : cookieVal.substring(pos + 1);

        return new String[] {username, password};
    }

    /**
     * 登记访客,只放在listtopic.jsp及index.jsp,其余页面不放
     * @param request 请求.
     * @param response 响应.
     * @return void
     */
    public void enrolGuest(HttpServletRequest request, HttpServletResponse res) throws
            ErrMsgException, UserArrestedException {
        /**
         * zjrj.cn/index.jsp登录---->login.jsp--->/forum/index.jsp---->enrolGuest() refreshStayTime()
         * 王长江登录时发现 登录成功后,用户名在listtopic.jsp中看时变成了随机用户名,并且测试后发现
         * 该随机用户名是在refreshStayTime()时被create的,并且该随机用户于在线列表中还不是游客身份,说明"islogin"这个
         * cookie应该是被写入了,怀疑在login.jsp中因为<html><body>头的存在,可能使cookie未能及时写入
         * 而被重定向至index.jsp后,enrolGuest认为未被登记,而将其登记,而当5分钟后,refreshStayTime()时,islogin这个cookie
         * 已被写入,造成随机名称用户有非游客的身份出现在线列中有
         * 解决方法:将login.jsp中多余的<html><body>头去掉,将%> <%之间的换行及空格也去掉
         * 经检查,原来有可能是login.jsp中sendRedirect的问题 见http://dev.csdn.net/develop/article/6/6435.shtm
         */
        // 已经用会员身份登录了
        if (isUserLogin(request)) {
            HttpSession session = request.getSession(true);
            Authorization auth = (Authorization) session.getAttribute(
                    SESSION_CWBBS_AUTH);
            if (!auth.isArrestChecked()) { // 如果未检查过是否被捕
                // 检查其是否被捕,如果是的话,则强制其退出登录
                // 此检查只进行一次
                auth.setArrestChecked(true);
                Prision prision = new Prision();
                String userName = getUser(request);
                if (prision.isUserArrested(userName)) {
                    // 如果被捕,则撤销以前保存的登录信息
                    logout(request, res);

                    Calendar cal = prision.getReleaseDate(userName);

                    String s = LoadString(request, "err_prision");
                    s = s.replaceFirst("\\$d",
                                       ForumSkin.formatDate(request, cal.getTime()));
                    throw new ErrMsgException(s); // "您已被关押在社区监狱中,释放日期为" + DateUtil.format(cal, "yy-MM-dd") + ",不能登录!");
                } else // 未被捕,则退出函数
                    return;
            } else {
                // 已检查过是否被捕
                return;
            }
        }

        HttpSession session = request.getSession(true);
        Authorization auth = (Authorization) session.getAttribute(
                SESSION_CWBBS_AUTH);
        // 如果用户未登录,则检查是否已随机赋予name值
        if (auth != null)
            return; // name已记录则表示已被登记过
        String guestname = FileUpload.getRandName(); // "" + System.currentTieMillis();
        String boardcode = StrUtil.getNullString(ParamUtil.get(request,
                "boardcode"));

        // 在数据库中插入在线记录,置游客在位时间
        OnlineUserDb ou = new OnlineUserDb();
        int k = 0;
        boolean isGuestNameUsed = true;
        while (k < 10) {
            // 检查该用户名是否已被使用,防止重复
            ou = ou.getOnlineUserDb(guestname);
            // 未被使用,则退出
            if (!ou.isLoaded()) {
                isGuestNameUsed = false;
                break;
            } else {
                isGuestNameUsed = true;
                guestname = FileUpload.getRandName(); // "" + System.currentTimeMillis() + "f";
            }
            k++;
        }

        // 原来在forum/index.jsp中之所以不能写入cookie,可能与userservice.enrolGuest(request,response);
        // 在index.jsp中的位置有关,当位于网页的正文部分时,会不起作用,但listtopic.jsp放在body后一开始处却也是可以的
        // 将其移至index.jsp的首部时,cookie就能被写入了
        if (!isGuestNameUsed) {
            auth = new Authorization(guestname, true);
            session.setAttribute(SESSION_CWBBS_AUTH, auth);
            ou.setName(guestname);
            ou.setBoardCode(boardcode);
            ou.setGuest(true);
            ou.setIp(request.getRemoteAddr());
            ou.setCovered(false);
            ou.create();
        }
    }

    public Authorization getAuthorization(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        return (Authorization) session.getAttribute(SESSION_CWBBS_AUTH);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -