Skip to content

Add ListTenantsPage class. #358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions src/main/java/com/google/firebase/auth/FirebaseUserManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@
import com.google.firebase.auth.UserRecord.UpdateRequest;
import com.google.firebase.auth.internal.DownloadAccountResponse;
import com.google.firebase.auth.internal.GetAccountInfoResponse;

import com.google.firebase.auth.internal.HttpErrorResponse;
import com.google.firebase.auth.internal.ListTenantsResponse;
import com.google.firebase.auth.internal.UploadAccountResponse;
import com.google.firebase.internal.FirebaseRequestInitializer;
import com.google.firebase.internal.NonNull;
Expand All @@ -57,6 +57,9 @@
/**
* FirebaseUserManager provides methods for interacting with the Google Identity Toolkit via its
* REST API. This class does not hold any mutable state, and is thread safe.
*
* <p>TODO(micahstairs): Consider renaming this to FirebaseAuthManager since this also supports
* tenants.
*
* @see <a href="https://developers.google.com/identity/toolkit/web/reference/relyingparty">
* Google Identity Toolkit</a>
Expand Down Expand Up @@ -87,6 +90,7 @@ class FirebaseUserManager {
.put("INVALID_DYNAMIC_LINK_DOMAIN", "invalid-dynamic-link-domain")
.build();

static final int MAX_LIST_TENANTS_RESULTS = 1000;
static final int MAX_LIST_USERS_RESULTS = 1000;
static final int MAX_IMPORT_USERS = 1000;

Expand All @@ -95,10 +99,11 @@ class FirebaseUserManager {
"iss", "jti", "nbf", "nonce", "sub", "firebase");

private static final String ID_TOOLKIT_URL =
"https://identitytoolkit.googleapis.com/v1/projects/%s";
"https://identitytoolkit.googleapis.com/%s/projects/%s";
private static final String CLIENT_VERSION_HEADER = "X-Client-Version";

private final String baseUrl;
private final String userMgtBaseUrl;
private final String tenantMgtBaseUrl;
private final JsonFactory jsonFactory;
private final HttpRequestFactory requestFactory;
private final String clientVersion = "Java/Admin/" + SdkUtils.getVersion();
Expand All @@ -117,7 +122,8 @@ class FirebaseUserManager {
"Project ID is required to access the auth service. Use a service account credential or "
+ "set the project ID explicitly via FirebaseOptions. Alternatively you can also "
+ "set the project ID via the GOOGLE_CLOUD_PROJECT environment variable.");
this.baseUrl = String.format(ID_TOOLKIT_URL, projectId);
this.userMgtBaseUrl = String.format(ID_TOOLKIT_URL, "v1", projectId);
this.tenantMgtBaseUrl = String.format(ID_TOOLKIT_URL, "v2", projectId);
this.jsonFactory = app.getOptions().getJsonFactory();
HttpTransport transport = app.getOptions().getHttpTransport();
this.requestFactory = transport.createRequestFactory(new FirebaseRequestInitializer(app));
Expand Down Expand Up @@ -201,7 +207,7 @@ DownloadAccountResponse listUsers(int maxResults, String pageToken) throws Fireb
builder.put("nextPageToken", pageToken);
}

GenericUrl url = new GenericUrl(baseUrl + "/accounts:batchGet");
GenericUrl url = new GenericUrl(userMgtBaseUrl + "/accounts:batchGet");
url.putAll(builder.build());
DownloadAccountResponse response = sendRequest(
"GET", url, null, DownloadAccountResponse.class);
Expand All @@ -221,6 +227,24 @@ UserImportResult importUsers(UserImportRequest request) throws FirebaseAuthExcep
return new UserImportResult(request.getUsersCount(), response);
}

ListTenantsResponse listTenants(int maxResults, String pageToken) throws FirebaseAuthException {
ImmutableMap.Builder<String, Object> builder = ImmutableMap.<String, Object>builder()
.put("pageSize", maxResults);
if (pageToken != null) {
checkArgument(!pageToken.equals(
ListTenantsPage.END_OF_LIST), "invalid end of list page token");
builder.put("pageToken", pageToken);
}

GenericUrl url = new GenericUrl(tenantMgtBaseUrl + "/tenants:list");
url.putAll(builder.build());
ListTenantsResponse response = sendRequest("GET", url, null, ListTenantsResponse.class);
if (response == null) {
throw new FirebaseAuthException(INTERNAL_ERROR, "Failed to retrieve tenants.");
}
return response;
}

String createSessionCookie(String idToken,
SessionCookieOptions options) throws FirebaseAuthException {
final Map<String, Object> payload = ImmutableMap.<String, Object>of(
Expand Down Expand Up @@ -257,7 +281,7 @@ String getEmailActionLink(EmailLinkType type, String email,
private <T> T post(String path, Object content, Class<T> clazz) throws FirebaseAuthException {
checkArgument(!Strings.isNullOrEmpty(path), "path must not be null or empty");
checkNotNull(content, "content must not be null for POST requests");
GenericUrl url = new GenericUrl(baseUrl + path);
GenericUrl url = new GenericUrl(userMgtBaseUrl + path);
return sendRequest("POST", url, content, clazz);
}

Expand Down
248 changes: 248 additions & 0 deletions src/main/java/com/google/firebase/auth/ListTenantsPage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.firebase.auth;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.api.client.json.JsonFactory;
import com.google.api.gax.paging.Page;
import com.google.common.collect.ImmutableList;
import com.google.firebase.auth.internal.DownloadAccountResponse;
import com.google.firebase.auth.internal.ListTenantsResponse;
import com.google.firebase.internal.NonNull;
import com.google.firebase.internal.Nullable;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

/**
* Represents a page of {@link Tenant} instances.
*
* <p>Provides methods for iterating over the tenants in the current page, and calling up
* subsequent pages of tenants.
*
* <p>Instances of this class are thread-safe and immutable.
*/
public class ListTenantsPage implements Page<Tenant> {

static final String END_OF_LIST = "";

private final ListTenantsResponse currentBatch;
private final TenantSource source;
private final int maxResults;

private ListTenantsPage(
@NonNull ListTenantsResponse currentBatch, @NonNull TenantSource source, int maxResults) {
this.currentBatch = checkNotNull(currentBatch);
this.source = checkNotNull(source);
this.maxResults = maxResults;
}

/**
* Checks if there is another page of tenants available to retrieve.
*
* @return true if another page is available, or false otherwise.
*/
@Override
public boolean hasNextPage() {
return !END_OF_LIST.equals(currentBatch.getPageToken());
}

/**
* Returns the string token that identifies the next page.
*
* <p>Never returns null. Returns empty string if there are no more pages available to be
* retrieved.
*
* @return A non-null string token (possibly empty, representing no more pages)
*/
@NonNull
@Override
public String getNextPageToken() {
return currentBatch.getPageToken();
}

/**
* Returns the next page of tenants.
*
* @return A new {@link ListTenantsPage} instance, or null if there are no more pages.
*/
@Nullable
@Override
public ListTenantsPage getNextPage() {
if (hasNextPage()) {
PageFactory factory = new PageFactory(source, maxResults, currentBatch.getPageToken());
try {
return factory.create();
} catch (FirebaseAuthException e) {
throw new RuntimeException(e);
}
}
return null;
}

/**
* Returns an {@link Iterable} that facilitates transparently iterating over all the tenants in
* the current Firebase project, starting from this page.
*
* <p>The {@link Iterator} instances produced by the returned {@link Iterable} never buffers more
* than one page of tenants at a time. It is safe to abandon the iterators (i.e. break the loops)
* at any time.
*
* @return a new {@link Iterable} instance.
*/
@NonNull
@Override
public Iterable<Tenant> iterateAll() {
return new TenantIterable(this);
}

/**
* Returns an {@code Iterable} over the users in this page.
*
* @return a {@code Iterable<Tenant>} instance.
*/
@NonNull
@Override
public Iterable<Tenant> getValues() {
return currentBatch.getTenants();
}

private static class TenantIterable implements Iterable<Tenant> {

private final ListTenantsPage startingPage;

TenantIterable(@NonNull ListTenantsPage startingPage) {
this.startingPage = checkNotNull(startingPage, "starting page must not be null");
}

@Override
@NonNull
public Iterator<Tenant> iterator() {
return new TenantIterator(startingPage);
}

/**
* An {@link Iterator} that cycles through tenants, one at a time.
*
* <p>It buffers the last retrieved batch of tenants in memory. The {@code maxResults} parameter
* is an upper bound on the batch size.
*/
private static class TenantIterator implements Iterator<Tenant> {

private ListTenantsPage currentPage;
private List<Tenant> batch;
private int index = 0;

private TenantIterator(ListTenantsPage startingPage) {
setCurrentPage(startingPage);
}

@Override
public boolean hasNext() {
if (index == batch.size()) {
if (currentPage.hasNextPage()) {
setCurrentPage(currentPage.getNextPage());
} else {
return false;
}
}

return index < batch.size();
}

@Override
public Tenant next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return batch.get(index++);
}

@Override
public void remove() {
throw new UnsupportedOperationException("remove operation not supported");
}

private void setCurrentPage(ListTenantsPage page) {
this.currentPage = checkNotNull(page);
this.batch = ImmutableList.copyOf(page.getValues());
this.index = 0;
}
}
}

