Skip to content
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

fix(amplify_auth_cognito) adding credentials code #22

Merged
merged 2 commits into from
Aug 11, 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
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,11 @@ import com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.Cognito
import com.amazonaws.services.cognitoidentityprovider.model.*
import com.amplifyframework.auth.AuthChannelEventName
import com.amplifyframework.auth.AuthException
import com.amplifyframework.auth.AuthSession
import com.amplifyframework.auth.cognito.AWSCognitoAuthPlugin
import com.amplifyframework.auth.cognito.AWSCognitoAuthSession
import com.amplifyframework.auth.result.AuthResetPasswordResult
import com.amplifyframework.auth.result.AuthSessionResult
import com.amplifyframework.auth.result.AuthSignInResult
import com.amplifyframework.auth.result.AuthSignUpResult
import com.amplifyframework.core.Amplify
Expand Down Expand Up @@ -82,7 +85,7 @@ public class AuthCognito : FlutterPlugin, ActivityAware, MethodCallHandler {
}

private fun checkData(@NonNull args: HashMap<String, Any>): HashMap<String, Any> {
if (args["data"] !is HashMap<*, *>) {
if (args["data"] !is HashMap<*, *> ) {
throw java.lang.Exception("Flutter method call arguments.data is not a map.")
}
return args["data"] as HashMap<String, Any>
Expand All @@ -108,13 +111,14 @@ public class AuthCognito : FlutterPlugin, ActivityAware, MethodCallHandler {
"confirmSignUp" -> onConfirmSignUp(result, data)
"signIn" -> onSignIn(result, data)
"confirmSignIn" -> onConfirmSignIn(result, data)
"signOut" -> onSignOut(result, data);
"changePassword" -> onChangePassword(result, data);
"resetPassword" -> onResetPassword(result, data);
"confirmPassword" -> onConfirmPassword(result, data);
else -> result.notImplemented()
}
"signOut" -> onSignOut(result, data)
"changePassword" -> onChangePassword(result, data)
"resetPassword" -> onResetPassword(result, data)
"confirmPassword" -> onConfirmPassword(result, data)
"fetchAuthSession" -> onFetchAuthSession(result, data)
else -> result.notImplemented()
}
}

