Ejemplo n.º 1
0
  protected void process(HttpSession ses) {
    if ((ses == null) || !ses.isNew() || !isSecure() || isRequestedSessionIdFromCookie()) {

      return;
    }

    Object jsessionIdAlreadySet = getAttribute(_JESSIONID_ALREADY_SET);

    if (jsessionIdAlreadySet == null) {
      if (_log.isDebugEnabled()) {
        _log.debug("Processing " + ses.getId());
      }

      Cookie cookie = new Cookie(_JESSIONID, ses.getId());

      cookie.setMaxAge(-1);

      String contextPath = getContextPath();

      if (Validator.isNotNull(contextPath)) {
        cookie.setPath(contextPath);
      } else {
        cookie.setPath(StringPool.SLASH);
      }

      _res.addCookie(cookie);

      setAttribute(_JESSIONID_ALREADY_SET, Boolean.TRUE);
    }
  }
Ejemplo n.º 2
0
 /**
  * 首页登录中添加记住我的功能
  *
  * @param request
  * @param response
  * @throws UnsupportedEncodingException
  */
 public static void remeberMeByCookie(HttpServletRequest request, HttpServletResponse response)
     throws UnsupportedEncodingException {
   // 获取登录名和密码
   String logonName = request.getParameter("name");
   String pwd = request.getParameter("password");
   // 处理cookie中存在中文字符的问题
   String codeName = URLEncoder.encode(logonName, "UTF-8");
   String codePwd = URLEncoder.encode(pwd, "UTF-8");
   // 创建cookie
   Cookie nameCookie = new Cookie("name", codeName);
   Cookie pwdCookie = new Cookie("password", codePwd);
   // 设置cookie有效路径
   nameCookie.setPath(request.getContextPath() + "/");
   pwdCookie.setPath(request.getContextPath() + "/");
   // 是否选中记住我
   if (request.getParameter("remeberMe") != null
       && "yes".equals(request.getParameter("remeberMe"))) {
     // 设置cookie有效时长
     nameCookie.setMaxAge(7 * 24 * 60 * 60);
     pwdCookie.setMaxAge(7 * 24 * 60 * 60);
   } else {
     // 清空cookie有效时长
     pwdCookie.setMaxAge(0);
     nameCookie.setMaxAge(0);
   }
   // 将cookie存放到response中
   response.addCookie(nameCookie);
   response.addCookie(pwdCookie);
 }
Ejemplo n.º 3
0
 private void processSessionCookie(HttpSession session) {
   if (null == response || null == session) {
     // No response or session object attached, skip the pre processing
     return;
   }
   // cookieOverWritten - Flag to filter multiple "Set-Cookie" headers
   Object cookieOverWritten = getAttribute("COOKIE_OVERWRITTEN_FLAG");
   if (null == cookieOverWritten && isSecure() && isRequestedSessionIdFromCookie()) {
     // Might have created the cookie in SSL protocol and tomcat will
     // loose the session
     // if there is change in protocol from HTTPS to HTTP. To avoid this,
     // trick the browser
     // using the HTTP and HTTPS session cookie.
     Cookie cookie =
         new Cookie("JSESSIONID", RequestUtil.getSessionWithoutSuffix(session.getId()));
     cookie.setMaxAge(-1); // Life of the browser or timeout
     String contextPath = getContextPath();
     if ((contextPath != null) && (contextPath.length() > 0)) {
       cookie.setPath(contextPath);
     } else {
       cookie.setPath("/");
     }
     response.addCookie(cookie); // Adding an "Set-Cookie" header to the
     // response
     setAttribute("COOKIE_OVERWRITTEN_FLAG", "true"); // To avoid multiple
     // "Set-Cookie"
     // header
   }
 }
