Exemplo n.º 1
1
  public static void showSession(HttpServletRequest req, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    out.println("Session id: " + session.getId());
    out.println(" session.isNew(): " + session.isNew());
    out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs");
    out.println(
        " session.getCreationTime(): "
            + session.getCreationTime()
            + " ("
            + new Date(session.getCreationTime())
            + ")");
    out.println(
        " session.getLastAccessedTime(): "
            + session.getLastAccessedTime()
            + " ("
            + new Date(session.getLastAccessedTime())
            + ")");
    out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie());
    out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL());
    out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid());

    out.println("Saved session Attributes:");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(" " + name + ": " + session.getAttribute(name) + "<BR>");
    }
  }
  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);
    }
  }
 /**
  * 处理Service返回状态
  *
  * @param status
  * @param request
  * @param response
  * @param session
  * @throws IOException
  */
 private void handleStatus(
     int status, HttpServletRequest request, HttpServletResponse response, HttpSession session)
     throws IOException {
   switch (status) {
     case GroupService.OWNER_CAN_NOT_DROP_OUT:
       WebUtils.setResponseMessage(
           response,
           "error",
           "handlegroupmember_owner_not_deleted",
           session.getId(),
           request.getLocale());
       break;
     case GroupService.SUCCESS:
       WebUtils.setResponseBean(response, "success", null, session.getId(), request.getLocale());
       break;
     case GroupService.UID_NOT_OWNER:
       WebUtils.setResponseMessage(
           response, "error", "handlegroupmember_not_owner", session.getId(), request.getLocale());
       break;
     case GroupService.USER_NOT_INT_GROUP:
       WebUtils.setResponseMessage(
           response,
           "error",
           "handlegroupmember_user_not_in_group",
           session.getId(),
           request.getLocale());
       break;
     default:
       break;
   }
 }
Exemplo n.º 4
0
 public static final TSUser getSessionUserName() {
   HttpSession session = ContextHolderUtils.getSession();
   if (ClientManager.getInstance().getClient(session.getId()) != null) {
     return ClientManager.getInstance().getClient(session.getId()).getUser();
   }
   return null;
 }
  /** @throws Exception */
  public void testInvalidateSession() throws Exception {
    MockServletContextImpl servletContext = new MockServletContextImpl("hoge");
    MockHttpServletRequestImpl request = new MockHttpServletRequestImpl(servletContext, "foo");
    SessionStateManager sessionStateManager =
        new SessionStateManager() {
          public SessionState loadState(String sessionId) {
            return null;
          }

          public void updateState(String sessionId, SessionState sessionState) {}

          public void removeState(String sessionId) {}
        };
    S2HttpServletRequestWrapper requestWrapper =
        new S2HttpServletRequestWrapper(request, sessionStateManager);
    HttpSession session = requestWrapper.getSession();
    assertNotNull(session);

    session.invalidate();
    assertNull(request.getSession(false));
    assertNull(request.getRequestedSessionId());

    HttpSession session2 = requestWrapper.getSession();
    assertNotSame(session, session2);
    assertFalse(session.getId().equals(session2.getId()));
  }
  /* good2() reverses the bodies in the if statement */
  private void good2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    if (IO.static_returns_t()) {
      Logger tcLog = Logger.getLogger("cwe_testcases_logger");
      if (request.getParameter("username") == null) {
        return;
      }
      String username = request.getParameter("username");
      if (username.matches("[a-zA-Z0-9]*")) {
        HttpSession session = request.getSession(true);
        /* FIX: logged message does not contain session id */
        tcLog.log(Level.FINEST, "Username: "******" Session ID:" + session.getId());
      } else {
        response.getWriter().println("Invalid characters");
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Logger tcLog = Logger.getLogger("cwe_testcases_logger");
      if (request.getParameter("username") == null) {
        return;
      }

      String username = request.getParameter("username");

      if (username.matches("[a-zA-Z0-9]*")) {
        HttpSession session = request.getSession(true);
        /* FLAW: leak session ID to debug log */
        tcLog.log(Level.FINEST, "Username: "******" Session ID:" + session.getId());
      } else {
        response.getWriter().println("Invalid characters");
      }
    }
  }
 public IServerFacade getFacade(HttpSession session) {
   IServerFacade facade = _facades.get(session.getId());
   if (facade == null) {
     facade = new ServerFacade(session.getId());
     _facades.put(session.getId(), facade);
   }
   return facade;
 }
