In my app I made an authentification systeme using firebase. I didn't use the default page of firebase but made a custom one with email and password after a click on a button :
mauth.createUserWithEmailAndPassword(lEmail, lPassowrd)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
userManager.createUser(); //CREER USER DANS DATABASE FIRESTORE (PAREIL POUR EMAIL)
Toast.makeText(SignupActivity.this, "Account created !", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SignupActivity.this, LoginActivity.class));
} else{
Toast.makeText(SignupActivity.this, "Registration error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}});
I added a line to create the user in FireStore, and later in the code I'm using FireStore data to update his username and picture. This leads to a crash as the username is null.
When I check on the Firestore database, a user is created with an id, but the profile picture and username are null. Any idea why? When I just use the information from the FireBase auth the user has an id and a username (no picture but that's ok).
This is the function creating the user on FireStore, previously called :
public void createUser() {
FirebaseUser user = getCurrentUser();
if(user != null){
String urlPicture = (user.getPhotoUrl() != null) ? user.getPhotoUrl().toString() : null;
String username = user.getDisplayName();
//QUAND ON CREER UN DOCUMENT SUR FIRESTORE IL A AUTO UN ID UNIQUE
//MAIS DANS NOTRE CAS L'USER A UN ID LORSQUON L'A CREER AVEC L'AUTHENTIFICATION
String uid = user.getUid();
User userToCreate = new User(uid, username, urlPicture);
Task<DocumentSnapshot> userData = getUserData();
// If the user already exist in Firestore, we get his data (isMentor)
userData.addOnSuccessListener(documentSnapshot -> {
//if (documentSnapshot.contains(IS_MENTOR_FIELD)){
//userToCreate.setIsMentor((Boolean) documentSnapshot.get(IS_MENTOR_FIELD));
//}
this.getUsersCollection().document(uid).set(userToCreate);
});
}
}
A solution would be very appreciated as I'm stuck on this for a while now
EDIT :
I tried modifying the displayName like that :
mauth.createUserWithEmailAndPassword(lEmail, lPassowrd)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
FirebaseUser user = mauth.getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder().setDisplayName(lUsername).build();
//user.updateProfile(profileUpdates);
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("filds", "User profile updated.");
}
}
});
userManager.createUser(); //CREER USER DANS DATABASE FIRESTORE (PAREIL POUR EMAIL)
Toast.makeText(SignupActivity.this, "Account created !", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SignupActivity.this, LoginActivity.class));
} else{
Toast.makeText(SignupActivity.this, "Registration error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}});
The logcat shows "User profile updated." but the username is still null in FireStore :/
When I check on the Firestore database, a user is created with an id, but the profile picture and username are null. Any idea why?
When you authenticate your users using email and password, it means that a new instance of type FirebaseUser is created. Since you are only getting the email address and the password from the user, the only field of the class that is populated is the "email". Since there is no user name involved, nor a profile picture, when you are using getDisplayName() or getPhotoUrl() the result that you get is null, hence that result. If you want to populate those fields too, then you should consider either getting that information from the user, or use of one of the available providers. It can be Google, Facebook, or any other provider. In this way, you'll have both the user name and the profile picture URL populated.
Related
I'm working with Firebase authentication and database.In my project user sign in and sign up with their email and password.I use a model class where i have three variable email,password and name.I can store email in authentication sector and users details in database.
code is given below:
User user = new User(name,mail,password);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
startActivity(new Intent(SignUp.this,Home.class));
finish();
}else {
Toast.makeText(SignUp.this, "Getting error", Toast.LENGTH_SHORT).show();
}
}
Is there any way that i used user name instead of getUid value?like this
To solve this, instead of passing the uid (FirebaseAuth.getInstance().getCurrentUser().getUid()) of the user to the child() method, pass the userName:
FirebaseDatabase.getInstance().getReference("Users").child(name).setValue(user).addOnCompleteListener(/* ... */);
// ^ ^
See I have passed the name instead of the uid.
You can set like below: replace FirebaseAuth.getInstance().getCurrentUser().getUid() with name. It will create node with userName.
user = new User(name,mail,password);
FirebaseDatabase.getInstance().getReference("Users")
.child(name) // replace the getUid() code with name
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
startActivity(new Intent(SignUp.this,Home.class));
finish();
}else {
Toast.makeText(SignUp.this, "Getting error", Toast.LENGTH_SHORT).show();
}
}
Hope it will help you:)
I have been trying to login via different accounts in android, i am not able to have different redirects for different users. Mainly i cant fetch users' email from authentication as a condition so that i can have different redirects. trying different steps from a while now. Can someone help?
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful() == true) {
if(email.equals("dummy#gmail.com"))
{
progressDialog.dismiss();
finish();
startActivity(new Intent(Login.this,RegisterActivity.class));
}
else {
progressDialog.dismiss();
finish();
startActivity(new Intent(Login.this, MainActivity.class));
}
} else if (task.isSuccessful() == false) {
progressDialog.dismiss();
Toast.makeText(Login.this, "Invalid emailid or password.", Toast.LENGTH_SHORT).show();
passwordUser.getText().clear();
emailUser.getText().clear();
emailUser.requestFocus();
return;
}
}
});
Only firebase can't help you to determine role of user. You need to integrate firebase auth with your database to determine role of user.
For Accessing email of logged in user please follow this code
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// Check if user's email is verified
boolean emailVerified = user.isEmailVerified();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getIdToken() instead.
String uid = user.getUid();
}
Im Creating Registration with email and Password but with Fullname of the user and display it when the users Login i try to find tutorials in youtube but no one provide or i dont just find it, only email and password tutorials ,
Anyone here could help me?
This is for Android
Im using Android Studio
my backend is Firebase
I want the user in the registration
when click to the confirm button the Full name is will be registered to the firebase and display it in users profile..
thanks a lot.
By the way
the code that I am using now is this
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
finish();
}
}
});
As you said you found tutorials with email and password.
Follow those tutorials, the only thing extra you have to do is, make full name edit text in XML and during sign up check if it is not null and make users DB in the realtime database using UID.
if (!emailAdd.equals("") || !pass.equals("") || (!name.eqauls(""){
mAuth.createUserWithEmailAndPassword(emailAdd, pass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Getting UID of Current User
FirebaseUser current_user = mAuth.getCurrentUser();
String UID = current_user.getUid();
usersDB.child(UID).child("email").setValue(emailAdd);
usersDB.child(UID).child("name").setValue(name);
Toast.makeText(youractivity.this, "Registeration done", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(youractivity.this, "Registeration Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
I am developing an Android Application with Firebase User Authentication. The problem I am facing is that I get email and password from user and then create that user into firebase. I am not verifying email which user has entered. Now I want to implement reset password feature. For that Firebase provides resetPassword method and send reset password email to that particular user. But the question is that if email is not exist then what should we do?
Here is the code I am using to register user in Firebase:
private void registerUser(){
//creating a new user
firebaseAuth.createUserWithEmailAndPassword("user email here", "user password here")
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if(task.isSuccessful()){
//display some message here
}else{
//display some message here
}
}
});
}
Please let me know if there is any alternate option available for this feature.
Thanks.
An alternative would be to use the Firebase Admin SDK to change the user's password. From the documentation on updating user information:
The updateUser() method allows you to modify an existing user's data. It accepts a uid for the user to update as well as an object containing the UserRecord properties to update:
admin.auth().updateUser(uid, {
email: "modifiedUser#example.com",
emailVerified: true,
password: "newPassword",
displayName: "Jane Doe",
photoURL: "http://www.example.com/12345678/photo.png",
disabled: true
})
.then(function(userRecord) {
// See the UserRecord reference doc for the contents of userRecord.
console.log("Successfully updated user", userRecord.toJSON());
})
.catch(function(error) {
console.log("Error updating user:", error);
});
With:
password- string - The user's new raw, unhashed password. Must be at least six characters long.
This part of the Firebase Admin SDK is currently only available in Node.js. But if you don't have a Node.js server yet, you could implement the functionality in Cloud Functions for Firebase.
Please try with below code may be help you , I am using this.
private FirebaseUser user;
user = FirebaseAuth.getInstance().getCurrentUser();
final String email = user.getEmail();
AuthCredential credential = EmailAuthProvider.getCredential(email,oldpass);
user.reauthenticate(credential).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
user.updatePassword(newPass).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(!task.isSuccessful()){
Snackbar snackbar_fail = Snackbar
.make(coordinatorLayout, "Something went wrong. Please try again later", Snackbar.LENGTH_LONG);
snackbar_fail.show();
}else {
Snackbar snackbar_su = Snackbar
.make(coordinatorLayout, "Password Successfully Modified", Snackbar.LENGTH_LONG);
snackbar_su.show();
}
}
});
}else {
Snackbar snackbar_su = Snackbar
.make(coordinatorLayout, "Authentication Failed", Snackbar.LENGTH_LONG);
snackbar_su.show();
}
}
});
}
}
I want to check when a user attempts to signup with createUserWithEmailAndPassword() in Firebase user Authentication method, this user is already registered with my app.
To detect whether a user with that email address already exists, you can detect when the call to createUserWithEmailAndPassword () fails with auth/email-already-in-use. I see that #Srinivasan just posted an answer for this.
Alternatively, you can detect that an email address is already used by calling fetchSignInMethodsForEmail().
The usual flow for this is that you first ask the user to enter their email address, then call fetchSignInMethodsForEmail, and then move them to a screen that either asks for the rest of their registration details (if they're new), or show them the provider(s) with which they're signed up already.
When the user trying to create an user with same email address, the task response will be "Response: The email address is already in use by another account."
mFirebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//User registered successfully
}else{
Log.i("Response","Failed to create user:"+task.getException().getMessage());
}
}
});
First of all, you need to make sure you have that restriction enabled in Firebase console (Account and email address settings). Take a look at #Srinivasan's answer.
Then, do this in your java code:
firebaseAuthenticator.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(SignUpActivity.this, "User with this email already exist.", Toast.LENGTH_SHORT).show();
}
} else {
sendVerificationEmail();
startActivity(new Intent(SignUpActivity.this, DetailsCaptureActivity.class));
}
// ...
}
});
This is where the trick happens:
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(SignUpActivity.this,
"User with this email already exist.", Toast.LENGTH_SHORT).show();
Several exceptions can be thrown when registering a user with email and password, but the one we are interested in is the FirebaseAuthUserCollisionException. As the name implies, this exception is thrown if the email already exists. If the exception thrown is an instance of this class, let the user know.
As a practice of #Frank's answer here is the code of using fetchProvidersForEmail()
private boolean checkAccountEmailExistInFirebase(String email) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
final boolean[] b = new boolean[1];
mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
#Override
public void onComplete(#NonNull Task<ProviderQueryResult> task) {
b[0] = !task.getResult().getProviders().isEmpty();
}
});
return b[0];
}
I was looking into this kind of condition where we can detect if user exists or not and perform registration and login. fetchProvidersForEmail is best option right now. I have found this tutorial. Hope it helps you too!
See : Manage Users
UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmail(email);
System.out.println("Successfully fetched user data: " + userRecord.getEmail());
This method returns a UserRecord object for the user corresponding to the email provided.
If the provided email does not belong to an existing user or the user cannot be fetched for any other reason, the Admin SDK throws an error. For a full list of error codes, including descriptions and resolution steps, see Admin Authentication API Errors.
private ProgressDialog progressDialog;
progressDialog.setMessage("Registering, please Wait...");
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if (task.isSuccessful()) {
//Registration was successfull:
Toast.makeText(RegistrationActivity.this, "Successfully registered!", Toast.LENGTH_LONG).show();
} else {
//Registration failed:
//task.getException().getMessage() makes the magic
Toast.makeText(RegistrationActivity.this, "Registration failed! " + "\n" + task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
Add below code to MainActivity.java file.When user attempt to register with the same email address a message "The email address is already used by another account" will pop up as a Toast
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Sign up successfull", Toast.LENGTH_SHORT).show();
}
}
});
You do not have to do anything because the backend of Firebase will do the job.
Unless you are referring to reauthenticating of the app.
Take a scenario for an example, w