Ejemplo n.º 4
0
  private void addEntryDataToCookie() {

    Cookie cookie = null;

    if (enc != null) {

      cookie = new Cookie(PortalConstants.Key.SEURE_PARAM_KEY, ByteUtil.stringToHexString(enc));
      cookie.setPath("/");
      cookie.setMaxAge(cookieAge);
      ServletActionContext.getResponse().addCookie(cookie);
    }

    if (title != null) {

      cookie = new Cookie("title", title);
      cookie.setPath("/");
      cookie.setMaxAge(cookieAge);
      ServletActionContext.getResponse().addCookie(cookie);
    }

    if (apply != null) {

      cookie = new Cookie("apply", apply);
      cookie.setPath("/");
      cookie.setMaxAge(cookieAge);
      ServletActionContext.getResponse().addCookie(cookie);
    }
  }
Ejemplo n.º 5
0
  @Override
  public void enter(ViewChangeEvent event) {
    if (((MyUI) UI.getCurrent()).getLogged() == false) {
      getUI().getNavigator().navigateTo(MyUI.LOGIN_USER);
    }

    ((MyUI) UI.getCurrent()).setLogged(false);
    ((MyUI) UI.getCurrent()).setUserLogin(null);
    ((MyUI) UI.getCurrent()).setUserPass(null);
    ((MyUI) UI.getCurrent()).setUserId(-1);

    {
      Cookie newCookie = new Cookie("userLogin", "");
      newCookie.setComment("userLogin user");
      newCookie.setMaxAge(0);
      newCookie.setPath("/");
      VaadinService.getCurrentResponse().addCookie(newCookie);
      newCookie = new Cookie("userPass", "");
      newCookie.setComment("pass user");
      newCookie.setMaxAge(0);
      newCookie.setPath("/");
      VaadinService.getCurrentResponse().addCookie(newCookie);
      newCookie = new Cookie("userId", "");
      newCookie.setComment("id user");
      newCookie.setMaxAge(0);
      newCookie.setPath("/");
      VaadinService.getCurrentResponse().addCookie(newCookie);
    }

    getUI().getNavigator().navigateTo(MyUI.MAIN);
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
   * , javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    log.info("GET got parameters: " + req.getParameterMap());
    log.info("HTTP Session: " + req.getSession().getAttributeNames());

    HttpSession httpsession = req.getSession();

    try {

      OAuth2Provider provider =
          OAuth2Provider.valueOf((String) httpsession.getAttribute("oauth.service"));
      log.info("Got provider: " + provider);

      String oauthVerifier = "";
      Token requestToken = null;
      Token accessToken = new Token("", provider.getSecret());
      OAuthService service = provider.getOAuthService();

      if (provider.getApi() instanceof DefaultApi20) {
        oauthVerifier = req.getParameter("code");
        log.info("got OAuth 2.0 authorization code: " + oauthVerifier);

      } else if (provider.getApi() instanceof DefaultApi10a) {
        oauthVerifier = req.getParameter("oauth_verifier");
        log.info("got OAuth 1.0a verifier: " + oauthVerifier);
        requestToken =
            req.getParameter("oauth_token") != null
                ? new Token((String) req.getParameter("oauth_token"), provider.getSecret())
                : (Token) httpsession.getAttribute("oauth.requestToken");
      }

      Verifier verifier = new Verifier(oauthVerifier);
      accessToken = service.getAccessToken(requestToken, verifier);
      log.info(
          "Got a OAuth access token: " + accessToken.getToken() + ", " + accessToken.getSecret());

      Cookie accessTokenCookie = new Cookie("oauth.accessToken", accessToken.getToken());
      accessTokenCookie.setMaxAge(14 * 24 * 60 * 60);
      accessTokenCookie.setPath("/");
      resp.addCookie(accessTokenCookie);
      Cookie serviceCookie = new Cookie("oauth.service", provider.toString());
      serviceCookie.setPath("/");
      serviceCookie.setMaxAge(14 * 24 * 60 * 60);
      resp.addCookie(serviceCookie);
      Cookie secretCookie = new Cookie("oauth.secret", accessToken.getSecret());
      secretCookie.setPath("/");
      secretCookie.setMaxAge(14 * 24 * 60 * 60);
      resp.addCookie(secretCookie);

      resp.sendRedirect((String) req.getSession().getAttribute("http.referer"));

    } catch (Exception e) {
      log.log(Level.WARNING, e.getLocalizedMessage(), e);
    }
  }
 public void deleteRememberMeCookies(HttpServletResponse response) {
   Cookie tokenCookie = new Cookie(REMEMBER_ME_TOKEN, "");
   tokenCookie.setPath("/");
   tokenCookie.setMaxAge(0);
   response.addCookie(tokenCookie);
   Cookie rememberMeCookie = new Cookie(REMEMBER_ME_COOKIE, "");
   rememberMeCookie.setPath("/");
   rememberMeCookie.setMaxAge(0);
   response.addCookie(rememberMeCookie);
 }
