/**
   * Serialize a session into a byte array<br>
   * This method simple calls the writeObjectData method on the session and returns the byte data
   * from that call
   *
   * @param session - the session to be serialized
   * @return a byte array containing the session data, null if the serialization failed
   */
  protected byte[] writeSession(Session session) {
    try {
      java.io.ByteArrayOutputStream session_data = new java.io.ByteArrayOutputStream();
      java.io.ObjectOutputStream session_out = new java.io.ObjectOutputStream(session_data);
      session_out.flush();
      boolean hasPrincipal = session.getPrincipal() != null;
      session_out.writeBoolean(hasPrincipal);
      if (hasPrincipal) {
        session_out.writeObject(
            SerializablePrincipal.createPrincipal((GenericPrincipal) session.getPrincipal()));
      } // end if
      ((ReplicatedSession) session).writeObjectData(session_out);
      return session_data.toByteArray();

    } catch (Exception x) {
      log.error("Failed to serialize the session!", x);
    }
    return null;
  }
  public void logout() throws SecurityServiceException {
    HttpGraniteContext context = (HttpGraniteContext) GraniteManager.getCurrentInstance();

    Session session = getSession(context.getRequest(), false);
    if (session != null && session.getPrincipal() != null) {
      session.setAuthType(null);
      session.setPrincipal(null);
      session.removeNote(Constants.SESS_USERNAME_NOTE);
      session.removeNote(Constants.SESS_PASSWORD_NOTE);
      session.expire();
    }
  }
  public Object authorize(AbstractSecurityContext context) throws Exception {

    startAuthorization(context);

    HttpGraniteContext graniteContext = (HttpGraniteContext) GraniteManager.getCurrentInstance();
    HttpServletRequest httpRequest = graniteContext.getRequest();
    Request request = getRequest(httpRequest);
    Session session = request.getSessionInternal();
    request.setAuthType(session.getAuthType());
    request.setUserPrincipal(session.getPrincipal());

    if (context.getDestination().isSecured()) {
      Principal principal = getPrincipal(httpRequest);
      if (principal == null) {
        if (httpRequest.getRequestedSessionId() != null) {
          HttpSession httpSession = httpRequest.getSession(false);
          if (httpSession == null
              || httpRequest.getRequestedSessionId().equals(httpSession.getId()))
            throw SecurityServiceException.newSessionExpiredException("Session expired");
        }
        throw SecurityServiceException.newNotLoggedInException("User not logged in");
      }

      Realm realm = getRealm(httpRequest);
      boolean accessDenied = true;
      for (String role : context.getDestination().getRoles()) {
        if (realm.hasRole(principal, role)) {
          accessDenied = false;
          break;
        }
      }
      if (accessDenied)
        throw SecurityServiceException.newAccessDeniedException("User not in required role");
    }

    try {
      return endAuthorization(context);
    } catch (InvocationTargetException e) {
      for (Throwable t = e; t != null; t = t.getCause()) {
        // Don't create a dependency to javax.ejb in SecurityService...
        if (t instanceof SecurityException
            || "javax.ejb.EJBAccessException".equals(t.getClass().getName()))
          throw SecurityServiceException.newAccessDeniedException(t.getMessage());
      }
      throw e;
    }
  }
 protected Principal getPrincipal(HttpServletRequest httpRequest) {
   Request request = getRequest(httpRequest);
   Session session = request.getSessionInternal(false);
   return (session != null ? session.getPrincipal() : null);
 }
  /**
   * Enforce the security restrictions in the web application deployment descriptor of our
   * associated Context.
   *
   * @param request Request to be processed
   * @param response Response to be processed
   * @param context The valve context used to invoke the next valve in the current processing
   *     pipeline
   * @exception IOException if an input/output error occurs
   * @exception ServletException if thrown by a processing element
   */
  public void invoke(Request request, Response response, ValveContext context)
      throws IOException, ServletException {

    // If this is not an HTTP request, do nothing
    if (!(request instanceof HttpRequest) || !(response instanceof HttpResponse)) {
      context.invokeNext(request, response);
      return;
    }
    if (!(request.getRequest() instanceof HttpServletRequest)
        || !(response.getResponse() instanceof HttpServletResponse)) {
      context.invokeNext(request, response);
      return;
    }
    HttpRequest hrequest = (HttpRequest) request;
    HttpResponse hresponse = (HttpResponse) response;
    if (debug >= 1)
      log(
          "Security checking request "
              + ((HttpServletRequest) request.getRequest()).getMethod()
              + " "
              + ((HttpServletRequest) request.getRequest()).getRequestURI());
    LoginConfig config = this.context.getLoginConfig();

    // Have we got a cached authenticated Principal to record?
    if (cache) {
      Principal principal = ((HttpServletRequest) request.getRequest()).getUserPrincipal();
      if (principal == null) {
        Session session = getSession(hrequest);
        if (session != null) {
          principal = session.getPrincipal();
          if (principal != null) {
            if (debug >= 1)
              log(
                  "We have cached auth type "
                      + session.getAuthType()
                      + " for principal "
                      + session.getPrincipal());
            hrequest.setAuthType(session.getAuthType());
            hrequest.setUserPrincipal(principal);
          }
        }
      }
    }

    // Special handling for form-based logins to deal with the case
    // where the login form (and therefore the "j_security_check" URI
    // to which it submits) might be outside the secured area
    String contextPath = this.context.getPath();
    String requestURI = hrequest.getDecodedRequestURI();
    if (requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION)) {
      if (!authenticate(hrequest, hresponse, config)) {
        if (debug >= 1) log(" Failed authenticate() test");
        return;
      }
    }

    // Is this request URI subject to a security constraint?
    SecurityConstraint constraint = findConstraint(hrequest);
    if ((constraint == null) /*
									 * && (!Constants.FORM_METHOD.equals(config.
									 * getAuthMethod()))
									 */) {
      if (debug >= 1) log(" Not subject to any constraint");
      context.invokeNext(request, response);
      return;
    }
    if ((debug >= 1) && (constraint != null)) log(" Subject to constraint " + constraint);

    // Make sure that constrained resources are not cached by web proxies
    // or browsers as caching can provide a security hole
    if (!(((HttpServletRequest) hrequest.getRequest()).isSecure())) {
      HttpServletResponse sresponse = (HttpServletResponse) response.getResponse();
      sresponse.setHeader("Pragma", "No-cache");
      sresponse.setHeader("Cache-Control", "no-cache");
      sresponse.setDateHeader("Expires", 1);
    }

    // Enforce any user data constraint for this security constraint
    if (debug >= 1) log(" Calling checkUserData()");
    if (!checkUserData(hrequest, hresponse, constraint)) {
      if (debug >= 1) log(" Failed checkUserData() test");
      // ASSERT: Authenticator already set the appropriate
      // HTTP status code, so we do not have to do anything special
      return;
    }

    // Authenticate based upon the specified login configuration
    if (constraint.getAuthConstraint()) {
      if (debug >= 1) log(" Calling authenticate()");
      if (!authenticate(hrequest, hresponse, config)) {
        if (debug >= 1) log(" Failed authenticate() test");
        // ASSERT: Authenticator already set the appropriate
        // HTTP status code, so we do not have to do anything special
        return;
      }
    }

    // Perform access control based on the specified role(s)
    if (constraint.getAuthConstraint()) {
      if (debug >= 1) log(" Calling accessControl()");
      if (!accessControl(hrequest, hresponse, constraint)) {
        if (debug >= 1) log(" Failed accessControl() test");
        // ASSERT: AccessControl method has already set the appropriate
        // HTTP status code, so we do not have to do anything special
        return;
      }
    }

    // Any and all specified constraints have been satisfied
    if (debug >= 1) log(" Successfully passed all security constraints");
    context.invokeNext(request, response);
  }