override fun onAttachedToActivity(binding: ActivityPluginBinding) {
this.mainActivity = binding.activity
Expand Down Expand Up @@ -173,7 +177,7 @@ public class AuthCognito : FlutterPlugin, ActivityAware, MethodCallHandler {
channel.setMethodCallHandler(null)
}

fun onSignUp (@NonNull flutterResult: Result, @NonNull request: HashMap<String, *>) {
private fun onSignUp (@NonNull flutterResult: Result, @NonNull request: HashMap<String, *>) {
if (FlutterSignUpRequest.validate(request)) {

var req = FlutterSignUpRequest(request as HashMap<String, *>);
Expand Down Expand Up @@ -294,7 +298,7 @@ public class AuthCognito : FlutterPlugin, ActivityAware, MethodCallHandler {
}
}

private fun onConfirmPassword (@NonNull flutterResult: Result, @NonNull request: HashMap<String, *>?) {
private fun onConfirmPassword (@NonNull flutterResult: Result, @NonNull request: HashMap<String, *>) {
if (FlutterConfirmPasswordRequest.validate(request)) {
var req = FlutterConfirmPasswordRequest(request as HashMap<String, *>)
try {
Expand All @@ -312,33 +316,65 @@ public class AuthCognito : FlutterPlugin, ActivityAware, MethodCallHandler {
}
}

private fun onFetchAuthSession (@NonNull flutterResult: Result, @NonNull request: HashMap<String, *>) {
// TODO: Implement forceRefresh when/if supported by Amplify libs
var req = FlutterFetchAuthSessionRequest(request as HashMap<String, *>)
try {
Amplify.Auth.fetchAuthSession(
{ result ->
if (req.getAWSCredentials) {
val cognitoAuthSession = result as AWSCognitoAuthSession
when (cognitoAuthSession.identityId.type) {
AuthSessionResult.Type.SUCCESS -> this.mainActivity?.runOnUiThread({ prepareCognitoSessionResult(flutterResult, cognitoAuthSession)})
AuthSessionResult.Type.FAILURE -> this.mainActivity?.runOnUiThread({ prepareCognitoSessionFailure(flutterResult, cognitoAuthSession)})
}
} else {
val session = result as AuthSession;
this.mainActivity?.runOnUiThread({ prepareSessionResult(flutterResult, session)})
}
},
{ error -> prepareError(flutterResult, error, FlutterAuthFailureMessage.FETCH_SESSION.toString()) }
)
} catch(e: Exception) {
prepareError(flutterResult, e, FlutterAuthFailureMessage.FETCH_SESSION.toString())
}

}

private fun prepareError(@NonNull flutterResult: Result, @NonNull error: Exception, @NonNull msg: String) {
var errorMap: HashMap<String, Any> = HashMap();
if (error is AuthException) {
when (error.cause) {
is InvalidParameterException -> errorMap.put("INVALID_PARAMETER", (error.cause as InvalidParameterException).errorMessage)
is UsernameExistsException -> errorMap.put("USERNAME_EXISTS", (error.cause as UsernameExistsException).errorMessage)
is AliasExistsException -> errorMap.put("ALIAS_EXISTS", (error.cause as AliasExistsException).errorMessage)
is CodeDeliveryFailureException -> errorMap.put("CODE_DELIVERY_FAILURE", (error.cause as CodeDeliveryFailureException).errorMessage)
is CodeMismatchException -> errorMap.put("CODE_MISMATCH", (error.cause as CodeMismatchException).errorMessage)
is CognitoCodeExpiredException -> errorMap.put("CODE_EXPIRED", (error.cause as CognitoCodeExpiredException).localizedMessage)
is InternalErrorException -> errorMap.put("INTERNAL_ERROR", (error.cause as InternalErrorException).errorMessage)
is InvalidLambdaResponseException -> errorMap.put("INVALID_LAMBDA_RESPONSE", (error.cause as InvalidLambdaResponseException).errorMessage)
is InvalidPasswordException -> errorMap.put("INVALID_PASSWORD", (error.cause as InvalidPasswordException).errorMessage)
is MFAMethodNotFoundException -> errorMap.put("MFA_METHOD_NOT_FOUND", (error.cause as MFAMethodNotFoundException).errorMessage)
is NotAuthorizedException -> errorMap.put("NOT_AUTHORIZED", (error.cause as NotAuthorizedException).errorMessage)
is ResourceNotFoundException -> errorMap.put("RESOURCE_NOT_FOUND", (error.cause as ResourceNotFoundException).errorMessage)
is SoftwareTokenMFANotFoundException -> errorMap.put("SOFTWARE_TOKEN_MFA_NOT_FOUND", (error.cause as SoftwareTokenMFANotFoundException).errorMessage)
is PasswordResetRequiredException -> errorMap.put("PASSWORD_RESET_REQUIRED", (error.cause as PasswordResetRequiredException).errorMessage)
is TooManyRequestsException -> errorMap.put("TOO_MANY_REQUESTS", (error.cause as TooManyRequestsException).errorMessage)
is UnexpectedLambdaException -> errorMap.put("UNEXPECTED_LAMBDA", (error.cause as UnexpectedLambdaException).errorMessage)
is UserLambdaValidationException -> errorMap.put("USER_LAMBDA_VALIDATION", (error.cause as UserLambdaValidationException).errorMessage)
is TooManyFailedAttemptsException -> errorMap.put("TOO_MANY_FAILED_REQUESTS", (error.cause as TooManyFailedAttemptsException).errorMessage)
is UserNotConfirmedException -> errorMap.put("USER_NOT_CONFIRMED", (error.cause as UserNotConfirmedException).errorMessage)
is LimitExceededException -> errorMap.put("REQUEST_LIMIT_EXCEEDED", (error.cause as LimitExceededException).errorMessage)
is AmazonClientException -> errorMap.put("AMAZON_CLIENT_EXCEPTION", (error.cause as AmazonClientException).localizedMessage)
is AmazonServiceException -> errorMap.put("AMAZON_SERVICE_EXCEPTION", (error.cause as AmazonServiceException).localizedMessage)
else -> errorMap.put("UNKNOWN", "Unknown Auth Error.")
when (error) {
is AuthException.SignedOutException -> errorMap["SIGNED_OUT"] = error.localizedMessage
is AuthException.SessionExpiredException -> errorMap["SESSION_EXPIRED"] = error.localizedMessage
is AuthException.InvalidAccountTypeException -> errorMap["INVALID_ACCOUNT_TYPE"] = error.localizedMessage
is AuthException.SessionUnavailableOfflineException -> errorMap["SESSION_UNAVAILABLE_OFFLINE"] = error.localizedMessage
is AuthException.SessionUnavailableServiceException -> errorMap["SESSION_UNAVAILABLE_SERVICE"] = error.localizedMessage
else -> when (error.cause) {
is InvalidParameterException -> errorMap["INVALID_PARAMETER"] = (error.cause as InvalidParameterException).errorMessage;
is UsernameExistsException -> errorMap["USERNAME_EXISTS"] = (error.cause as UsernameExistsException).errorMessage;
is AliasExistsException -> errorMap["ALIAS_EXISTS"] = (error.cause as AliasExistsException).errorMessage;
is CodeDeliveryFailureException -> errorMap["CODE_DELIVERY_FAILURE"] = (error.cause as CodeDeliveryFailureException).errorMessage;
is CodeMismatchException -> errorMap["CODE_MISMATCH"] = (error.cause as CodeMismatchException).errorMessage;
is CognitoCodeExpiredException -> errorMap["CODE_EXPIRED"] = (error.cause as CognitoCodeExpiredException).localizedMessage;
is InternalErrorException -> errorMap["INTERNAL_ERROR"] = (error.cause as InternalErrorException).errorMessage;
is InvalidLambdaResponseException -> errorMap["INVALID_LAMBDA_RESPONSE"] = (error.cause as InvalidLambdaResponseException).errorMessage;
is InvalidPasswordException -> errorMap["INVALID_PASSWORD"] = (error.cause as InvalidPasswordException).errorMessage;
is MFAMethodNotFoundException -> errorMap["MFA_METHOD_NOT_FOUND"] = (error.cause as MFAMethodNotFoundException).errorMessage;
is NotAuthorizedException -> errorMap["NOT_AUTHORIZED"] = (error.cause as NotAuthorizedException).errorMessage;
is ResourceNotFoundException -> errorMap["RESOURCE_NOT_FOUND"] = (error.cause as ResourceNotFoundException).errorMessage;
is SoftwareTokenMFANotFoundException -> errorMap["SOFTWARE_TOKEN_MFA_NOT_FOUND"] = (error.cause as SoftwareTokenMFANotFoundException).errorMessage;
is PasswordResetRequiredException -> errorMap["PASSWORD_RESET_REQUIRED"] = (error.cause as PasswordResetRequiredException).errorMessage;
is TooManyRequestsException -> errorMap["TOO_MANY_REQUESTS"] = (error.cause as TooManyRequestsException).errorMessage;
is UnexpectedLambdaException -> errorMap["UNEXPECTED_LAMBDA"] = (error.cause as UnexpectedLambdaException).errorMessage;
is UserLambdaValidationException -> errorMap["USER_LAMBDA_VALIDATION"] = (error.cause as UserLambdaValidationException).errorMessage;
is TooManyFailedAttemptsException -> errorMap["TOO_MANY_FAILED_REQUESTS"] = (error.cause as TooManyFailedAttemptsException).errorMessage;
is UserNotConfirmedException -> errorMap["USER_NOT_CONFIRMED"] = (error.cause as UserNotConfirmedException).errorMessage;
is LimitExceededException -> errorMap["REQUEST_LIMIT_EXCEEDED"] = (error.cause as LimitExceededException).errorMessage;
is AmazonClientException -> errorMap["AMAZON_CLIENT_EXCEPTION"] = (error.cause as AmazonClientException).localizedMessage;
is AmazonServiceException -> errorMap["AMAZON_SERVICE_EXCEPTION"] = (error.cause as AmazonServiceException).localizedMessage;
else -> errorMap["UNKNOWN"] = "Unknown Auth Error.";
}
}
} else {
when(error.message) {
Expand Down Expand Up @@ -388,6 +424,21 @@ public class AuthCognito : FlutterPlugin, ActivityAware, MethodCallHandler {
flutterResult.success(resetData.serializeToMap());
}

private fun prepareCognitoSessionResult(@NonNull flutterResult: Result, @NonNull result: AWSCognitoAuthSession) {
var session = FlutterFetchCognitoAuthSessionResult(result);
flutterResult.success(session.serializeToMap());
}

private fun prepareCognitoSessionFailure(@NonNull flutterResult: Result, @NonNull result: AWSCognitoAuthSession) {
prepareError(flutterResult, result.awsCredentials.error as AuthException, FlutterAuthFailureMessage.FETCH_SESSION.toString())
}

private fun prepareSessionResult(@NonNull flutterResult: Result, @NonNull result: AuthSession) {
var session = FlutterFetchAuthSessionResult(result);
flutterResult.success(session.serializeToMap());
}


//convert a data class to a map
fun <T> T.serializeToMap(): Map<String, Any> {
return convert()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,10 @@ enum class FlutterAuthFailureMessage {
override fun toString(): String {
return "AMPLIFY_CONFIRM_PASSWORD_FAILED"
}
},
FETCH_SESSION {
override fun toString(): String {
return "AMPLIFY_FETCH_SESSION_FAILED"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.amplify.amplify_auth_cognito.types

import com.amplifyframework.auth.options.AuthSignOutOptions


data class FlutterFetchAuthSessionRequest(val map: HashMap<String, *>) {
// TODO: Implement options when/if supported by Amplify libraries
// var sessionOptions: AuthFetchSessionOptions = setOptions()
val options: HashMap<String, *>? = map["options"] as HashMap<String, *>?;
val getAWSCredentials: Boolean = options != null && options["getAWSCredentials"] as Boolean? == true;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.amplify.amplify_auth_cognito.types

import androidx.annotation.Nullable
import com.amazonaws.auth.AWSCredentials
import com.amplifyframework.auth.AuthSession
import com.amplifyframework.auth.cognito.AWSCognitoAuthSession
import com.amplifyframework.auth.cognito.AWSCognitoUserPoolTokens
import com.amplifyframework.auth.result.AuthSessionResult
import com.amplifyframework.auth.result.AuthSignInResult
import com.google.gson.Gson

data class FlutterFetchAuthSessionResult(@Nullable public var raw: AuthSession) {
val isSignedIn: Boolean = raw.isSignedIn;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.amplify.amplify_auth_cognito.types

import com.amazonaws.auth.AWSCredentials
import com.amplifyframework.auth.AuthSession
import com.amplifyframework.auth.cognito.AWSCognitoAuthSession
import com.amplifyframework.auth.cognito.AWSCognitoUserPoolTokens
import com.amplifyframework.auth.result.AuthSessionResult
import com.amplifyframework.auth.result.AuthSignInResult
import com.google.gson.Gson

data class FlutterFetchCognitoAuthSessionResult(private val raw: AWSCognitoAuthSession) {
val isSignedIn: Boolean = raw.isSignedIn;
val identityId: String = raw.identityId.value as String;
val userSub: String = raw.userSub.value as String;
val credentials: AuthSessionResult<AWSCredentials> = raw.awsCredentials
val tokens: AuthSessionResult<AWSCognitoUserPoolTokens> = raw.userPoolTokens
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,15 @@ package com.amazonaws.amplify.amplify_auth_cognito.types
import androidx.annotation.NonNull
import com.amplifyframework.auth.AuthUserAttribute
import com.amplifyframework.auth.AuthUserAttributeKey
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthSignUpOptions
import com.amplifyframework.auth.options.AuthSignUpOptions
import java.lang.reflect.Method

data class FlutterSignUpRequest(val map: HashMap<String, *>) {
var standardAttributes: Array<String> = arrayOf("address", "birthdate", "email", "family_name", "gender", "given_name", "locale", "middle_name", "name", "nickname", "phone_number", "preferred_username", "picture", "profile", "updated_at", "website", "zoneinfo")
val username: String = setUserName(map);
val password: String = map["password"] as String;
val options: AuthSignUpOptions = formatOptions(map["options"] as HashMap<String, String>);
val options: AWSCognitoAuthSignUpOptions = formatOptions(map["options"] as HashMap<String, String>);

private fun setUserName(@NonNull request: HashMap<String, *>): String {
var username: String = "";
Expand All @@ -50,11 +51,11 @@ data class FlutterSignUpRequest(val map: HashMap<String, *>) {
return username;
};

private fun formatOptions(@NonNull rawOptions: HashMap<String, String>): AuthSignUpOptions {
var options: AuthSignUpOptions.Builder<*> = AuthSignUpOptions.builder();
private fun formatOptions(@NonNull rawOptions: HashMap<String, String>): AWSCognitoAuthSignUpOptions {
var options = AWSCognitoAuthSignUpOptions.builder();
var authUserAttributes: MutableList<AuthUserAttribute> = mutableListOf();
var attributeMethods = AuthUserAttributeKey::class.java.declaredMethods;
var validationData = rawOptions["validationData"];
var validationData = rawOptions["validationData"] as? MutableMap<String, String>;

(rawOptions["userAttributes"] as HashMap<String, String>).forEach { (key, value) ->
var keyCopy: String = key;
Expand All @@ -70,7 +71,10 @@ data class FlutterSignUpRequest(val map: HashMap<String, *>) {
}
}
options.userAttributes(authUserAttributes);
//TODO: Add validationData

if (validationData is MutableMap<String, String>) {
options.validationData(validationData)
}
return options.build();
}

Expand Down Expand Up @@ -106,4 +110,3 @@ data class FlutterSignUpRequest(val map: HashMap<String, *>) {
}

}

Loading