Exemplo n.º 8
0
 /*
  * (non-Javadoc)
  *
  * @see
  * javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet
  * .http.HttpSessionEvent)
  */
 public void sessionDestroyed(HttpSessionEvent event) {
   HttpSession session = event.getSession();
   if (getAllUserNumber() > 0) {
     logger.info("销毁了一个Session连接:[" + session.getId() + "]");
   }
   session.removeAttribute(Constants.CURRENT_USER);
   sessionService.deleteBySessionId(session.getId());
   setAllUserNumber(-1);
 }
 @PostConstruct
 public void inicializarAdministrador() {
   try {
     FacesContext x = FacesContext.getCurrentInstance();
     HttpSession ses = (HttpSession) x.getExternalContext().getSession(false);
     administrarEmpresas.obtenerConexion(ses.getId());
     administrarRastros.obtenerConexion(ses.getId());
   } catch (Exception e) {
     System.out.println("Error postconstruct " + this.getClass().getName() + ": " + e);
     System.out.println("Causa: " + e.getCause());
   }
 }
Exemplo n.º 10
0
  // any time the server needs access to the dataset, it gets a "GuardedDataset" which allows us to
  // add caching
  // optionally, a session may be established, which allows us to reserve the dataset for that
  // session.
  protected GuardedDataset getDataset(ReqState preq) throws Exception {
    HttpServletRequest req = preq.getRequest();
    String reqPath = preq.getDataSet();

    // see if the client wants sessions
    boolean acceptSession = false;
    String s = req.getHeader("X-Accept-Session");
    if (s != null && s.equalsIgnoreCase("true") && allowSessions) acceptSession = true;

    HttpSession session = null;
    if (acceptSession) {
      // see if theres already a session established, create one if not
      session = req.getSession();
      if (!session.isNew()) {
        GuardedDataset gdataset = (GuardedDataset) session.getAttribute(reqPath);
        if (null != gdataset) {
          if (debugSession)
            System.out.printf(" found gdataset %s in session %s %n", reqPath, session.getId());
          if (log.isDebugEnabled())
            log.debug(" found gdataset " + gdataset + " in session " + session.getId());
          return gdataset;
        }
      }
    }

    NetcdfFile ncd = DatasetHandler.getNetcdfFile(req, preq.getResponse(), reqPath);
    if (null == ncd) return null;

    GuardedDataset gdataset = new GuardedDatasetCacheAndClone(reqPath, ncd, acceptSession);
    // GuardedDataset gdataset = new GuardedDatasetImpl(reqPath, ncd, acceptSession);

    if (acceptSession) {
      String cookiePath = req.getRequestURI();
      String suffix = "." + preq.getRequestSuffix();
      if (cookiePath.endsWith(suffix)) // snip off the suffix
      cookiePath = cookiePath.substring(0, cookiePath.length() - suffix.length());
      session.setAttribute(reqPath, gdataset);
      session.setAttribute(CookieFilter.SESSION_PATH, cookiePath);
      // session.setAttribute("dataset", ncd.getLocation());  // for UsageValve
      // session.setMaxInactiveInterval(30); // 30 second timeout !!
      if (debugSession)
        System.out.printf(
            " added gdataset %s in session %s cookiePath %s %n",
            reqPath, session.getId(), cookiePath);
      if (log.isDebugEnabled())
        log.debug(" added gdataset " + gdataset + " in session " + session.getId());
    } /* else {
        session = req.getSession();
        session.setAttribute("dataset", ncd.getLocation()); // for UsageValve
      } */

    return gdataset;
  }
