Get user's displayname in firebase function once account is created - java

I have an Android app where the user registers for an account with their email, password, and displayName. I want to send a welcome email to the user after they create an account. This is how I create my account and set their display name.
// This happens in Android (RegisterActivity.java) where I create user's account
FirebaseAuth auth = FirebaseAuth.getInstance();
auth.createUserWithEmailAndPassword(email, password)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
FirebaseUser user = authResult.getUser();
user.updateProfile(new UserProfileChangeRequest.Builder()
.setDisplayName(name).build());
}
});
Once the user's account is created, a firebase function is triggered. Below is my code:
// This happens in Firebase Cloud Functions (index.js)
exports.sendWelcomeEmail = functions.auth.user().onCreate((user) => {
// send welcome email here
console.log(user.displayName) // displayName is null here
});
I believe that the firebase function gets triggered as soon as the account creation is successful, and I set user's displayname after the account is created and so displayName is null in the function. What can I do to solve the issue? I don't want to send an email to the user without their name in the email.

tl;dr: displayName is being called before is being set.
The onCreate function runs after the front end finishes createUserWithEmailAndPassword but before the displayName is set.
Either you run an onCall function after you update the displayName or as suggested on the firebase github thread on this issue you can add a profile parameter to the createUserWithEmailAndPassword so that we create new accounts with a pre-populated profile.

Related

validate existing user's mobile number in firebase

I have a firebase project which allows users to login only if they are already exists in identifier in authentication .
I already added few users using my web app with mobile numbers.
Now, in android I have used the signInWithPhoneAuthCredential method to get the users login.
But in this method, it allows any users to login even if the user is first time entering the mobile number.
Is there any method to restrict this ?
Sample Code :
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
// ...
} else {
// Sign in failed, display a message and update the UI
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
}
}
}
});
}
According to the docs:
signInWithPhoneNumber:
Asynchronously signs in using a phone number. This method sends a code via SMS to the given phone number, and returns a firebase.auth.ConfirmationResult. After the user provides the code sent to their phone, call firebase.auth.ConfirmationResult.confirm with the code to sign the user in.
This is the default behavior in all applications that uses phone number as login. There is no method in the firebase docs that can restrict this.
you have to use firebase database also with this code to save user info, that way you can achieve your use case

How to get a user by Id and delete it after from firebase auth database

I want to add a feature in my app that allows the admin account to delete firebase user accounts from inside the app. I have the user Id that I want to delete stored in a String but can't get the user record from the firebase auth database using the Id.
The getUser() method stays in red and android studio shows a note :
Cannot resolve method getUser(java.lang.String).
I already tried searching on the net for previous similar problems but they were all trying to delete the connected user and not a specific user of a given ID
// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
final String UserId = myIntent.getStringExtra("uid"); // will return "User Id"
final Button btnDelete = findViewById(R.id.deleteaccount);
final FirebaseUser userToDelete = FirebaseAuth.getInstance().getUser(UserId);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userToDelete.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(TAG, "Account deleted", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(TAG, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
})
}
});
I want to achieve one goal: Being able to delete a user with a given Id.
The Firebase web and mobile client libraries don't support the ability to get and delete user accounts, as that would pose a security risk. The only way to programmatically manage user accounts is using the Firebase Admin SDK to on a backend you control.

How Firebase defines current user in Auth?

I'm using Firebase Auth with Google and doing everyrhing through Firebase docs, and in my SigninActivity, I have onStart method, which check is there are current user or no.
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart");
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
and also have
FirebaseAuth.getInstance().signOut();
which signs out user.
And i cannot understand, how Firebase defines current user, when he not logged in yet.
Is there are unique ID for app or how ?
According to your comments:
Yes, And also i dont understand, how Firebase knows current user, when he not signed in yet ? I mean, which criteria Firebase checks in this method FirebaseUser currentUser = mAuth.getCurrentUser()
Firebase "knows" when the current user is logged in or not by checking the FirebaseUser object for nullity. If the user is logged in, when using the following line of code:
FirebaseUser currentUser = mAuth.getCurrentUser();
It returns a non nullable FirebaseUser object. This is the reason why we always check it for nullity. If you are using the following line of code:
FirebaseAuth.getInstance().signOut();
It means that the FirebaseUser becomes null, which also means that the user has signed out.

