AWS auth seesion not keeping alive when we close the android application - android

I'm using AWS Amplify SDK for Cognito integration. Actually, I successfully integrated user sign in and sign up flows based on the documentation available here. However, after the successful login if we restart the app the user session is not persisting. Amplify.Auth.fetchAuthSession() always returns isSignedIn as false. I have no idea where I'm making a problem. Please find the 'sign in' snippet below.
fun onSingIn(view: View) {
Amplify.Auth.signIn(
email.value,
password.value,
{ result ->
Log.i(TAG, if (result.isSignInComplete) "Sign in succeeded" else "Sign in not complete")
if (result.isSignInComplete) {
view.context.let {
it.startActivity(Intent(it, FeedActivity::class.java))
signInStatus.postValue(true)
}
}
},
{ error ->
view.context.let {
var message = it.getString(R.string.something_went_wrong)
when (error.cause) {
is UserNotConfirmedException ->{
email.value?.let {emailAddress ->
val direction =LoginFragmentDirections
.actionLoginFragmentToEmailVerificationCodeFragment(emailAddress)
view.findNavController().navigate(direction)
}
}
is UserNotFoundException ->
message = it.getString(R.string.credentilas_incorrect)
else->
viewModelScope.launch(Dispatchers.Main) { it.showToast(message) }
}
Log.e(TAG, error.toString())
}
}
)
}

Finally resolved the issue. The problem was related user pool app client settings configurations. I haven't checked identity providers inside app client settings. After choosing 'Cognito User Pool' as an identity provider the login session stayed alive without any issues. Hope this answer will help someone facing a similar issue.

Related

Can createUserWithEmailAndPassword called be multiple times?

I'm asking this because I want display a message to the user only once:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val isUserNew = authResult.additionalUserInfo!!.isNewUser!!
if(isUserNew) {
Toast.makeText(baseContext, "Hello", Toast.LENGTH_SHORT).show()
}
} else {
Log.d(TAG, task.exception!!.message!!)
}
}
So can isUserNew be false? Or it's always true since createUserWithEmailAndPassword is only called once? And I don't even need to check that.
AdditionalUserInfo is also used in other auth methods so, isUserNew is there for convenience.
If user deleted the app and signed in again, or logged in via Google on second device for example, isUserNew will be false. But in this particular case it will always be true.

Why isn't the variable being updated and returned correctly in this function?

So I've been following a video and Google's documentation trying to implement user sign in with Firebase on an android app. Which is working, so to try and tidy up (and help me reuse the code in another project) I have alot of the sign in code moved to a seperate .kt file and used the below funcion to create a new user.
//in LoginActivity.kt
fun createNewUser(email:String, password:String) :Boolean{
var success:Boolean = false
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
success = true
// Sign in success, update UI with the signed-in user's information
Log.d(null, "createUserWithEmail:success")
val user = auth.currentUser
//updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(null, "createUserWithEmail:failure", task.exception)
//Toast.makeText(baseContext, "Authentication failed.",Toast.LENGTH_SHORT).show()
//updateUI(null)
success = false
}
}
return success
}
The issue I am having is that the "success" boolean isn't being updated when the account is created, the Log saying "success" appears to run fine. I tried changing the inital state of success from false to true and that returned true as expected and my code looking at the result of this ran fine.
Here is where its being called from, as I said the toasts run fine but the value of success returned is always what it was initialised as.
//in MainActivity.kt
var login = LoginActivity()
if(login.createNewUser(email,password)) {
Toast.makeText(this,"I got this far",Toast.LENGTH_SHORT).show()
uploadImageToFirebase()
}
else{
Toast.makeText(this,"I didnt get this far",Toast.LENGTH_SHORT).show()
}
Thanks for any help :)
I'll start at the end, because this is a huge mistake:
var login = LoginActivity()
Never instantiate an Activity. Activity instantiation is handled by the operating system. If createNewUser relies on any functions of LoginActivity, then it will fail when called on your own instantiated instance. And if it doesn't rely on them, then don't define it inside LoginActivity.
Regarding your main question:
When you pass a callback to a function, that means it runs asynchronously. The callback will be called some time in the future, after this function has already returned. So createNewUser can't return the result of the callback.
Instead, you can create your own callback for your function like this. I'm treating auth.currentUser as type User, but you should put whatever class it actually is.
fun createNewUser(email:String, password:String, onComplete: (User?) -> Unit) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(null, "createUserWithEmail:success")
onComplete(auth.currentUser)
} else {
// If sign in fails, display a message to the user.
Log.w(null, "createUserWithEmail:failure", task.exception)
onComplete(null)
}
}
}
Then to use it, you can call the function and in your lambda callback you can react based on whether the user is null or not, which indicates failure or success:
createNewUser(email, password) { user ->
if (user != null) {
// success. Do something with the smart-casted non-null user variable
} else {
// failure. Show error message to the user, etc.
}
}