/**
* Represents a source of tenant data that can be queried to load a batch of tenants.
*/
interface TenantSource {
@NonNull
ListTenantsResponse fetch(int maxResults, String pageToken)
throws FirebaseAuthException;
}

static class DefaultTenantSource implements TenantSource {

private final FirebaseUserManager userManager;
private final JsonFactory jsonFactory;

DefaultTenantSource(FirebaseUserManager userManager, JsonFactory jsonFactory) {
this.userManager = checkNotNull(userManager, "user manager must not be null");
this.jsonFactory = checkNotNull(jsonFactory, "json factory must not be null");
}

@Override
public ListTenantsResponse fetch(int maxResults, String pageToken)
throws FirebaseAuthException {
return userManager.listTenants(maxResults, pageToken);
}
}

/**
* A simple factory class for {@link ListTenantsPage} instances.
*
* <p>Performs argument validation before attempting to load any tenant data (which is expensive,
* and hence may be performed asynchronously on a separate thread).
*/
static class PageFactory {

private final TenantSource source;
private final int maxResults;
private final String pageToken;

PageFactory(@NonNull TenantSource source) {
this(source, FirebaseUserManager.MAX_LIST_TENANTS_RESULTS, null);
}

PageFactory(@NonNull TenantSource source, int maxResults, @Nullable String pageToken) {
checkArgument(maxResults > 0 && maxResults <= FirebaseUserManager.MAX_LIST_TENANTS_RESULTS,
"maxResults must be a positive integer that does not exceed %s",
FirebaseUserManager.MAX_LIST_TENANTS_RESULTS);
checkArgument(!END_OF_LIST.equals(pageToken), "invalid end of list page token");
this.source = checkNotNull(source, "source must not be null");
this.maxResults = maxResults;
this.pageToken = pageToken;
}

ListTenantsPage create() throws FirebaseAuthException {
ListTenantsResponse batch = source.fetch(maxResults, pageToken);
return new ListTenantsPage(batch, source, maxResults);
}
}
}

