Search in sources :

Example 1 with AuthCategory

use of com.amplifyframework.auth.AuthCategory in project amplify-android by aws-amplify.

the class MultiAuthSyncEngineInstrumentationTest method configure.

/**
 * Method used to configure each scenario.
 * @param modelType The model type.
 * @param signInToCognito Does the test scenario require the user to be logged in with user pools.
 * @param signInWithOidc Does the test scenario require the user to be logged in with an OIDC provider.
 * @param expectedAuthType The auth type that should succeed for the test.
 * @throws AmplifyException No expected.
 * @throws IOException Not expected.
 */
private void configure(Class<? extends Model> modelType, boolean signInToCognito, boolean signInWithOidc, AuthorizationType expectedAuthType) throws AmplifyException, IOException {
    Amplify.addPlugin(new AndroidLoggingPlugin(LogLevel.VERBOSE));
    String tag = modelType.getSimpleName();
    MultiAuthTestModelProvider modelProvider = MultiAuthTestModelProvider.getInstance(Collections.singletonList(modelType));
    SchemaRegistry schemaRegistry = SchemaRegistry.instance();
    ModelSchema modelSchema = ModelSchema.fromModelClass(modelType);
    schemaRegistry.register(modelType.getSimpleName(), modelSchema);
    StrictMode.enable();
    Context context = getApplicationContext();
    @RawRes int configResourceId = Resources.getRawResourceId(context, "amplifyconfiguration");
    AmplifyConfiguration amplifyConfiguration = AmplifyConfiguration.fromConfigFile(context, configResourceId);
    readCredsFromConfig(context);
    // Setup an auth plugin
    CategoryConfiguration authCategoryConfiguration = amplifyConfiguration.forCategoryType(CategoryType.AUTH);
    // Turn off persistence so the mobile client's state for one test does not interfere with the others.
    try {
        authCategoryConfiguration.getPluginConfig("awsCognitoAuthPlugin").getJSONObject("Auth").getJSONObject("Default").put("Persistence", false);
    } catch (JSONException exception) {
        exception.printStackTrace();
        fail();
        return;
    }
    AuthCategory authCategory = new AuthCategory();
    AWSCognitoAuthPlugin authPlugin = new AWSCognitoAuthPlugin();
    authCategory.addPlugin(authPlugin);
    authCategory.configure(authCategoryConfiguration, context);
    auth = SynchronousAuth.delegatingTo(authCategory);
    if (signInToCognito) {
        Log.v(tag, "Test requires signIn.");
        AuthSignInResult authSignInResult = auth.signIn(cognitoUser, cognitoPassword);
        if (!authSignInResult.isSignInComplete()) {
            fail("Unable to complete initial sign-in");
        }
    }
    if (signInWithOidc) {
        oidcLogin();
        if (token.get() == null) {
            fail("Unable to autenticate with OIDC provider");
        }
    }
    // Setup an API
    DefaultCognitoUserPoolsAuthProvider cognitoProvider = new DefaultCognitoUserPoolsAuthProvider(authPlugin.getEscapeHatch());
    CategoryConfiguration apiCategoryConfiguration = amplifyConfiguration.forCategoryType(CategoryType.API);
    ApiAuthProviders apiAuthProviders = ApiAuthProviders.builder().cognitoUserPoolsAuthProvider(cognitoProvider).awsCredentialsProvider(authPlugin.getEscapeHatch()).oidcAuthProvider(token::get).build();
    ApiCategory apiCategory = new ApiCategory();
    requestInterceptor = new HttpRequestInterceptor(expectedAuthType);
    apiCategory.addPlugin(AWSApiPlugin.builder().configureClient("DataStoreIntegTestsApi", okHttpClientBuilder -> okHttpClientBuilder.addInterceptor(requestInterceptor)).apiAuthProviders(apiAuthProviders).build());
    apiCategory.configure(apiCategoryConfiguration, context);
    api = SynchronousApi.delegatingTo(apiCategory);
    // Setup DataStore
    DataStoreConfiguration dsConfig = DataStoreConfiguration.builder().errorHandler(exception -> Log.e(tag, "DataStore error handler received an error.", exception)).syncExpression(modelSchema.getName(), () -> Where.id("FAKE_ID").getQueryPredicate()).build();
    CategoryConfiguration dataStoreCategoryConfiguration = AmplifyConfiguration.fromConfigFile(context, configResourceId).forCategoryType(CategoryType.DATASTORE);
    String databaseName = "IntegTest" + modelType.getSimpleName() + ".db";
    SQLiteStorageAdapter sqLiteStorageAdapter = TestStorageAdapter.create(schemaRegistry, modelProvider, databaseName);
    AWSDataStorePlugin awsDataStorePlugin = AWSDataStorePlugin.builder().storageAdapter(sqLiteStorageAdapter).modelProvider(modelProvider).apiCategory(apiCategory).authModeStrategy(AuthModeStrategyType.MULTIAUTH).schemaRegistry(schemaRegistry).dataStoreConfiguration(dsConfig).build();
    DataStoreCategory dataStoreCategory = new DataStoreCategory();
    dataStoreCategory.addPlugin(awsDataStorePlugin);
    dataStoreCategory.configure(dataStoreCategoryConfiguration, context);
    dataStoreCategory.initialize(context);
    dataStore = SynchronousDataStore.delegatingTo(dataStoreCategory);
}
Also used : MultiAuthTestModelProvider(com.amplifyframework.testmodels.multiauth.MultiAuthTestModelProvider) ApplicationProvider.getApplicationContext(androidx.test.core.app.ApplicationProvider.getApplicationContext) Context(android.content.Context) AmplifyException(com.amplifyframework.AmplifyException) ApplicationProvider.getApplicationContext(androidx.test.core.app.ApplicationProvider.getApplicationContext) AuthorizationType(com.amplifyframework.api.aws.AuthorizationType) PrivatePrivatePublicUPIAMIAMPost(com.amplifyframework.testmodels.multiauth.PrivatePrivatePublicUPIAMIAMPost) PublicPublicIAMAPIPost(com.amplifyframework.testmodels.multiauth.PublicPublicIAMAPIPost) AuthSignOutOptions(com.amplifyframework.auth.options.AuthSignOutOptions) DataStoreHubEventFilters.publicationOf(com.amplifyframework.datastore.DataStoreHubEventFilters.publicationOf) AndroidLoggingPlugin(com.amplifyframework.logging.AndroidLoggingPlugin) OwnerPublicUPAPIPost(com.amplifyframework.testmodels.multiauth.OwnerPublicUPAPIPost) JSONException(org.json.JSONException) AWSApiPlugin(com.amplifyframework.api.aws.AWSApiPlugin) JSONObject(org.json.JSONObject) AmplifyConfiguration(com.amplifyframework.core.AmplifyConfiguration) Map(java.util.Map) PrivateUPPost(com.amplifyframework.testmodels.multiauth.PrivateUPPost) Assert.fail(org.junit.Assert.fail) Log(android.util.Log) ResponseBody(okhttp3.ResponseBody) MultiAuthTestModelProvider(com.amplifyframework.testmodels.multiauth.MultiAuthTestModelProvider) Interceptor(okhttp3.Interceptor) AfterClass(org.junit.AfterClass) Request(okhttp3.Request) GroupUPPost(com.amplifyframework.testmodels.multiauth.GroupUPPost) HubChannel(com.amplifyframework.hub.HubChannel) SerializedModel(com.amplifyframework.core.model.SerializedModel) OwnerPublicOIDAPIPost(com.amplifyframework.testmodels.multiauth.OwnerPublicOIDAPIPost) OwnerPrivateUPIAMPost(com.amplifyframework.testmodels.multiauth.OwnerPrivateUPIAMPost) DefaultCognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.DefaultCognitoUserPoolsAuthProvider) UUID(java.util.UUID) ApiCategory(com.amplifyframework.api.ApiCategory) PrivatePublicComboUPPost(com.amplifyframework.testmodels.multiauth.PrivatePublicComboUPPost) Logger(com.amplifyframework.logging.Logger) CognitoJWTParser(com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoJWTParser) Assert.assertFalse(org.junit.Assert.assertFalse) RandomString(com.amplifyframework.testutils.random.RandomString) SynchronousAuth(com.amplifyframework.testutils.sync.SynchronousAuth) LogLevel(com.amplifyframework.logging.LogLevel) PublicAPIPost(com.amplifyframework.testmodels.multiauth.PublicAPIPost) Context(android.content.Context) GroupPrivatePublicUPIAMAPIPost(com.amplifyframework.testmodels.multiauth.GroupPrivatePublicUPIAMAPIPost) AuthCategory(com.amplifyframework.auth.AuthCategory) HashMap(java.util.HashMap) ApiAuthProviders(com.amplifyframework.api.aws.ApiAuthProviders) Resources(com.amplifyframework.testutils.Resources) HubAccumulator(com.amplifyframework.testutils.HubAccumulator) SynchronousApi(com.amplifyframework.testutils.sync.SynchronousApi) IdToken(com.google.auth.oauth2.IdToken) AtomicReference(java.util.concurrent.atomic.AtomicReference) Headers(okhttp3.Headers) RequestBody(okhttp3.RequestBody) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) RawRes(androidx.annotation.RawRes) PrivatePublicUPIAMPost(com.amplifyframework.testmodels.multiauth.PrivatePublicUPIAMPost) AuthSignInResult(com.amplifyframework.auth.result.AuthSignInResult) Author(com.amplifyframework.testmodels.commentsblog.Author) ModelSchema(com.amplifyframework.core.model.ModelSchema) PrivatePublicComboAPIPost(com.amplifyframework.testmodels.multiauth.PrivatePublicComboAPIPost) Response(okhttp3.Response) CategoryConfiguration(com.amplifyframework.core.category.CategoryConfiguration) PublicIAMPost(com.amplifyframework.testmodels.multiauth.PublicIAMPost) Amplify(com.amplifyframework.core.Amplify) PrivatePrivatePublicUPIAMAPIPost(com.amplifyframework.testmodels.multiauth.PrivatePrivatePublicUPIAMAPIPost) SynchronousDataStore(com.amplifyframework.testutils.sync.SynchronousDataStore) Buffer(okio.Buffer) CategoryType(com.amplifyframework.core.category.CategoryType) GroupPrivateUPIAMPost(com.amplifyframework.testmodels.multiauth.GroupPrivateUPIAMPost) PrivatePublicUPAPIPost(com.amplifyframework.testmodels.multiauth.PrivatePublicUPAPIPost) Model(com.amplifyframework.core.model.Model) AWSCognitoAuthPlugin(com.amplifyframework.auth.cognito.AWSCognitoAuthPlugin) Test(org.junit.Test) IOException(java.io.IOException) Where(com.amplifyframework.core.model.query.Where) SQLiteStorageAdapter(com.amplifyframework.datastore.storage.sqlite.SQLiteStorageAdapter) GroupPublicUPIAMPost(com.amplifyframework.testmodels.multiauth.GroupPublicUPIAMPost) PrivatePrivateUPIAMPost(com.amplifyframework.testmodels.multiauth.PrivatePrivateUPIAMPost) TimeUnit(java.util.concurrent.TimeUnit) AuthModeStrategyType(com.amplifyframework.api.aws.AuthModeStrategyType) OwnerOIDCPost(com.amplifyframework.testmodels.multiauth.OwnerOIDCPost) OwnerPrivatePublicUPIAMAPIPost(com.amplifyframework.testmodels.multiauth.OwnerPrivatePublicUPIAMAPIPost) TestStorageAdapter(com.amplifyframework.datastore.storage.sqlite.TestStorageAdapter) PrivatePublicPublicUPAPIIAMPost(com.amplifyframework.testmodels.multiauth.PrivatePublicPublicUPAPIIAMPost) Resources.readJsonResourceFromId(com.amplifyframework.core.Resources.readJsonResourceFromId) DataStoreHubEventFilters.networkStatusFailure(com.amplifyframework.datastore.DataStoreHubEventFilters.networkStatusFailure) GroupPublicUPAPIPost(com.amplifyframework.testmodels.multiauth.GroupPublicUPAPIPost) OwnerUPPost(com.amplifyframework.testmodels.multiauth.OwnerUPPost) Collections(java.util.Collections) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) JSONArray(org.json.JSONArray) RawRes(androidx.annotation.RawRes) AmplifyConfiguration(com.amplifyframework.core.AmplifyConfiguration) DefaultCognitoUserPoolsAuthProvider(com.amplifyframework.api.aws.sigv4.DefaultCognitoUserPoolsAuthProvider) SQLiteStorageAdapter(com.amplifyframework.datastore.storage.sqlite.SQLiteStorageAdapter) CategoryConfiguration(com.amplifyframework.core.category.CategoryConfiguration) JSONException(org.json.JSONException) RandomString(com.amplifyframework.testutils.random.RandomString) AWSCognitoAuthPlugin(com.amplifyframework.auth.cognito.AWSCognitoAuthPlugin) AndroidLoggingPlugin(com.amplifyframework.logging.AndroidLoggingPlugin) ModelSchema(com.amplifyframework.core.model.ModelSchema) AuthCategory(com.amplifyframework.auth.AuthCategory) ApiCategory(com.amplifyframework.api.ApiCategory) ApiAuthProviders(com.amplifyframework.api.aws.ApiAuthProviders) AuthSignInResult(com.amplifyframework.auth.result.AuthSignInResult) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry)