com.google.firebase.FirebaseException: An internal error has occured. [API key not valid. Please pass a valid API key.] Android, Firebase, Google Auth

I've been trying for 3 days but cant solve the problem. The application connects with Google, I can get the information of the user, but Firebase does not save. private fun
firebaseAuthWithGoogle(idtoken : String?) {
val credential = GoogleAuthProvider.getCredential(idtoken, null)
println(credential)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
user = auth.currentUser!!
Toast.makeText(this,"başarılı",Toast.LENGTH_LONG).show()
updateUI(user)
} else {
// If sign in fails, display a message to the user.
// ...
Toast.makeText(this,"olmadııııııııııı",Toast.LENGTH_LONG).show()
updateUI(null)
}
}
}
I can intent to other activity but when I go Toast shows "olmadııııııııııı". So I think the problem
signinwithcredential. I also enableb the google sign-in method in firebase and entered my SHA-1 fingerprint.
What should I do ?
I get this error on auth.signInWithCredential() ->if(task.isSuccessful)

How to sign in a user with AWS Amplify on Android + Kotlin?

I'm trying to make an Android app with a sign in screen on Android in Kotlin using AWS Amplify, here's my sign in code:
AWSMobileClient.getInstance().signIn(username, password, null, object : Callback<SignInResult> {
override fun onResult(signInResult: SignInResult) {
runOnUiThread {
Log.d("DEBUG", "Sign-in callback state: " + signInResult.signInState)
when (signInResult.signInState) {
SignInState.DONE -> Log.d("DEBUG", "Sign-in done.")
SignInState.SMS_MFA -> Log.d("DEBUG", "Please confirm sign-in with SMS.")
SignInState.NEW_PASSWORD_REQUIRED -> Log.d("DEBUG", "Please confirm sign-in with new password.")
else -> Log.d("DEBUG", "Unsupported sign-in confirmation: " + signInResult.signInState)
}
}
}
override fun onError(e: Exception) {
Log.e("DEBUG", "Sign-in error", e)
}
})
I used the documentation of Amazon here, copied and pasted the block found at the Sign In chapter into Android Studio that automatically converted the Java code into Kotlin.
Using logs I see that my code above this one is executed when I press the login button but the onResult block is never called. The logs only print a D/AWSMobileClient: Sending password. from AWS sdk.
I remember that this code worked before Christmas holidays so I think that it's maybe a change on the Amazon side but I find nothing in the documentation.
Do you have any idea of what's wrong here ?

Firebase authentication after user had been deleted

I have an android application which uses Firebase Authentication via Facebook. A user can delete their account in the application using the following function:
override fun deleteUserAcc() {
val user = FirebaseAuth.getInstance().currentUser
val userToken = FacebookAuthProvider.getCredential(authTokenProvider.provideToken())
user?.reauthenticate(userToken)?.addOnCompleteListener { task ->
user.delete()
}
}
After this a user really gets deleted on the Firebase servers. However when they try to access the application again and log in one more time, they are not able to do this (their account with uid had been deleted and somehow they are not assigned a new one uid).
The login function and the onSuccess callback are both implemented and called.
override fun login(): Completable {
LoginManager.getInstance().logInWithReadPermissions(
activityReference.get(),
listOf("public_profile", "user_birthday", "user_location")
)
return CompletableSubject.create().apply {
loginSubject = this
}
}
override fun onSuccess(result: LoginResult) {
val credential = FacebookAuthProvider.getCredential(result.accessToken.token)
authTokenProvider.saveToken(result.accessToken.token)
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
getInfoOnFirestore(loginSubject)
} else {
loginSubject.onError(task.exception!!)
}
}
}
What can possibly be the cause of the following issue?
A little late to the party but I know what the issue is. Firebase deletes only the authentication, which means that the real-time database is still there with the same uid. In order to delete the database entry as well, you need to upgrade to the blaze program and add the extension.

Categories

Resources