28 changes: 22 additions & 6 deletions src/main/java/com/google/firebase/auth/Tenant.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,26 @@ public final class Tenant {
private String displayName;

@Key("allowPasswordSignup")
private String passwordSignInAllowed;
private boolean passwordSignInAllowed;

@Key("enableEmailLinkSignin")
private String emailLinkSignInEnabled;
private boolean emailLinkSignInEnabled;

public String getTenantId() {
return tenantId;
}

public String getDisplayName() {
return displayName;
}

public boolean isPasswordSignInAllowed() {
return passwordSignInAllowed;
}

public boolean isEmailLinkSignInEnabled() {
return emailLinkSignInEnabled;
}

/**
* Class used to hold the information needs to make a tenant create request.
Expand Down Expand Up @@ -73,8 +89,8 @@ public static Builder newBuilder() {
}

/**
* Builder class used to construct a create request.
*/
* Builder class used to construct a create request.
*/
@AutoValue.Builder
abstract static class Builder {
public abstract Builder setDisplayName(String displayName);
Expand Down Expand Up @@ -122,8 +138,8 @@ public static Builder newBuilder() {
}

/**
* Builder class used to construct a update request.
*/
* Builder class used to construct a update request.
*/
@AutoValue.Builder
abstract static class Builder {
public abstract Builder setDisplayName(String displayName);
Expand Down
Loading