Exemplo n.º 11
0
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   HttpSession session = request.getSession(false);
   if (session != null) {
     RAPSupport.setLoggedInUser(new UserPrincipal("none"));
     HttpSessionManager.removeStoredHttpSession(session.getId());
     invalidateCookies(request, response);
     redirectLoginPage(response);
     LOGGER.log(
         Level.INFO, TextUtils.merge("Logout from httpSessionId: {0} performed", session.getId()));
   }
 }
Exemplo n.º 12
0
  @Override
  public HttpSession getSession(boolean create) {
    if (create) {
      httpSession = config.getHttpSessionManager().create();
      requestedSessionId = httpSession.getId();
      response.addCookie(new Cookie(config.getSessionIdName(), httpSession.getId()));
    } else {
      if (isRequestedSessionIdFromCookie() || isRequestedSessionIdFromURL()) {
        httpSession = config.getHttpSessionManager().get(requestedSessionId);
      }
    }

    return httpSession;
  }
Exemplo n.º 13
0
  private void handleLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    HttpSession session = req.getSession();
    String sendMeTo = req.getParameter("sendMeTo");
    if (sendMeTo != null) {
      session.setAttribute("sendMeTo", sendMeTo);
    }
    String redir = Configuration.mooseheadLocation() + "/oauth2callback";
    session.setAttribute("redir", redir);
    String sessionid = session.getId();
    // redirect to google for authorization
    StringBuilder oauthUrl =
        new StringBuilder()
            .append("https://accounts.google.com/o/oauth2/auth")
            .append("?client_id=")
            .append(
                Configuration.googleClientId()) // the client id from the api console registration
            .append("&response_type=code")
            .append("&scope=openid%20email") // scope is the api permissions we are requesting
            .append("&redirect_uri=")
            .append(redir) // the servlet that google redirects to after authorization
            .append("&state=" + sessionid)
            .append("&access_type=online")
            .append(
                "&approval_prompt=auto") // here we are asking to access to user's data while they
                                         // are not signed in
        ;

    resp.sendRedirect(oauthUrl.toString());
  }
Exemplo n.º 14
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
   }
 }
Exemplo n.º 15
0
  @RequestMapping(value = "/logout")
  public String logout(final HttpSession httpSession) {
    logger.trace("invalidating session:{}", httpSession.getId());
    httpSession.invalidate();

    return "redirect:/index.htm";
  }
  @Override
  public void requestInitialized(final ServletRequestEvent servletRequestEvent) {
    final HttpServletRequest httpServletRequest =
        (HttpServletRequest) servletRequestEvent.getServletRequest();

    if (Requests.searchEngineBotRequest(httpServletRequest)) {
      LOGGER.log(
          Level.DEBUG,
          "Request made from a search engine[User-Agent={0}]",
          httpServletRequest.getHeader("User-Agent"));
      httpServletRequest.setAttribute(Keys.HttpRequest.IS_SEARCH_ENGINE_BOT, true);
    } else {
      httpServletRequest.setAttribute(Keys.HttpRequest.IS_SEARCH_ENGINE_BOT, false);

      if (StaticResources.isStatic(httpServletRequest)) {
        return;
      }

      // Gets the session of this request
      final HttpSession session = httpServletRequest.getSession();
      LOGGER.log(
          Level.TRACE,
          "Gets a session[id={0}, remoteAddr={1}, User-Agent={2}, isNew={3}]",
          new Object[] {
            session.getId(),
            httpServletRequest.getRemoteAddr(),
            httpServletRequest.getHeader("User-Agent"),
            session.isNew()
          });
      // Online visitor count
      OptionQueryService.onlineVisitorCount(httpServletRequest);
    }
  }