Example 2 with AuthCategory

use of com.amplifyframework.auth.AuthCategory in project amplify-android by aws-amplify.

the class AuthComponentConfigureTest method setup.

/**
 * Get all setup for the future tests with mocks and a standard response for tokens.
 * @throws AmplifyException If add plugin fails
 */
@Before
public void setup() throws AmplifyException {
    mobileClient = mock(AWSMobileClient.class);
    authCategory = new AuthCategory();
    authCategory.addPlugin(new AWSCognitoAuthPlugin(mobileClient, USER_SUB));
}
Also used : AuthCategory(com.amplifyframework.auth.AuthCategory) AWSMobileClient(com.amazonaws.mobile.client.AWSMobileClient) Before(org.junit.Before)

Example 3 with AuthCategory

use of com.amplifyframework.auth.AuthCategory in project amplify-android by aws-amplify.

the class AuthComponentTest method setup.

/**
 * Get all setup for the future tests with mocks and a standard response for tokens.
 * @throws AmplifyException If add plugin fails
 * @throws JSONException has to be declared as part of creating a test JSON object
 */
@Before
public void setup() throws AmplifyException, JSONException {
    mobileClient = mock(AWSMobileClient.class);
    authCategory = new AuthCategory();
    authCategory.addPlugin(new AWSCognitoAuthPlugin(mobileClient, USER_SUB));
    Map<String, String> additionalInfoMap = Collections.singletonMap("token", ACCESS_TOKEN);
    UserStateDetails userStateDetails = new UserStateDetails(UserState.SIGNED_IN, additionalInfoMap);
    Context context = getApplicationContext();
    JSONObject pluginConfig = new JSONObject().put("TestKey", "TestVal");
    pluginConfig.put("UserAgentOverride", UserAgent.string());
    JSONObject json = new JSONObject().put("plugins", new JSONObject().put(PLUGIN_KEY, pluginConfig));
    AuthCategoryConfiguration authConfig = new AuthCategoryConfiguration();
    authConfig.populateFromJSON(json);
    doAnswer(invocation -> {
        Callback<UserStateDetails> callback = invocation.getArgument(2);
        callback.onResult(userStateDetails);
        return null;
    }).when(mobileClient).initialize(any(), any(), any());
    authCategory.configure(authConfig, context);
    authCategory.initialize(context);
    synchronousAuth = SynchronousAuth.delegatingTo(authCategory);
}
Also used : ApplicationProvider.getApplicationContext(androidx.test.core.app.ApplicationProvider.getApplicationContext) Context(android.content.Context) AuthCategory(com.amplifyframework.auth.AuthCategory) JSONObject(org.json.JSONObject) AuthCategoryConfiguration(com.amplifyframework.auth.AuthCategoryConfiguration) AWSMobileClient(com.amazonaws.mobile.client.AWSMobileClient) RandomString(com.amplifyframework.testutils.random.RandomString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) UserStateDetails(com.amazonaws.mobile.client.UserStateDetails) Before(org.junit.Before)