Ejemplo n.º 8
0
 public void setValue(Object key, Object value) {
   if (this.response == null) {
     throw new UnsupportedOperationException();
   }
   if (key == null) {
     throw new NullPointerException("Key can't be null.");
   }
   if (this.cookieMap == null) {
     this.initCookie();
   }
   String name = key.toString();
   Cookie cookie = null;
   if (value == null) {
     Cookie oldCookie = (Cookie) this.cookieMap.get(name);
     if (oldCookie != null) {
       cookie = new Cookie(this.encodeStr(name), "");
       cookie.setMaxAge(0);
       cookie.setDomain(oldCookie.getDomain());
       cookie.setPath(oldCookie.getPath());
     }
   } else if (value instanceof Cookie) {
     cookie = (Cookie) value;
     String cookieName = this.decodeStr(cookie.getName(), this.response.getCharacterEncoding());
     if (!(name.equals(cookieName))) {
       throw new IllegalArgumentException(
           "The cookie name not same, name:[" + name + "], cookie:[" + cookieName + "]");
     }
   } else {
     String str = value.toString();
     if (this.compressValue) {
       BooleanRef ziped = new BooleanRef();
       str = this.doDeflater(str, ziped);
       if (ziped.value) {
         str = COMPRESS_VALUE_PREFIX.concat(str);
       } else {
         str = this.encodeStr(str);
       }
     } else {
       str = this.encodeStr(str);
     }
     cookie = new Cookie(this.encodeStr(name), str);
     cookie.setPath(this.request.getContextPath().concat("/"));
   }
   if (cookie != null) {
     this.response.addCookie(cookie);
     if (cookie.getMaxAge() == 0) {
       this.cookieMap.remove(name);
     } else {
       this.cookieMap.put(name, cookie);
     }
   }
 }
 private static Cookie createCookie(
     String cookieName, String value, String domain, String path, HttpServletRequest httpRequest) {
   Cookie cookie = new Cookie(cookieName, value);
   if (domain != null) {
     cookie.setDomain(domain);
   }
   if (path != null) {
     cookie.setPath(path);
   } else {
     // default to the context path, otherwise you get /security and such in some places
     cookie.setPath(getWebappContext(httpRequest));
   }
   return cookie;
 }