Exemplo n.º 17
0
  @Before
  public void setup() throws Exception {
    try (ServerSocket serverSocket = new ServerSocket(0)) {
      googlePort = serverSocket.getLocalPort();
    }
    googleServer = new Server(googlePort);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    googleServer.setHandler(context);
    context.addServlet(new ServletHolder(userinfoServlet), "/oauth2/v2/userinfo");
    context.addServlet(new ServletHolder(tokenServlet), "/o/oauth2/token");
    googleServer.start();

    // Allow attributes to be set and got from a session.
    final Map<String, Object> attributes = Maps.newHashMap();
    Answer<Void> setAttributeAnswer =
        new Answer<Void>() {
          @Override
          public Void answer(InvocationOnMock invocation) throws Throwable {
            attributes.put((String) invocation.getArguments()[0], invocation.getArguments()[1]);
            return null;
          }
        };
    Answer<Object> getAttributeAnswer =
        new Answer<Object>() {
          @Override
          public Object answer(InvocationOnMock invocation) throws Throwable {
            return attributes.get((String) invocation.getArguments()[0]);
          }
        };
    when(session.getAttribute(anyString())).thenAnswer(getAttributeAnswer);
    when(session.getId()).thenReturn("sessionID");
    doAnswer(setAttributeAnswer).when(session).setAttribute(anyString(), anyObject());
  }
 @Override
 public void sessionCreated(HttpSessionEvent httpSessionEvent) {
   HttpSession session = httpSessionEvent.getSession();
   String sessionId = session.getId();
   LoggerFactory.getLogger(getClass())
       .info("HttpSession '" + session + "' with ID '" + sessionId + "' created");
 }
Exemplo n.º 19
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Tracking Example";
    HttpSession session = request.getSession(true);
    String heading;

    Integer accessCount = (Integer) session.getAttribute("accessCount");

    if (accessCount == null) {
      accessCount = new Integer(0);
      heading = "Welcome, Newcomer";
    } else {
      heading = "Welcome Back";
      accessCount = new Integer(accessCount.intValue() + 1);
    }

    session.setAttribute("accessCount", accessCount);
    out.println(
        "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=\"CENTER\">"
            + heading
            + "</H1>\n"
            + "<H2>Information on Your Session:</H2>\n"
            + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "  <TH>Info Type<TH>Value\n"
            + "<TR>\n"
            + "  <TD>ID\n"
            + "  <TD>"
            + session.getId()
            + "\n"
            + "<TR>\n"
            + "  <TD>Creation Time\n"
            + "  <TD>"
            + new Date(session.getCreationTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Time of Last Access\n"
            + "  <TD>"
            + new Date(session.getLastAccessedTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Number of Previous Accesses\n"
            + "  <TD>"
            + accessCount
            + "\n"
            + "</TR>"
            + "</TABLE>\n");

    // the following two statements show how to retrieve parameters in
    // the request.  The URL format is something like:
    // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li
    String myname = request.getParameter("myname");
    if (myname != null) out.println("Hey " + myname + "<br><br>");

    out.println("</BODY></HTML>");
  }
  @Override
  public String doAction(HttpServletRequest request) {
    HttpSession session = request.getSession();
    String key = (String) session.getAttribute("svplogin_Key");
    boolean answerCrypted = getAuthenticationSettings().getBoolean("loginAnswerCrypted", false);

    try {
      String userId = getAdmin().authenticate(key, session.getId(), false, false);
      UserDetail userDetail = getAdmin().getUserDetail(userId);
      String question = request.getParameter("question");
      String answer = request.getParameter("answer");
      userDetail.setLoginQuestion(question);

      // encrypt the answer if needed
      if (answerCrypted) {
        answer = CryptMD5.encrypt(answer);
      }
      userDetail.setLoginAnswer(answer);
      getAdmin().updateUser(userDetail);

      if (getGeneral().getBoolean("userLoginForcePasswordChange", false)) {
        return getGeneral().getString("userLoginForcePasswordChangePage");
      }
      return sessionOpenener.openSession(request, key);
    } catch (AdminException e) {
      // Error : go back to login page
      SilverTrace.error(
          "peasCore", "validationQuestionHandler.doAction()", "peasCore.EX_USER_KEY_NOT_FOUND", e);
      return "/Login.jsp";
    }
  }
Exemplo n.º 21
0
  /*
   * Return the AjaxWebClient for this session+clientId.
   * Create one if it does not already exist.
   */
  protected AjaxWebClient getAjaxWebClient(HttpServletRequest request) {
    HttpSession session = request.getSession(true);

    String clientId = request.getParameter("clientId");
    // if user doesn't supply a 'clientId', we'll just use a default.
    if (clientId == null) {
      clientId = "defaultAjaxWebClient";
    }
    String sessionKey = session.getId() + '-' + clientId;

    AjaxWebClient client = null;
    synchronized (ajaxWebClients) {
      client = ajaxWebClients.get(sessionKey);
      // create a new AjaxWebClient if one does not already exist for this sessionKey.
      if (client == null) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("creating new AjaxWebClient in " + sessionKey);
        }
        client = new AjaxWebClient(request, maximumReadTimeout);
        ajaxWebClients.put(sessionKey, client);
      }
      client.updateLastAccessed();
    }
    return client;
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    HttpSession session = req.getSession(true);
    String sessionId = session.getId();

    ChannelService channelService = ChannelServiceFactory.getChannelService();
    String token = channelService.createChannel(sessionId);

    StringBuilder sessionMap = new StringBuilder();
    Enumeration<String> attributeNames = session.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
      String name = attributeNames.nextElement();
      sessionMap
          .append(name)
          .append(" => ")
          .append(session.getAttribute(name).toString())
          .append("<br/>");
    }

    resp.setContentType("text/html");
    new SkimpyTemplate(getServletContext().getResourceAsStream("/injectable.html"))
        .add("sessionId", sessionId)
        .add("token", token)
        .add("session-vars", sessionMap.toString())
        .write(resp.getWriter());
  }
