diff --git a/src/main/java/com/google/firebase/auth/AbstractFirebaseAuth.java b/src/main/java/com/google/firebase/auth/AbstractFirebaseAuth.java index 2f030ccce..d169ae72c 100644 --- a/src/main/java/com/google/firebase/auth/AbstractFirebaseAuth.java +++ b/src/main/java/com/google/firebase/auth/AbstractFirebaseAuth.java @@ -690,8 +690,7 @@ protected UserRecord execute() throws FirebaseAuthException { * UpdateRequest}. * * @param request A non-null {@link UpdateRequest} instance. - * @return A {@link UserRecord} instance corresponding to the updated user account. account, the - * task fails with a {@link FirebaseAuthException}. + * @return A {@link UserRecord} instance corresponding to the updated user account. * @throws NullPointerException if the provided update request is null. * @throws FirebaseAuthException if an error occurs while updating the user account. */ @@ -1053,7 +1052,6 @@ public ApiFuture generateSignInWithEmailLinkAsync( .callAsync(firebaseApp); } - @VisibleForTesting FirebaseUserManager getUserManager() { return this.userManager.get(); } @@ -1074,7 +1072,7 @@ protected String execute() throws FirebaseAuthException { }; } - private Supplier threadSafeMemoize(final Supplier supplier) { + Supplier threadSafeMemoize(final Supplier supplier) { checkNotNull(supplier); return Suppliers.memoize( new Supplier() { diff --git a/src/main/java/com/google/firebase/auth/FirebaseAuth.java b/src/main/java/com/google/firebase/auth/FirebaseAuth.java index 47c9b3f82..653c6e6f5 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseAuth.java +++ b/src/main/java/com/google/firebase/auth/FirebaseAuth.java @@ -31,19 +31,29 @@ * then use it to perform a variety of authentication-related operations, including generating * custom tokens for use by client-side code, verifying Firebase ID Tokens received from clients, or * creating new FirebaseApp instances that are scoped to a particular authentication UID. - * - *

TODO(micahstairs): Add getTenantManager() method. */ public class FirebaseAuth extends AbstractFirebaseAuth { private static final String SERVICE_ID = FirebaseAuth.class.getName(); - private FirebaseAuth(Builder builder) { + private final Supplier tenantManager; + + private FirebaseAuth(final Builder builder) { super( builder.firebaseApp, builder.tokenFactory, builder.idTokenVerifier, builder.cookieVerifier); + tenantManager = threadSafeMemoize(new Supplier() { + @Override + public TenantManager get() { + return new TenantManager(builder.firebaseApp, getUserManager()); + } + }); + } + + public TenantManager getTenantManager() { + return tenantManager.get(); } /** diff --git a/src/main/java/com/google/firebase/auth/FirebaseUserManager.java b/src/main/java/com/google/firebase/auth/FirebaseUserManager.java index 21abdeaf3..eec3a81cc 100644 --- a/src/main/java/com/google/firebase/auth/FirebaseUserManager.java +++ b/src/main/java/com/google/firebase/auth/FirebaseUserManager.java @@ -57,9 +57,8 @@ /** * 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. - * - *

TODO(micahstairs): Consider renaming this to FirebaseAuthManager since this also supports - * tenants. + * + *

TODO(micahstairs): Rename this class to IdentityToolkitClient. * * @see * Google Identity Toolkit @@ -227,7 +226,8 @@ UserImportResult importUsers(UserImportRequest request) throws FirebaseAuthExcep return new UserImportResult(request.getUsersCount(), response); } - ListTenantsResponse listTenants(int maxResults, String pageToken) throws FirebaseAuthException { + ListTenantsResponse listTenants(int maxResults, String pageToken) + throws FirebaseAuthException { ImmutableMap.Builder builder = ImmutableMap.builder() .put("pageSize", maxResults); if (pageToken != null) { diff --git a/src/main/java/com/google/firebase/auth/ListTenantsPage.java b/src/main/java/com/google/firebase/auth/ListTenantsPage.java index 5f5f213fd..51edb6d96 100644 --- a/src/main/java/com/google/firebase/auth/ListTenantsPage.java +++ b/src/main/java/com/google/firebase/auth/ListTenantsPage.java @@ -32,10 +32,10 @@ /** * Represents a page of {@link Tenant} instances. - * + * *

Provides methods for iterating over the tenants in the current page, and calling up * subsequent pages of tenants. - * + * *

Instances of this class are thread-safe and immutable. */ public class ListTenantsPage implements Page { @@ -65,7 +65,7 @@ public boolean hasNextPage() { /** * Returns the string token that identifies the next page. - * + * *

Never returns null. Returns empty string if there are no more pages available to be * retrieved. * @@ -99,7 +99,7 @@ public ListTenantsPage getNextPage() { /** * Returns an {@link Iterable} that facilitates transparently iterating over all the tenants in * the current Firebase project, starting from this page. - * + * *

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. @@ -139,7 +139,7 @@ public Iterator iterator() { /** * An {@link Iterator} that cycles through tenants, one at a time. - * + * *

It buffers the last retrieved batch of tenants in memory. The {@code maxResults} parameter * is an upper bound on the batch size. */ @@ -199,11 +199,9 @@ ListTenantsResponse fetch(int maxResults, String pageToken) static class DefaultTenantSource implements TenantSource { private final FirebaseUserManager userManager; - private final JsonFactory jsonFactory; - DefaultTenantSource(FirebaseUserManager userManager, JsonFactory jsonFactory) { + DefaultTenantSource(FirebaseUserManager userManager) { this.userManager = checkNotNull(userManager, "user manager must not be null"); - this.jsonFactory = checkNotNull(jsonFactory, "json factory must not be null"); } @Override @@ -215,7 +213,7 @@ public ListTenantsResponse fetch(int maxResults, String pageToken) /** * A simple factory class for {@link ListTenantsPage} instances. - * + * *

Performs argument validation before attempting to load any tenant data (which is expensive, * and hence may be performed asynchronously on a separate thread). */ diff --git a/src/main/java/com/google/firebase/auth/Tenant.java b/src/main/java/com/google/firebase/auth/Tenant.java index f64d93a78..366d9e997 100644 --- a/src/main/java/com/google/firebase/auth/Tenant.java +++ b/src/main/java/com/google/firebase/auth/Tenant.java @@ -16,8 +16,13 @@ package com.google.firebase.auth; +import static com.google.common.base.Preconditions.checkArgument; + import com.google.api.client.util.Key; -import com.google.auto.value.AutoValue; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; +import java.util.HashMap; +import java.util.Map; /** * Contains metadata associated with a Firebase tenant. @@ -26,7 +31,7 @@ */ public final class Tenant { - @Key("tenantId") + @Key("name") private String tenantId; @Key("displayName") @@ -55,100 +60,136 @@ public boolean isEmailLinkSignInEnabled() { } /** - * Class used to hold the information needs to make a tenant create request. + * Returns a new {@link UpdateRequest}, which can be used to update the attributes + * of this tenant. + * + * @return a non-null Tenant.UpdateRequest instance. */ - @AutoValue - public abstract static class CreateRequest { + public UpdateRequest updateRequest() { + return new UpdateRequest(getTenantId()); + } + + /** + * A specification class for creating new user accounts. + * + *

Set the initial attributes of the new tenant by calling various setter methods available in + * this class. None of the attributes are required. + */ + public static final class CreateRequest { + + private final Map properties = new HashMap<>(); /** - * Returns the display name of this tenant. + * Creates a new {@link CreateRequest}, which can be used to create a new tenant. * - * @return a non-empty display name string. + *

The returned object should be passed to {@link TenantManager#createTenant(CreateRequest)} + * to register the tenant information persistently. */ - public abstract String getDisplayName(); + public CreateRequest() { } /** - * Returns whether to allow email/password user authentication. + * Sets the display name for the new tenant. * - * @return true if a user can be authenticated using an email and password, and false otherwise. + * @param displayName a non-null, non-empty display name string. */ - public abstract boolean isPasswordSignInAllowed(); + public CreateRequest setDisplayName(String displayName) { + checkArgument(!Strings.isNullOrEmpty(displayName), "display name must not be null or empty"); + properties.put("displayName", displayName); + return this; + } /** - * Returns whether to enable email link user authentication. + * Sets whether to allow email/password user authentication. * - * @return true if a user can be authenticated using an email link, and false otherwise. + * @param passwordSignInAllowed a boolean indicating whether users can be authenticated using + * an email and password, and false otherwise. */ - public abstract boolean isEmailLinkSignInEnabled(); + public CreateRequest setPasswordSignInAllowed(boolean passwordSignInAllowed) { + properties.put("allowPasswordSignup", passwordSignInAllowed); + return this; + } /** - * Returns a builder for a tenant create request. + * Sets whether to enable email link user authentication. + * + * @param emailLinkSignInEnabled a boolean indicating whether users can be authenticated using + * an email link, and false otherwise. */ - public static Builder newBuilder() { - return new AutoValue_Tenant_CreateRequest.Builder(); + public CreateRequest setEmailLinkSignInEnabled(boolean emailLinkSignInEnabled) { + properties.put("enableEmailLinkSignin", emailLinkSignInEnabled); + return this; } - /** - * Builder class used to construct a create request. - */ - @AutoValue.Builder - abstract static class Builder { - public abstract Builder setDisplayName(String displayName); - - public abstract Builder setPasswordSignInAllowed(boolean allowPasswordSignIn); - - public abstract Builder setEmailLinkSignInEnabled(boolean enableEmailLinkSignIn); - - public abstract CreateRequest build(); + Map getProperties() { + return ImmutableMap.copyOf(properties); } } /** - * Class used to hold the information needs to make a tenant update request. + * A class for updating the attributes of an existing tenant. + * + *

An instance of this class can be obtained via a {@link Tenant} object, or from a tenant ID + * string. Specify the changes to be made to the tenant by calling the various setter methods + * available in this class. */ - @AutoValue - public abstract static class UpdateRequest { + public static final class UpdateRequest { + + private final Map properties = new HashMap<>(); /** - * Returns the display name of this tenant. + * Creates a new {@link UpdateRequest}, which can be used to update the attributes of the + * of the tenant identified by the specified tenant ID. + * + *

This method allows updating attributes of a tenant account, without first having to call + * {@link TenantManager#getTenant(String)}. * - * @return a non-empty display name string. + * @param tenantId a non-null, non-empty tenant ID string. + * @throws IllegalArgumentException If the tenant ID is null or empty. */ - public abstract String getDisplayName(); + public UpdateRequest(String tenantId) { + checkArgument(!Strings.isNullOrEmpty(tenantId), "tenant ID must not be null or empty"); + properties.put("name", tenantId); + } + + String getTenantId() { + return (String) properties.get("name"); + } /** - * Returns whether to allow email/password user authentication. + * Sets the display name of the existingtenant. * - * @return true if a user can be authenticated using an email and password, and false otherwise. + * @param displayName a non-null, non-empty display name string. */ - public abstract boolean isPasswordSignInAllowed(); + public UpdateRequest setDisplayName(String displayName) { + checkArgument(!Strings.isNullOrEmpty(displayName), "display name must not be null or empty"); + properties.put("displayName", displayName); + return this; + } /** - * Returns whether to enable email link user authentication. + * Sets whether to allow email/password user authentication. * - * @return true if a user can be authenticated using an email link, and false otherwise. + * @param passwordSignInAllowed a boolean indicating whether users can be authenticated using + * an email and password, and false otherwise. */ - public abstract boolean isEmailLinkSignInEnabled(); + public UpdateRequest setPasswordSignInAllowed(boolean passwordSignInAllowed) { + properties.put("allowPasswordSignup", passwordSignInAllowed); + return this; + } /** - * Returns a builder for a tenant update request. + * Sets whether to enable email link user authentication. + * + * @param emailLinkSignInEnabled a boolean indicating whether users can be authenticated using + * an email link, and false otherwise. */ - public static Builder newBuilder() { - return new AutoValue_Tenant_UpdateRequest.Builder(); + public UpdateRequest setEmailLinkSignInEnabled(boolean emailLinkSignInEnabled) { + properties.put("enableEmailLinkSignin", emailLinkSignInEnabled); + return this; } - /** - * Builder class used to construct a update request. - */ - @AutoValue.Builder - abstract static class Builder { - public abstract Builder setDisplayName(String displayName); - - public abstract Builder setPasswordSignInAllowed(boolean allowPasswordSignIn); - - public abstract Builder setEmailLinkSignInEnabled(boolean enableEmailLinkSignIn); - - public abstract UpdateRequest build(); + Map getProperties() { + return ImmutableMap.copyOf(properties); } } } diff --git a/src/main/java/com/google/firebase/auth/TenantManager.java b/src/main/java/com/google/firebase/auth/TenantManager.java new file mode 100644 index 000000000..38d64f15d --- /dev/null +++ b/src/main/java/com/google/firebase/auth/TenantManager.java @@ -0,0 +1,118 @@ +/* + * 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.checkNotNull; + +import com.google.api.client.json.JsonFactory; +import com.google.api.core.ApiFuture; +import com.google.firebase.FirebaseApp; +import com.google.firebase.auth.ListTenantsPage.DefaultTenantSource; +import com.google.firebase.auth.ListTenantsPage.PageFactory; +import com.google.firebase.auth.ListTenantsPage.TenantSource; +import com.google.firebase.auth.Tenant.CreateRequest; +import com.google.firebase.auth.Tenant.UpdateRequest; +import com.google.firebase.internal.CallableOperation; +import com.google.firebase.internal.NonNull; +import com.google.firebase.internal.Nullable; + +/** + * This class can be used to perform a variety of tenant-related operations, including creating, + * updating, and listing tenants. + * + * TODO(micahstairs): Implement the following methods: getAuthForTenant(), getTenant(), + * deleteTenant(), createTenant(), and updateTenant(). + */ +public class TenantManager { + + private final FirebaseApp firebaseApp; + private final FirebaseUserManager userManager; + + public TenantManager(FirebaseApp firebaseApp, FirebaseUserManager userManager) { + this.firebaseApp = firebaseApp; + this.userManager = userManager; + } + + /** + * Gets a page of tenants starting from the specified {@code pageToken}. Page size will be limited + * to 1000 tenants. + * + * @param pageToken A non-empty page token string, or null to retrieve the first page of tenants. + * @return A {@link ListTenantsPage} instance. + * @throws IllegalArgumentException If the specified page token is empty. + * @throws FirebaseAuthException If an error occurs while retrieving tenant data. + */ + public ListTenantsPage listTenants(@Nullable String pageToken) throws FirebaseAuthException { + return listTenants(pageToken, FirebaseUserManager.MAX_LIST_TENANTS_RESULTS); + } + + /** + * Gets a page of tenants starting from the specified {@code pageToken}. + * + * @param pageToken A non-empty page token string, or null to retrieve the first page of tenants. + * @param maxResults Maximum number of tenants to include in the returned page. This may not + * exceed 1000. + * @return A {@link ListTenantsPage} instance. + * @throws IllegalArgumentException If the specified page token is empty, or max results value is + * invalid. + * @throws FirebaseAuthException If an error occurs while retrieving tenant data. + */ + public ListTenantsPage listTenants(@Nullable String pageToken, int maxResults) + throws FirebaseAuthException { + return listTenantsOp(pageToken, maxResults).call(); + } + + /** + * Similar to {@link #listTenants(String)} but performs the operation asynchronously. + * + * @param pageToken A non-empty page token string, or null to retrieve the first page of tenants. + * @return An {@code ApiFuture} which will complete successfully with a {@link ListTenantsPage} + * instance. If an error occurs while retrieving tenant data, the future throws an exception. + * @throws IllegalArgumentException If the specified page token is empty. + */ + public ApiFuture listTenantsAsync(@Nullable String pageToken) { + return listTenantsAsync(pageToken, FirebaseUserManager.MAX_LIST_TENANTS_RESULTS); + } + + /** + * Similar to {@link #listTenants(String, int)} but performs the operation asynchronously. + * + * @param pageToken A non-empty page token string, or null to retrieve the first page of tenants. + * @param maxResults Maximum number of tenants to include in the returned page. This may not + * exceed 1000. + * @return An {@code ApiFuture} which will complete successfully with a {@link ListTenantsPage} + * instance. If an error occurs while retrieving tenant data, the future throws an exception. + * @throws IllegalArgumentException If the specified page token is empty, or max results value is + * invalid. + */ + public ApiFuture listTenantsAsync(@Nullable String pageToken, int maxResults) { + return listTenantsOp(pageToken, maxResults).callAsync(firebaseApp); + } + + private CallableOperation listTenantsOp( + @Nullable final String pageToken, final int maxResults) { + // TODO(micahstairs): Add a check to make sure the app has not been destroyed yet. + final TenantSource tenantSource = new DefaultTenantSource(userManager); + final PageFactory factory = new PageFactory(tenantSource, maxResults, pageToken); + return new CallableOperation() { + @Override + protected ListTenantsPage execute() throws FirebaseAuthException { + return factory.create(); + } + }; + } +} diff --git a/src/main/java/com/google/firebase/auth/UserRecord.java b/src/main/java/com/google/firebase/auth/UserRecord.java index e00450079..1e199e015 100644 --- a/src/main/java/com/google/firebase/auth/UserRecord.java +++ b/src/main/java/com/google/firebase/auth/UserRecord.java @@ -357,10 +357,10 @@ public CreateRequest setEmailVerified(boolean emailVerified) { /** * Sets the display name for the new user. * - * @param displayName a non-null, non-empty display name string. + * @param displayName a non-null display name string. */ public CreateRequest setDisplayName(String displayName) { - checkNotNull(displayName, "displayName cannot be null or empty"); + checkNotNull(displayName, "displayName cannot be null"); properties.put("displayName", displayName); return this; } diff --git a/src/main/java/com/google/firebase/auth/internal/ListTenantsResponse.java b/src/main/java/com/google/firebase/auth/internal/ListTenantsResponse.java index 7abb79805..83460a234 100644 --- a/src/main/java/com/google/firebase/auth/internal/ListTenantsResponse.java +++ b/src/main/java/com/google/firebase/auth/internal/ListTenantsResponse.java @@ -17,20 +17,24 @@ package com.google.firebase.auth.internal; import com.google.api.client.util.Key; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.ImmutableList; +import com.google.firebase.auth.ListTenantsPage; import com.google.firebase.auth.Tenant; import java.util.List; /** * JSON data binding for ListTenantsResponse messages sent by Google identity toolkit service. */ -public class ListTenantsResponse { +public final class ListTenantsResponse { @Key("tenants") - private List tenants; + private List tenants = ImmutableList.of(); // Default to empty list. @Key("pageToken") - private String pageToken; + private String pageToken = ""; // Default to ListTenantsPage.END_OF_LIST. + @VisibleForTesting public ListTenantsResponse(List tenants, String pageToken) { this.tenants = tenants; this.pageToken = pageToken; diff --git a/src/test/java/com/google/firebase/auth/FirebaseUserManagerTest.java b/src/test/java/com/google/firebase/auth/FirebaseUserManagerTest.java index 97ff7447a..86332ad69 100644 --- a/src/test/java/com/google/firebase/auth/FirebaseUserManagerTest.java +++ b/src/test/java/com/google/firebase/auth/FirebaseUserManagerTest.java @@ -430,6 +430,52 @@ public void testImportUsersLargeList() { } } + @Test + public void testListTenants() throws Exception { + final TestResponseInterceptor interceptor = initializeAppForUserManagement( + TestUtils.loadResource("listTenants.json")); + ListTenantsPage page = + FirebaseAuth.getInstance().getTenantManager().listTenantsAsync(null, 999).get(); + assertEquals(2, Iterables.size(page.getValues())); + for (Tenant tenant : page.getValues()) { + checkTenant(tenant); + } + assertEquals("", page.getNextPageToken()); + checkRequestHeaders(interceptor); + + GenericUrl url = interceptor.getResponse().getRequest().getUrl(); + assertEquals(999, url.getFirst("pageSize")); + assertNull(url.getFirst("pageToken")); + } + + @Test + public void testListTenantsWithPageToken() throws Exception { + final TestResponseInterceptor interceptor = initializeAppForUserManagement( + TestUtils.loadResource("listTenants.json")); + ListTenantsPage page = + FirebaseAuth.getInstance().getTenantManager().listTenantsAsync("token", 999).get(); + assertEquals(2, Iterables.size(page.getValues())); + for (Tenant tenant : page.getValues()) { + checkTenant(tenant); + } + assertEquals("", page.getNextPageToken()); + checkRequestHeaders(interceptor); + + GenericUrl url = interceptor.getResponse().getRequest().getUrl(); + assertEquals(999, url.getFirst("pageSize")); + assertEquals("token", url.getFirst("pageToken")); + } + + @Test + public void testListZeroTenants() throws Exception { + final TestResponseInterceptor interceptor = initializeAppForUserManagement("{}"); + ListTenantsPage page = + FirebaseAuth.getInstance().getTenantManager().listTenantsAsync(null).get(); + assertTrue(Iterables.isEmpty(page.getValues())); + assertEquals("", page.getNextPageToken()); + checkRequestHeaders(interceptor); + } + @Test public void testCreateSessionCookie() throws Exception { TestResponseInterceptor interceptor = initializeAppForUserManagement( @@ -1264,6 +1310,13 @@ private static void checkUserRecord(UserRecord userRecord) { assertEquals("gold", claims.get("package")); } + private static void checkTenant(Tenant tenant) { + assertEquals("TENANT_ID", tenant.getTenantId()); + assertEquals("DISPLAY_NAME", tenant.getDisplayName()); + assertTrue(tenant.isPasswordSignInAllowed()); + assertFalse(tenant.isEmailLinkSignInEnabled()); + } + private static void checkRequestHeaders(TestResponseInterceptor interceptor) { HttpHeaders headers = interceptor.getResponse().getRequest().getHeaders(); String auth = "Bearer " + TEST_TOKEN; @@ -1276,5 +1329,5 @@ private static void checkRequestHeaders(TestResponseInterceptor interceptor) { private interface UserManagerOp { void call(FirebaseAuth auth) throws Exception; } - + } diff --git a/src/test/java/com/google/firebase/auth/ListTenantsPageTest.java b/src/test/java/com/google/firebase/auth/ListTenantsPageTest.java index 227e3dca4..c1d09bc52 100644 --- a/src/test/java/com/google/firebase/auth/ListTenantsPageTest.java +++ b/src/test/java/com/google/firebase/auth/ListTenantsPageTest.java @@ -321,7 +321,7 @@ public void testInvalidMaxResults() throws IOException { private static Tenant newTenant(String tenantId) throws IOException { return Utils.getDefaultJsonFactory().fromString( - String.format("{\"tenantId\":\"%s\"}", tenantId), Tenant.class); + String.format("{\"name\":\"%s\"}", tenantId), Tenant.class); } private static class TestTenantSource implements ListTenantsPage.TenantSource { diff --git a/src/test/java/com/google/firebase/auth/TenantTest.java b/src/test/java/com/google/firebase/auth/TenantTest.java new file mode 100644 index 000000000..22209e8ad --- /dev/null +++ b/src/test/java/com/google/firebase/auth/TenantTest.java @@ -0,0 +1,97 @@ +/* + * 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.firebase.auth.Tenant.UpdateRequest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.google.api.client.googleapis.util.Utils; +import com.google.api.client.json.JsonFactory; +import java.io.IOException; +import java.util.Map; +import org.junit.Test; + +public class TenantTest { + + private static final JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); + + private static final String TENANT_JSON_STRING = + "{" + + "\"name\":\"TENANT_ID\"," + + "\"displayName\":\"DISPLAY_NAME\"," + + "\"allowPasswordSignup\":true," + + "\"enableEmailLinkSignin\":false" + + "}"; + + @Test + public void testJsonSerialization() throws IOException { + Tenant tenant = jsonFactory.fromString(TENANT_JSON_STRING, Tenant.class); + + assertEquals(tenant.getTenantId(), "TENANT_ID"); + assertEquals(tenant.getDisplayName(), "DISPLAY_NAME"); + assertTrue(tenant.isPasswordSignInAllowed()); + assertFalse(tenant.isEmailLinkSignInEnabled()); + } + + @Test + public void testUpdateRequestFromTenant() throws IOException { + Tenant tenant = jsonFactory.fromString(TENANT_JSON_STRING, Tenant.class); + + Tenant.UpdateRequest updateRequest = tenant.updateRequest(); + + assertEquals("TENANT_ID", updateRequest.getTenantId()); + Map properties = updateRequest.getProperties(); + assertEquals(properties.size(), 1); + assertEquals("TENANT_ID", (String) properties.get("name")); + } + + @Test + public void testUpdateRequestFromTenantId() throws IOException { + Tenant.UpdateRequest updateRequest = new Tenant.UpdateRequest("TENANT_ID"); + updateRequest + .setDisplayName("DISPLAY_NAME") + .setPasswordSignInAllowed(false) + .setEmailLinkSignInEnabled(true); + + assertEquals("TENANT_ID", updateRequest.getTenantId()); + Map properties = updateRequest.getProperties(); + assertEquals(properties.size(), 4); + assertEquals("TENANT_ID", (String) properties.get("name")); + assertEquals("DISPLAY_NAME", (String) properties.get("displayName")); + assertFalse((boolean) properties.get("allowPasswordSignup")); + assertTrue((boolean) properties.get("enableEmailLinkSignin")); + } + + @Test + public void testCreateRequest() throws IOException { + Tenant.CreateRequest createRequest = new Tenant.CreateRequest(); + createRequest + .setDisplayName("DISPLAY_NAME") + .setPasswordSignInAllowed(false) + .setEmailLinkSignInEnabled(true); + + Map properties = createRequest.getProperties(); + assertEquals(properties.size(), 3); + assertEquals("DISPLAY_NAME", (String) properties.get("displayName")); + assertFalse((boolean) properties.get("allowPasswordSignup")); + assertTrue((boolean) properties.get("enableEmailLinkSignin")); + } +} + diff --git a/src/test/resources/listTenants.json b/src/test/resources/listTenants.json new file mode 100644 index 000000000..997cd2979 --- /dev/null +++ b/src/test/resources/listTenants.json @@ -0,0 +1,17 @@ +{ + "tenants" : [ { + "name" : "TENANT_ID", + "displayName" : "DISPLAY_NAME", + "allowPasswordSignup" : true, + "enableEmailLinkSignin" : false, + "disableAuth" : true, + "enableAnonymousUser" : false + }, { + "name" : "TENANT_ID", + "displayName" : "DISPLAY_NAME", + "allowPasswordSignup" : true, + "enableEmailLinkSignin" : false, + "disableAuth" : true, + "enableAnonymousUser" : false + } ] +}