I have Created a Android User Login And Registration App . I want That When a user registration is successful a Name Points And Value 0 will be added To the Database .
enter image description here
Here is my Registration Code :
//logging in the user
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
//if the task is successfull
if(task.isSuccessful()){
//start the profile activity
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}else{
//display some message here
Toast.makeText(LoginActivity.this,"Error Email Or Password",Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
So in order to achieve this, use setValue() method directly in the reference like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child(userId).child("Points").setValue(0);
In which userId is the id of the specific user that is authenticated.
Related
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.
I have a few sign-up methods in my app as shown below:
Let's revolve the problem around Google sign-in method:
What I am doing is that when a user signs in enteringDataIntoUserNode() method is called inside signInWithCredential() method like:
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential =
GoogleAuthProvider.getCredential(acct.getIdToken(), null);
// signing in
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// entering default values in the database
enteringDataIntoUserNode();
Intent intent = new Intent(LoginAndSignupActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
}
}
});
}
enteringDataIntoUserNode()
private void enteringDataIntoUserNode() {
final String currentUid = mAuth.getCurrentUser().getUid();
//
String deviceToken = FirebaseInstanceId.getInstance().getToken();
final String userName = mAuth.getCurrentUser().getDisplayName();
String imageUrl = mAuth.getCurrentUser().getPhotoUrl().toString();
String userStatus = "Hi there! How is it going?";
// inserting data in key-value pair
usersReference.child(currentUid).child("user_name").setValue(userName);
usersReference.child(currentUid).child("user_status").setValue(userStatus);
usersReference.child(currentUid).child("user_image").setValue(imageUrl);
usersReference.child(currentUid).child("device_token").setValue(deviceToken);
// when this last value will be inserted then, making an intent to MainActivity
usersReference.child(currentUid).child("user_thumb_image").setValue(imageUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: Data insertion for the new user is successful ");
}
}
});
}
enteringDataIntoUserNode() method is simply passing some default data to the database every time a user signs in. But if a user change its details like image or username etc. and sign out and again sign in through Google sign in method then again enteringDataIntoUserNode() method will be called and user details would be overwritten with the default ones.
My question is that is there any way to check whether a user is signing in for the first time or not during the Google sign in so that in the latter case I can skip calling enteringDataIntoUserNode() method and prevent overwriting of data.
Same thing I want to acheive during Facebook and Phone Number sign in.
If you check if the user logs in for the first time, it's the same thing if you want to check if a user is new. So to solve this, we can simply call the isNewUser() method in the OnCompleteListener.onComplete callback like this:
OnCompleteListener<AuthResult> completeListener = new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
Log.d("TAG", "The user is new!");
} else {
Log.d("TAG", "The user is not new!");
}
}
}
};
For more informations, please see the official documentation.
You could check when the account was created with:
task.getResult().getUser().getMetadata().getCreationTimestamp()
See the reference docs.
But a common approach is also to check if the user already exists in the database using a transaction.
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 using Firebase's isEmailVerified method to verify an email. The following is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verifying);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
mAuth=FirebaseAuth.getInstance();
spinner=(ProgressBar)findViewById(R.id.progressBar);
spinner.setVisibility(View.GONE);
Log.e("I am launched","hello");
if(user.isEmailVerified()==true){
Log.e("I am here","hello");
State state= new AccountSettingUp(this);
state.doAction();
} else {
Log.e("Maybe i am here","yes");
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("email", "Email sent.");
}
}
});
}
Here, the else code should only run when the email is not verified. However, even after I verify the email and restart the activity, the if statement is not true and the email is sent again.
This behavior appears to be a limitation, possibly a bug, in the current version (10.0.1) of Firebase Authentication. The same issue is reported in this related question.
I tried doing a reload() of the user data after the email verification. That didn't help. As reported in the related question, it seems that a sign-out/sign-in is required to get the new email verification status.
For firebase-auth:10.0.1, it seems that it is not possible. However, the workaround is to log the user out and logging them in again. Upon signing in, the isEmailVerified() function will work properly.
I did a sign up activity
mAuth.createUserWithEmailAndPassword(Email, Password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
user = mAuth.getCurrentUser();
UserProfileChangeRequest profileChange = new UserProfileChangeRequest.Builder()
.setDisplayName(FirstName)
.build();
user.updateProfile(profileChange).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getBaseContext(), "Thanks for signing up, " + FirstName + "! Please verify your email!", Toast.LENGTH_SHORT).show();
user.sendEmailVerification();
mAuth.signOut();
Intent a = new Intent(getBaseContext(),Login_Activity.class);
startActivity(a);
}
else {
Toast.makeText(getBaseContext(),"Failed to create username",Toast.LENGTH_SHORT).show();
}
}
});
}
else{
Toast.makeText(getBaseContext(),"Failed",Toast.LENGTH_SHORT).show();
}
}
});
As seen in the 'task.isSuccessful()' portion of the '.updateProfile' code, I did an 'mAuth.signOut();' and informing them to verify their email before sending them back to the login screen.
On the Login screen, I did a simple 'if (user.isEmailVerified())' statement to check for verification. If they are still not verified, a toast will appear to remind them, if they are verified then they will proceed into the next activity.
Hope this helps!
I am signing up my users using Firebase's email and password method. like this:
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser signed = task.getResult().getUser();
writeNewUser(signed.getUid());
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
updateUser(b);
}
}, 3000);
} else {
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
onSignupFailed();
}
}, 3000);
}
}
});
After the user's email has been successfully registered, I would like Firebase to send a verification email. I know this is possible using Firebase's sendEmailVerification. In addition to sending this email, I want the user's account to be disabled until they verify the email. This would also require using Firebase's isEmailVerified feature. However, I have been unsuccessful in getting Firebase to send the verification email, I have not been able to figure out to get it to disable and enable the account sending the verification email and after it has been verified.
This question is about how to use Firebase to send the verification email. The OP is unable to figure out how to disable and enable the account sending the verification email and after it has been verified.
Also, this is not properly documented in the firebase documentation. So I am writing a step by step procedure that someone may follow if he/she is facing the problem.
1) User can use createUserWithEmailAndPassword method.
Example:
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("TAG", "createUserWithEmail:onComplete:" + task.isSuccessful());
// 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()) {
// Show the message task.getException()
}
else
{
// successfully account created
// now the AuthStateListener runs the onAuthStateChanged callback
}
// ...
}
});
If the new account was created, the user is also signed in, and the AuthStateListener runs the onAuthStateChanged callback. In the callback, you can manage the work of sending the verification email to the user.
Example:
onCreate(...//
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
// NOTE: this Activity should get onpen only when the user is not signed in, otherwise
// the user will receive another verification email.
sendVerificationEmail();
} else {
// User is signed out
}
// ...
}
};
Now the send verification email can be written like:
private void sendVerificationEmail()
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// email sent
// after email is sent just logout the user and finish this activity
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(SignupActivity.this, LoginActivity.class));
finish();
}
else
{
// email not sent, so display message and restart the activity or do whatever you wish to do
//restart this activity
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
}
}
});
}
Now coming to LoginActivity:
Here if the user is successfully logged in then we can simply call a method where you are writing logic for checking if the email is verified or not.
Example:
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//Log.d("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());
// 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()) {
//Log.w("TAG", "signInWithEmail:failed", task.getException());
} else {
checkIfEmailVerified();
}
// ...
}
});
Now consider the checkIfEmailVerified method:
private void checkIfEmailVerified()
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isEmailVerified())
{
// user is verified, so you can finish this activity or send user to activity which you want.
finish();
Toast.makeText(LoginActivity.this, "Successfully logged in", Toast.LENGTH_SHORT).show();
}
else
{
// email is not verified, so just prompt the message to the user and restart this activity.
// NOTE: don't forget to log out the user.
FirebaseAuth.getInstance().signOut();
//restart this activity
}
}
So here I m checking if the email is verified or not. If not, then log out the user.
So this was my approach to keeping track of things properly.
send verification to user's Email
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification();
check if user is verified
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
boolean emailVerified = user.isEmailVerified();
Use FirebaseAuth.getInstance().getCurrentUser().sendEmailVerification() and FirebaseAuth.getInstance().getCurrentUser().isEmailVerified()
There is no way to disable the account via the Firebase SDK. The thing you can do is use the GetTokenResult containing the Firebase Auth ID Token and validate it against your custom backend or set a flag to Firebase database corresponding to that user. Personally I'd go with the flag in the Firebase database
For sending email link with Firebase first you need to grab FirebaseAuth instance
using the instance we create user on Firebase through:
firebaseauth.createUserWithEmailAndPassword(email,pass);
When method return success we send verification link to user using Firebase user instance as follows:
final FirebaseUser user = mAuth.getCurrentUser();
user.sendEmailVerification()
See this link: https://technicalguidee.000webhostapp.com/2018/10/email-verification-through-link-using-firebase-authentication-product-android.
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(this, "please check email for verification.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}else{
Toast.makeText(this, task.getException().getMessage() , Toast.LENGTH_SHORT).show();
}
}
});
For Kotlin
val user: FirebaseUser? = firebaseAuth.currentUser
user?.sendEmailVerification()