Exemplo n.º 23
0
  @RequestMapping("last")
  public ModelAndView getlast(HttpSession session, @ModelAttribute User_Results user, Model model) {

    logger.info("Results stored");

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("last");

    User_Results users = new User_Results();
    Iterator iterator = resultData.keySet().iterator();
    while (iterator.hasNext()) {
      Integer key = (Integer) iterator.next();
      List list = (List) resultData.get(key);
      users.setTitle(utitle);
      users.setExpertName(uName);
      users.setExperience(exp);
      users.setTestsNumber(numberTests);
      users.setEmail(mail);
      users.setDataSet("Data-Set" + key);
      users.setSession(session.getId());
      users.setPower(((GraphPlot) list.get(0)).getLast());
      users.setVCO2(((GraphPlot) list.get(0)).getVCO2());
      users.setVO2(((GraphPlot) list.get(0)).getVO2());
      users.setVE(((GraphPlot) list.get(0)).getVE());
      dataService.insertData(users);
    }
    session.invalidate();
    model.asMap().clear();
    return modelAndView;
  }
Exemplo n.º 24
0
  @Test
  public void inloggenJuist() {
    Medewerker medewerker = new Medewerker();
    medewerker.setIdentificatie("emailadres");
    medewerker.setHashWachtwoord("wachtwoord");

    try {
      EasyMock.expect(gebruikerRepository.zoek("emailadres")).andReturn(medewerker);
    } catch (NietGevondenException e1) {
      fail();
    }

    HttpSession httpSession = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(servletRequest.getSession()).andReturn(httpSession);
    EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("1234").times(2);
    EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent");

    EasyMock.expect(httpSession.getId()).andReturn("234");

    gebruikerRepository.opslaan(medewerker);
    EasyMock.expectLastCall();

    replayAll();

    try {
      gebruikerService.inloggen("emailadres", "wachtwoord", "false", servletRequest);
    } catch (LeegVeldException | NietGevondenException | OnjuistWachtwoordException e) {
      fail(e.getMessage());
    }

    verifyAll();
  }