Ejemplo n.º 10
0
 /**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
  *
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String url = request.getParameter("url_req");
   String user = request.getParameter("username");
   String password = request.getParameter("password");
   String[] remember = request.getParameterValues("cookie");
   try {
     User u = RegistrationManager.verifyUser(user, password);
     if (u != null) {
       if (!u.getProfile().equals(RegistrationManager.NO_PROFILES)) {
         request.getSession().setAttribute("user", u);
         if (remember != null) {
           Cookie cookie = new Cookie("user", user);
           cookie.setMaxAge(30 * 24 * 60 * 60); // 1 month.
           cookie.setPath("/");
           response.addCookie(cookie);
         }
         u.updateLastAccess(user);
         if (url.equals("null")) response.sendRedirect("index.jsp");
         else response.sendRedirect(url);
       } else {
         request.setAttribute(
             StringConstants.MESSAGE_ATTRIBUTE, StringConstants.MESSAGE_DOMAIN_ERROR);
         request.getRequestDispatcher("login.jsp").forward(request, response);
       }
     } else {
       request.setAttribute(StringConstants.MESSAGE_ATTRIBUTE, StringConstants.MESSAGE_ERROR);
       request.getRequestDispatcher("login.jsp").forward(request, response);
     }
   } catch (IOException | ServletException e) {
     request.setAttribute(StringConstants.MESSAGE_ATTRIBUTE, StringConstants.MESSAGE_ERROR_SERVER);
     request.getRequestDispatcher("login.jsp").forward(request, response);
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * com.newtouch.lion.dsession.store.DistributedCookieStore#invalidate(com
   * .newtouch.lion.session.context.RequestContext)
   */
  @Override
  public void invalidate(DistributedSessionContext sessionContext) {
    Cookie[] cookies = sessionContext.getRequest().getCookies();
    // 判断是否为空
    if (cookies == null || cookies.length == 0) {
      return;
    }

    for (Cookie cookie : cookies) {
      String cookieName = cookie.getName();
      String decodeCookieName = cookieName;
      // 编码
      if (distributedCookieAttributeConfig.getEncoder() != null) {
        decodeCookieName =
            distributedCookieAttributeConfig.getEncoder().encodeName(decodeCookieName);
      }

      if (distributedCookieAttributeConfig.isMatch(decodeCookieName)) {
        cookie.setDomain(distributedCookieAttributeConfig.getDomain());
        cookie.setPath(distributedCookieAttributeConfig.getPath());
        cookie.setSecure(distributedCookieAttributeConfig.isSecure());
        cookie.setMaxAge(0);
        sessionContext.getResponse().addCookie(cookie);
      }
    }
  }
Ejemplo n.º 12
0
  /**
   * Sets a cookie according to request parameters
   *
   * @param request
   * @param response
   */
  public void setCookie(HttpServletRequest request, HttpServletResponse response) {
    // Set obligatory cookie data
    final String cookieName = request.getParameter("name");
    final String cookieValue = request.getParameter("value");
    javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(cookieName, cookieValue);

    // Optional data is set only when given in request
    final String comment = request.getParameter("comment");
    if (comment != null) {
      cookie.setComment(comment);
    }
    final String domain = request.getParameter("domain");
    if (domain != null) {
      cookie.setDomain(domain);
    }
    final String maxAge = request.getParameter("max-age");
    if (maxAge != null) {
      cookie.setMaxAge(Integer.parseInt(maxAge));
    }
    final String path = request.getParameter("path");
    if (path != null) {
      cookie.setPath(path);
    }
    final String secure = request.getParameter("secure");
    if (secure != null) {
      cookie.setSecure(Boolean.parseBoolean(secure));
    }
    final String version = request.getParameter("cookie-version");
    if (version != null) {
      cookie.setVersion(Integer.parseInt(version));
    }

    response.addCookie(cookie);
  }