How to create unique token, in every users firebase android?

I want to generate and store token everytime users login. I tried for my code below, but it always generate same token when I login with another account.
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
AlertDialog.dismiss();
if (!task.isSuccessful()) {
if (password.length() < 6) {
new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("Enter minimum 6 charachters !! ")
.show();
} else {
passwordInput.setText("");
new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("Authentication failed !!")
.show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
FirebaseUser users = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users/"+ users.getUid());
String token = FirebaseInstanceId.getInstance().getToken();
Log.e("tokenid",""+token);
mDatabase.child("token_id").setValue(token);
finish();
}
}
});
}
});
please help, thanks..
When using the following line of code:
String token = FirebaseInstanceId.getInstance().getToken();
You are getting the Firebase Instance ID token, which is also known as FCM token, on the client side. You need to know that in Firebase there two different tokens:
A FCM Token/Instance ID token that identifies an installation of a specific application on a specific user device. It doesn't identify in any way a particular user.
An Auth ID token identifies a specific user of a specific application. It doesn't identify in any way a particular device.
The two tokens are quite different and serve different purposes. Please see the official documentation for Android regarding on how to retrieve ID tokens on clients.
The identity of the user is remembered indefinitely (or until you sign out). But their credentials (or rather, whether their token is still valid) are re-checked every hour.
FCM generates a registration token for the client app instance, hence It may happen that you'll get the same token for different users in your app. You can use forceRefresh to generate a new token every time. Register new token everytime user logins to any device and save it in DB and update with a new token on new login this way you will have a new token for each user on every login (If this fits your requirement)
Here is a good answer to understand how it works Firebase FCM force onTokenRefresh() to be called
Use UUID.randomUUID().toString()
You can read more here.
java docs - and here =)

Checking for last user that logged in

I am trying to finish up the implementation of a login screen for my app. I have a REST API backend that verifies the username + token and returns the userId of the person logging into the app.
I want to store the last userId from the user who has logged into the app. I plan to use Shared preferences for this.
Based on the last stored userId, i plan to execute either going to the main activity (if this user has logged in previously, but logged out after a while and is re-logging in), or executing an AsynkTask to syncronise some data from the backend (if it is a new user). Here is my logic, which seems to not be working properly.
It is switching directly to the MainSyncTask, even if i'm logging in with the last username (userId is the same, received from the API), and savedUserId.equals(currentUserId) should return true and execute the Intent. last userId is properly store in the sharedpreferences db, check with Stecho .
String userId = getUserIdFromAPIResponse();
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
private void checkIdAndGoToActivity() {
final String PREF_VERSION_CODE_KEY = "user_id";
// Get current version code
String currentUserId = userId;
// Get saved version code
String savedUserId = sharedpreferences.getString(PREF_VERSION_CODE_KEY, "");
if (savedUserId.equals(currentUserId)) {
Log.e(TAG, "Current User Logged in");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
/* destroys activity , prevents user from going back to previous MainActivity after login out */
finish();
} else if (!savedUserId.equals(currentUserId)) {
Log.e(TAG, "New user logged in");
MainSyncTask mainSyncTask = new MainSyncTask(LoginActivity.this, LoginActivity.this, userEmail, userPassword);
mainSyncTask.execute();
SyncEventReceiver.setupAlarm(getApplicationContext());
}
// Update the shared preferences with the current version code
sharedpreferences.edit().putString(PREF_VERSION_CODE_KEY, currentUserId).apply();
}

Categories

Resources