Exemplo n.º 25
0
  @Test
  public void getIngelogdeGebruiker() {
    HttpSession httpSession = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(servletRequest.getSession()).andReturn(httpSession);
    EasyMock.expect(httpSession.getId()).andReturn("a");
    EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("adr");
    EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent");

    Medewerker medewerker = new Medewerker();
    medewerker.setId(46L);

    Sessie sessie = new Sessie();
    sessie.setGebruiker(medewerker);
    sessie.setIpadres("adr");
    sessie.setSessie("a");
    medewerker.getSessies().add(sessie);

    try {
      EasyMock.expect(gebruikerRepository.zoekOpSessieEnIpadres("a", "adr")).andReturn(medewerker);
    } catch (NietGevondenException e1) {
    }

    replayAll();
    EasyMock.replay(httpSession);

    try {
      assertEquals(medewerker, gebruikerService.getIngelogdeGebruiker(servletRequest));
    } catch (NietIngelogdException e) {
    }

    verifyAll();
    EasyMock.verify(httpSession);
  }
Exemplo n.º 26
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String login = request.getParameter("email");
    String pwd = request.getParameter("password");
    User user = userService.getUser(login, pwd);

    if (user != null) {
      HttpSession session = request.getSession();

      long time = session.getCreationTime();
      long lastTime = session.getLastAccessedTime();
      String idSession = session.getId();

      session.setAttribute("user", user);
      response.sendRedirect("/home");

      System.out.println("session time creation " + time);
      System.out.println("session last access time " + lastTime);
      System.out.println("session id " + idSession);

      System.out.println(user.toString());
    } else {
      response.sendRedirect("/");
      System.out.println("hera lisogo");
    }
  }
Exemplo n.º 27
0
  @Test
  public void uitloggen() {
    HttpSession httpSession = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(servletRequest.getSession()).andReturn(httpSession).times(2);
    EasyMock.expect(httpSession.getId()).andReturn("a").times(2);
    EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("adr").times(2);
    EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent");

    Medewerker medewerker = new Medewerker();
    medewerker.setId(46L);

    Sessie sessie = new Sessie();
    sessie.setGebruiker(medewerker);
    sessie.setIpadres("adr");
    sessie.setSessie("a");
    medewerker.getSessies().add(sessie);

    try {
      EasyMock.expect(gebruikerRepository.zoekOpSessieEnIpadres("a", "adr")).andReturn(medewerker);
    } catch (NietGevondenException e1) {
    }

    gebruikerRepository.opslaan(medewerker);
    EasyMock.expectLastCall();

    replayAll();
    EasyMock.replay(httpSession);

    gebruikerService.uitloggen(servletRequest);

    verifyAll();
    EasyMock.verify(httpSession);
  }
Exemplo n.º 28
0
 /**
  * This method handles GET request and produces JSP page with all branch sections
  *
  * @param session http session that will be initiated
  * @return {@link ModelAndView} with view name as renderAllSection
  */
 @RequestMapping(
     value = {"/", "/sections"},
     method = RequestMethod.GET)
 public ModelAndView sectionList(HttpSession session) {
   /*
   Counting the number of active users based on the number of sessions.
   By default, the session will be initialized after controller's invocation,
   so at the time of request processing, we can miss the session
   if the current request is the first one for a particular user.
   To change a default behavior we call getId() method
   that initializes the session right now.
   If a request from the user is not the first one getId() call will have no effect.
   */
   session.getId();
   return new ModelAndView("sectionList")
       .addObject("pageSize", Pagination.getPageSizeFor(securityService.getCurrentUser()))
       .addObject("sectionList", sectionService.getAll())
       .addObject("breadcrumbList", breadcrumbBuilder.getForumBreadcrumb())
       .addObject("messagesCount", forumStaticsProvider.getPostsOnForumCount())
       .addObject("registeredUsersCount", forumStaticsProvider.getUsersCount())
       .addObject("visitors", forumStaticsProvider.getOnlineUsersCount())
       .addObject("usersRegistered", forumStaticsProvider.getOnlineRegisteredUsers())
       .addObject("visitorsRegistered", forumStaticsProvider.getOnlineRegisteredUsersCount())
       .addObject("visitorsGuests", forumStaticsProvider.getOnlineAnonymousUsersCount());
 }
