/**
   * Register an authenticated Principal and authentication type in our request, in the current
   * session (if there is one), and with our SingleSignOn valve, if there is one. Set the
   * appropriate cookie to be returned.
   *
   * @param request The servlet request we are processing
   * @param response The servlet response we are generating
   * @param principal The authenticated Principal to be registered
   * @param authType The authentication type to be registered
   * @param username Username used to authenticate (if any)
   * @param password Password used to authenticate (if any)
   */
  protected void register(
      HttpRequest request,
      HttpResponse response,
      Principal principal,
      String authType,
      String username,
      String password) {

    if (debug >= 1) log("Authenticated '" + principal.getName() + "' with type '" + authType + "'");

    // Cache the authentication information in our request
    request.setAuthType(authType);
    request.setUserPrincipal(principal);

    // Cache the authentication information in our session, if any
    if (cache) {
      Session session = getSession(request, false);
      if (session != null) {
        session.setAuthType(authType);
        session.setPrincipal(principal);
        if (username != null) session.setNote(Constants.SESS_USERNAME_NOTE, username);
        else session.removeNote(Constants.SESS_USERNAME_NOTE);
        if (password != null) session.setNote(Constants.SESS_PASSWORD_NOTE, password);
        else session.removeNote(Constants.SESS_PASSWORD_NOTE);
      }
    }

    // Construct a cookie to be returned to the client
    if (sso == null) return;
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();
    String value = generateSessionId();
    Cookie cookie = new Cookie(Constants.SINGLE_SIGN_ON_COOKIE, value);
    cookie.setMaxAge(-1);
    cookie.setPath("/");
    hres.addCookie(cookie);

    // Register this principal with our SSO valve
    sso.register(value, principal, authType, username, password);
    request.setNote(Constants.REQ_SSOID_NOTE, value);
  }
  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();
    }
  }