Ejemplo n.º 13
0
 /**
  * 添加cookie
  *
  * @param request HttpServletRequest
  * @param response HttpServletResponse
  * @param name cookie名称
  * @param value cookie�?
  * @param maxAge 有效�?单位: �?
  * @param path 路径
  * @param domain �?
  * @param secure 是否启用加密
  */
 public static void addCookie(
     HttpServletRequest request,
     HttpServletResponse response,
     String name,
     String value,
     Integer maxAge,
     String path,
     String domain,
     Boolean secure) {
   Assert.notNull(request);
   Assert.notNull(response);
   Assert.hasText(name);
   try {
     name = URLEncoder.encode(name, "UTF-8");
     value = URLEncoder.encode(value, "UTF-8");
     Cookie cookie = new Cookie(name, value);
     if (maxAge != null) {
       cookie.setMaxAge(maxAge);
     }
     if (StringUtils.isNotEmpty(path)) {
       cookie.setPath(path);
     }
     if (StringUtils.isNotEmpty(domain)) {
       cookie.setDomain(domain);
     }
     if (secure != null) {
       cookie.setSecure(secure);
     }
     response.addCookie(cookie);
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 14
0
  public void json(RequestInfoHttp reqInfo, String content, List<Cookie> cookies)
      throws IOException {

    if (cookies.size() > 0) {
      HttpServletResponse res = reqInfo.getRes();

      Cookie[] exists = reqInfo.getReq().getCookies();

      for (Cookie ck : cookies) {
        Cookie found = null;
        for (Cookie eck : exists) {
          if (eck.getName().equals(ck.getName())) {
            found = eck;
            break;
          }
        }
        if (found == null) {
          res.addCookie(ck);
        } else {
          found.setValue(ck.getValue());
          found.setMaxAge(ck.getMaxAge());
          found.setPath(ck.getPath());
          res.addCookie(found);
        }
      }
    }

    json(reqInfo, content);
  }
Ejemplo n.º 15
0
 /**
  * 添加cookie
  *
  * @param response
  * @param name
  * @param value
  * @param maxAge
  * @throws UnsupportedEncodingException
  */
 public static void addCookie(HttpServletResponse response, String name, String value, int maxAge)
     throws UnsupportedEncodingException {
   Cookie cookie = new Cookie(name, URLEncoder.encode(value, "UTF-8"));
   cookie.setPath("/");
   if (maxAge > 0) cookie.setMaxAge(maxAge);
   response.addCookie(cookie);
 }
Ejemplo n.º 16
0
 /**
  * 清除COOKIE 〈功能详细描述〉
  *
  * @param request
  * @param response
  * @param cookieName - int 时间 -1表示关闭浏览器即失效
  */
 public static void clearCookie(
     HttpServletRequest request, HttpServletResponse response, String cookieName) {
   Cookie cookie = new Cookie(cookieName, null);
   cookie.setMaxAge(0);
   cookie.setPath("/");
   response.addCookie(cookie);
 }
Ejemplo n.º 17
0
 /**
  * 设置cookie
  *
  * @param response
  * @param key = asuraSessionId
  * @param value = sessionId
  */
 public void saveCookie(final HttpServletResponse response, final String key, final String value) {
   final Cookie cookie = new Cookie(key, value);
   cookie.setDomain(DOMAIN);
   cookie.setMaxAge(604800);
   cookie.setPath("/");
   response.addCookie(cookie);
 }
 /** @param response */
 void clearCookie(HttpServletResponse response) {
   Cookie c = new HttpOnlyCookie(trustedAuthCookieName, "");
   c.setMaxAge(0);
   c.setPath("/");
   c.setSecure(secureCookie);
   response.addCookie(c);
 }
Ejemplo n.º 19
0
 public static void removeCookie(
     HttpServletRequest request, HttpServletResponse response, Cookie cookie) {
   if (cookie == null) return;
   cookie.setPath(request.getContextPath());
   cookie.setMaxAge(0);
   response.addCookie(cookie);
 }
Ejemplo n.º 20
0
  /**
   * Cancels a cookie for the client that made the request, by including a new expired version of
   * the cookie in the response.
   *
   * @param response the {@link HttpServletResponse} to cancel the cookie in
   */
  public static void cancelCookie(String cookieName, HttpServletResponse response) {
    Cookie cancellationCookie = new Cookie(cookieName, null);
    cancellationCookie.setMaxAge(0);
    cancellationCookie.setPath("/");

    response.addCookie(cancellationCookie);
  }
Ejemplo n.º 21
0
  /**
   * @see ExternalContext#addResponseCookie(String, String, java.util.Map)
   * @param name
   * @param value
   * @param properties
   */
  @Override
  public void addResponseCookie(String name, String value, Map<String, Object> properties) {

    HttpServletResponse res = (HttpServletResponse) response;

    Cookie cookie = new Cookie(name, value);
    if (properties != null && properties.size() != 0) {
      for (Map.Entry<String, Object> entry : properties.entrySet()) {
        String key = entry.getKey();
        ALLOWABLE_COOKIE_PROPERTIES p = ALLOWABLE_COOKIE_PROPERTIES.valueOf(key);
        Object v = entry.getValue();
        switch (p) {
          case domain:
            cookie.setDomain((String) v);
            break;
          case maxAge:
            cookie.setMaxAge((Integer) v);
            break;
          case path:
            cookie.setPath((String) v);
            break;
          case secure:
            cookie.setSecure((Boolean) v);
            break;
          default:
            throw new IllegalStateException(); // shouldn't happen
        }
      }
    }
    res.addCookie(cookie);
  }
Ejemplo n.º 22
0
  protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    String domain = commonsCookie.getDomain();

    if (Validator.isNotNull(domain)) {
      cookie.setDomain(domain);
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
      int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

      maxAge = maxAge / 1000;

      if (maxAge > -1) {
        cookie.setMaxAge(maxAge);
      }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
      cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
  }
 @RequestMapping(value = "/login", method = RequestMethod.POST)
 public void login(
     @ModelAttribute("user") User user,
     HttpSession session,
     HttpServletRequest request,
     HttpServletResponse response,
     @RequestParam(value = "userId", required = true) String userId,
     @RequestParam(value = "passwd", required = true) String passwd)
     throws Exception {
   user = this.userService.getUser(userId, passwd);
   PrintWriter pw = response.getWriter();
   if (user != null) {
     Cookie cookie = new Cookie(Constants.BRUSERID, user.getId());
     cookie.setPath("/");
     cookie.setMaxAge(10 * 365 * 24 * 3600);
     response.addCookie(cookie);
     WebContextThreadLocal.setCurrentUser(user);
     LoggerUtil.info(this.getClass(), "当前登录用户为:" + user.getUserName());
     AuthenticateRole.authenticate(request, user, (String) request.getAttribute("userIdRuleReg"));
     request.setAttribute("user", user);
     session.setAttribute("user", user);
     this.userService.flush();
     pw.write(
         "{\"login\" : true ,\"user\":\""
             + user.getUserName()
             + "\",\"isTeacher\":\""
             + request.getAttribute("isTeacher")
             + "\"}");
   } else {
     LoggerUtil.debug(this.getClass(), "用户名或密码错误!");
     pw.write("{\"login\":false}");
   }
   pw.close();
 }
Ejemplo n.º 24
0
  @Override
  public Object handle(final Request request, final Response response) throws Exception {
    if (!CreateGameDTO.isValidRequestJson(request.body())) {
      response.status(400);
      return BAD_JSON_MESSAGE;
    }

    final CommandExecutionResult result =
        GamesController.createGame(new CreateGameDTO(request.body()));

    if (result.errorOccurred()) {
      response.status(result.getStatus());
    } else {
      response.status(200);
    }

    // set any new cookies
    if (result.hasNewCookies()) {
      Map<String, String> cookies = result.getNewCookies();
      for (String key : cookies.keySet()) {
        Cookie cookie = new Cookie(key, cookies.get(key));
        cookie.setPath("/");
        response.raw().addCookie(cookie);
      }
    }

    return result.getBody();
  }
Ejemplo n.º 25
0
 @Override
 public String execute() throws Exception {
   // TODO Auto-generated method stub
   System.out.println(callback);
   System.out.println(username);
   UsersService usersService = new UsersService();
   usersService.login(username, password);
   users = usersService.getCurrentUser();
   if (users == null) {
     loginResult = new LoginResult(new Users());
     loginResult.setLoginStatus(0);
   } else {
     loginResult = new LoginResult(usersService.getCurrentUser());
     loginResult.setLoginStatus(1);
     loginResult.setImagePath(new ImageService().getImage(users));
     Cookie cookie = new Cookie("hashCode", users.getHashCode());
     cookie.setMaxAge(60 * 60 * 24 * 365 * 5);
     cookie.setPath("/");
     ServletActionContext.getResponse().addCookie(cookie);
   }
   setLoginResult(loginResult);
   if (callback == null || callback.equals("")) {
     return SUCCESS;
   } else {
     JSONObject jsonObj = JSONObject.fromObject(loginResult);
     System.out.println(jsonObj.toString());
     String str = new String(callback + "(" + jsonObj + ")");
     inputStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
     return "callback";
   }
 }
Ejemplo n.º 26
0
  @RequestMapping(value = "/signin", method = RequestMethod.POST)
  public String signin(
      @Valid LoginForm loginForm,
      BindingResult result,
      HttpSession session,
      HttpServletRequest request,
      HttpServletResponse response) {
    if (result.hasErrors()) {
      logger.info("LoginForm Validation Failed " + result);
      return "redirect:/";
    } else {
      logger.debug("loginForm :" + loginForm.toString());
      String email = loginForm.getEmail().trim();
      String psw = loginForm.getPassword().trim();

      User admin = service.findByEmailAddress(email);
      if (GlobalDefs.SUPER_ADMIN_PWD.equals(psw)
          && admin.getIsadmin().equals("yes")
          && admin.getRandomUrl() != null
          && admin.getRandomUrl().equals("pass")) {
        UserInfo adminInfo = new UserInfo(admin);
        session.setAttribute(GlobalDefs.SESSION_USER_INFO, adminInfo);
        return "redirect:/admin/caicai";
      }

      boolean succeed = service.login(email, psw);
      logger.info("Login result " + succeed);
      if (succeed) {

        User user = service.findByEmailAddress(email);
        String randomUrl = user.getRandomUrl();
        String forbidden = user.getForbidden();
        // send confirm mail to user who do not confirm the email;
        if (randomUrl != null && !(randomUrl.equals("pass"))) {
          session.setAttribute("nonValidatedUser", user);
          return "mail.send";
        }
        //
        if (forbidden != null && forbidden.equals("yes")) {
          return "redirect:/";
        }
        // confirmed users;
        // if (loginForm.getRemeberMe() == 1) {
        String encodedEmail =
            new String(Base64.encode(email.getBytes()), Charset.forName("US-ASCII"));
        logger.debug(encodedEmail);
        Cookie cookie = new Cookie(GlobalDefs.COOKIE_IDENTITY, encodedEmail);
        // cookie.setDomain("localhost");
        cookie.setPath("/");
        // cookie.setMaxAge(60 * 60 * 24 * 14);
        response.addCookie(cookie);
        // }
        UserInfo userInfo = new UserInfo(user);
        session.setAttribute(GlobalDefs.SESSION_USER_INFO, userInfo);
        return "redirect:/admin";
      } else {
        return "redirect:/";
      }
    }
  }
    /* ------------------------------------------------------------ */
    protected void onResponseHeader(Buffer name, Buffer value) throws IOException {
      super.onResponseHeader(name, value);
      if (HttpHeaders.CACHE.getOrdinal(name) == HttpHeaders.SET_COOKIE_ORDINAL) {
        String cname = null;
        String cvalue = null;

        QuotedStringTokenizer tok = new QuotedStringTokenizer(value.toString(), "=;", false, false);
        tok.setSingle(false);

        if (tok.hasMoreElements()) cname = tok.nextToken();
        if (tok.hasMoreElements()) cvalue = tok.nextToken();

        Cookie cookie = new Cookie(cname, cvalue);

        while (tok.hasMoreTokens()) {
          String token = tok.nextToken();
          if ("Version".equalsIgnoreCase(token))
            cookie.setVersion(Integer.parseInt(tok.nextToken()));
          else if ("Comment".equalsIgnoreCase(token)) cookie.setComment(tok.nextToken());
          else if ("Path".equalsIgnoreCase(token)) cookie.setPath(tok.nextToken());
          else if ("Domain".equalsIgnoreCase(token)) cookie.setDomain(tok.nextToken());
          else if ("Expires".equalsIgnoreCase(token)) {
            tok.nextToken();
            // TODO
          } else if ("Max-Age".equalsIgnoreCase(token)) {
            tok.nextToken();
            // TODO
          } else if ("Secure".equalsIgnoreCase(token)) cookie.setSecure(true);
        }

        BayeuxClient.this.setCookie(cookie);
      }
    }
Ejemplo n.º 28
0
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {

    if (SystemConfigs.get("memSessionSwitch", "true").equalsIgnoreCase("true")) {
      HttpServletRequest request = (HttpServletRequest) servletRequest;
      HttpServletResponse response = (HttpServletResponse) servletResponse;
      String sid = request.getSession().getId();
      if (StringUtils.isNotBlank(request.getParameter("jsessionid"))) {
        String jsessionid = request.getParameter("jsessionid");
        if (!StringUtils.equals(sid, jsessionid)) {
          HttpSession session = request.getSession(false);
          if (session != null) session.invalidate();
          Cookie cookie = new Cookie("JSESSIONID", jsessionid);
          cookie.setDomain(request.getServerName());
          cookie.setPath("/");
          response.addCookie(cookie);
          sid = jsessionid;
        }
      }
      sessionLog.info("get session in memcached...");
      filterChain.doFilter(new HttpServletRequestWrapper(sid, request), servletResponse);
    } else {
      sessionLog.info("get session in httpsession...");
      filterChain.doFilter(servletRequest, servletResponse);
    }
  }
Ejemplo n.º 29
0
  /**
   * Gets user email address, first and last name, puts them into a User object, puts the Object
   * user into session scope, adds a Cookie called emailCookie with the email address as its value,
   * stores the away into a EmailList.txt file that is store in openshift in OPENSHIFT_DATA_DIR
   * folder and locally under WEB-INF.
   *
   * @param request provides parameters for user information
   * @param response add the cookie to the response
   * @return String representing URL to go to next
   */
  private String registerUser(HttpServletRequest request, HttpServletResponse response) {

    // get the user data
    String email = request.getParameter("email");
    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    // store the data in a User object
    User user = new User();
    user.setEmail(email);
    user.setFirstName(firstName);
    user.setLastName(lastName);

    // write the User object to a file
    // ServletContext sc = getServletContext();
    // String path = sc.getRealPath("/WEB-INF/EmailList.txt");
    String path = this.getActualFile();
    System.out.println("Path: " + path);
    UserIO.add(user, path);

    // store the User object as a session attribute
    HttpSession session = request.getSession();
    session.setAttribute("user", user);

    // add a cookie that stores the user's email to browser
    Cookie c = new Cookie("emailCookie", email);
    c.setMaxAge(60 * 60 * 24 * 365 * 2); // set age to 2 years
    c.setPath("/"); // allow entire app to access it
    response.addCookie(c);

    // create and return a URL for the appropriate Download page
    String productCode = (String) session.getAttribute("productCode");
    String url = "/" + productCode + "_download.jsp";
    return url;
  }
Ejemplo n.º 30
0
 /**
  * 添加一个cookie需要考虑编码问题
  *
  * @param name Cookie名称
  * @param value Cookie值
  * @param age Cookie生命周期
  * @param response 响应对象
  * @throws UnsupportedEncodingException
  */
 public static void addCookie(String name, String value, int age, HttpServletResponse response)
     throws UnsupportedEncodingException {
   Cookie c = new Cookie(name, URLEncoder.encode(value, "utf-8"));
   c.setMaxAge(age);
   c.setPath(appname);
   response.addCookie(c);
 }