Exemplo n.º 29
0
  private Authentication fresh(Authentication authentication, ServletRequest req) {
    HttpServletRequest request = (HttpServletRequest) req;

    HttpSession session = request.getSession(false);

    if (session != null) {
      SessionRegistry sessionRegistry =
          (SessionRegistry) SpringBeanUtil.getBeanByName("sessionRegistry");
      SessionInformation info = sessionRegistry.getSessionInformation(session.getId());

      if (info != null) {
        // Non-expired - update last request date/time
        Object principal = info.getPrincipal();
        if (principal instanceof org.springframework.security.core.userdetails.User) {
          org.springframework.security.core.userdetails.User userRefresh =
              (org.springframework.security.core.userdetails.User) principal;
          ServletContext sc = session.getServletContext();
          HashSet<String> unrgas = springSecurityService.getUsersNeedRefreshGrantedAuthorities();
          if (unrgas.size() > 0) {
            HashSet<String> loginedUsernames = new HashSet<String>();

            List<Object> loggedUsers = sessionRegistry.getAllPrincipals();
            for (Object lUser : loggedUsers) {
              if (lUser instanceof org.springframework.security.core.userdetails.User) {
                org.springframework.security.core.userdetails.User u =
                    (org.springframework.security.core.userdetails.User) lUser;
                loginedUsernames.add(u.getUsername());
              }
            }
            // 清除已经下线的但需要刷新的username
            for (Iterator iterator = unrgas.iterator(); iterator.hasNext(); ) {
              String unrgs = (String) iterator.next();
              if (!loginedUsernames.contains(unrgs)) {
                iterator.remove();
              }
            }
            if (unrgas.contains(userRefresh.getUsername())) {
              // 如果需要刷新权限的列表中有当前的用户,刷新登录用户权限
              // FIXME:与springSecurityServiceImpl中的功能,相重复,需重构此方法和springSecurityServiceImpl
              MyJdbcUserDetailsManager mdudm =
                  (MyJdbcUserDetailsManager)
                      SpringBeanUtil.getBeanByType(MyJdbcUserDetailsManager.class);
              SecurityContextHolder.getContext()
                  .setAuthentication(
                      new UsernamePasswordAuthenticationToken(
                          userRefresh,
                          userRefresh.getPassword(),
                          mdudm.getUserAuthorities(userRefresh.getUsername())));
              session.setAttribute(
                  HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                  SecurityContextHolder.getContext());
              unrgas.remove(userRefresh.getUsername());
              return SecurityContextHolder.getContext().getAuthentication();
            }
          }
        }
      }
    }
    return authentication;
  }
  public static void add(HttpSession session) {
    String sessionId = session.getId();

    if (CompoundSessionIdSplitterUtil.hasSessionDelimiter()) {
      sessionId = CompoundSessionIdSplitterUtil.parseSessionId(sessionId);
    }

    Map<String, HttpSession> sessions = _sessions.get(sessionId);

    if (sessions == null) {
      sessions = new ConcurrentHashMap<String, HttpSession>();

      Map<String, HttpSession> previousSessions = _sessions.putIfAbsent(sessionId, sessions);

      if (previousSessions != null) {
        sessions = previousSessions;
      }
    }

    ServletContext servletContext = session.getServletContext();

    String contextPath = servletContext.getContextPath();

    // ConcurrentHashMap's read is faster than its write. This check is
    // logically unnecessary, but is a performance improvement.

    if (!sessions.containsKey(contextPath)) {
      sessions.put(contextPath, session);
    }
  }