/** {@inheritDoc} */
  public void unjoinGroup(String authzGroupId)
      throws GroupNotDefinedException, AuthzPermissionException {
    String user = sessionManager().getCurrentSessionUserId();
    if (user == null)
      throw new AuthzPermissionException(user, SECURE_UPDATE_OWN_AUTHZ_GROUP, authzGroupId);

    // check security (throws if not permitted)
    unlock(SECURE_UPDATE_OWN_AUTHZ_GROUP, authzGroupId);

    // get the AuthzGroup
    AuthzGroup azGroup = m_storage.get(authzGroupId);
    if (azGroup == null) {
      throw new GroupNotDefinedException(authzGroupId);
    }

    // if not joined (no grant), we are done
    BaseMember grant = (BaseMember) azGroup.getMember(user);
    if (grant == null) {
      return;
    }

    // if the user currently is the only maintain role user, disallow the unjoin
    if (grant.getRole().getId().equals(azGroup.getMaintainRole())) {
      Set maintainers = azGroup.getUsersHasRole(azGroup.getMaintainRole());
      if (maintainers.size() <= 1) {
        throw new AuthzPermissionException(user, SECURE_UPDATE_OWN_AUTHZ_GROUP, authzGroupId);
      }
    }

    // if the grant is provided, disallow the unjoin. There would be no point in
    // allowing the user to unjoin, since the user will rejoin the realm the next
    // time it is updated or he/she logs in.

    if (grant.isProvided()) {
      throw new AuthzPermissionException(user, SECURE_UPDATE_OWN_AUTHZ_GROUP, authzGroupId);
    }

    ((BaseAuthzGroup) azGroup).setEvent(SECURE_UPDATE_OWN_AUTHZ_GROUP);

    removeMemberFromGroup(azGroup, user);
  }
  /** {@inheritDoc} */
  public boolean allowUnjoinGroup(String authzGroupId) {
    String user = sessionManager().getCurrentSessionUserId();
    if (user == null) {
      return false;
    }

    // check security (throws if not permitted)
    if (!unlockCheck(SECURE_UPDATE_OWN_AUTHZ_GROUP, authzGroupId)) return false;

    // get the azGroup
    AuthzGroup azGroup = m_storage.get(authzGroupId);
    if (azGroup == null) {
      return false;
    }

    // if not joined (no grant), unable to unjoin
    BaseMember grant = (BaseMember) azGroup.getMember(user);
    if (grant == null) {
      return false;
    }

    // if the grant is provider, unable to unjoin
    else if (grant.isProvided()) {
      return false;
    }

    // if the user currently is the only maintain role user, disallow the unjoin
    if (grant.getRole().getId().equals(azGroup.getMaintainRole())) {
      Set maintainers = azGroup.getUsersHasRole(azGroup.getMaintainRole());
      if (maintainers.size() <= 1) {
        return false;
      }
    }

    return true;
  }