Example 4 with AuthCategory

use of com.amplifyframework.auth.AuthCategory in project amplify-android by aws-amplify.

the class TestCategory method forPlugin.

/**
 * Creates a test category to be used for testing. A category containing given
 * plugin will be used to register and configure the plugin. The category
 * instance will have the same Amplify category-type as registered plugin,
 * and it should be cast appropriately before usage.
 *
 * <pre>
 *     AuthCategory auth = (AuthCategory) TestCategory.forPlugin(plugin);
 * </pre>
 *
 * Resulting category object should not be used in production.
 *
 * @param plugin Plugin to register in the category. The resulting category
 *               will share the category type with this plugin.
 * @param <P> Type of plugin being registered.
 * @return An Amplify category object with the given plugin registered and
 *         configured. The category will be of same type as registered plugin
 *         and it should be cast to correct type before usage.
 * @throws AmplifyException if category fails to configure given plugin.
 */
public static <P extends Plugin<?>> Category<?> forPlugin(P plugin) throws AmplifyException {
    CategoryType categoryType = plugin.getCategoryType();
    Category<Plugin<?>> category = (Category<Plugin<?>>) fromCategoryType(categoryType);
    category.addPlugin(plugin);
    CategoryConfiguration config = AmplifyConfiguration.fromConfigFile(context()).forCategoryType(categoryType);
    category.configure(config, context());
    category.initialize(context());
    return category;
}
Also used : Category(com.amplifyframework.core.category.Category) AnalyticsCategory(com.amplifyframework.analytics.AnalyticsCategory) GeoCategory(com.amplifyframework.geo.GeoCategory) StorageCategory(com.amplifyframework.storage.StorageCategory) AuthCategory(com.amplifyframework.auth.AuthCategory) LoggingCategory(com.amplifyframework.logging.LoggingCategory) ApiCategory(com.amplifyframework.api.ApiCategory) HubCategory(com.amplifyframework.hub.HubCategory) PredictionsCategory(com.amplifyframework.predictions.PredictionsCategory) DataStoreCategory(com.amplifyframework.datastore.DataStoreCategory) CategoryConfiguration(com.amplifyframework.core.category.CategoryConfiguration) CategoryType(com.amplifyframework.core.category.CategoryType) Plugin(com.amplifyframework.core.plugin.Plugin)

Aggregations

AuthCategory (com.amplifyframework.auth.AuthCategory)4 Context (android.content.Context)2 ApplicationProvider.getApplicationContext (androidx.test.core.app.ApplicationProvider.getApplicationContext)2 AWSMobileClient (com.amazonaws.mobile.client.AWSMobileClient)2 ApiCategory (com.amplifyframework.api.ApiCategory)2 CategoryConfiguration (com.amplifyframework.core.category.CategoryConfiguration)2 CategoryType (com.amplifyframework.core.category.CategoryType)2 RandomString (com.amplifyframework.testutils.random.RandomString)2 JSONObject (org.json.JSONObject)2 Before (org.junit.Before)2 Log (android.util.Log)1 RawRes (androidx.annotation.RawRes)1 UserStateDetails (com.amazonaws.mobile.client.UserStateDetails)1 CognitoJWTParser (com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoJWTParser)1 AmplifyException (com.amplifyframework.AmplifyException)1 AnalyticsCategory (com.amplifyframework.analytics.AnalyticsCategory)1 AWSApiPlugin (com.amplifyframework.api.aws.AWSApiPlugin)1 ApiAuthProviders (com.amplifyframework.api.aws.ApiAuthProviders)1 AuthModeStrategyType (com.amplifyframework.api.aws.AuthModeStrategyType)1 AuthorizationType (com.amplifyframework.api.aws.AuthorizationType)1