I am developing an app, and so far it's able to upload images, and register users.
However, these two functionalities run independent of each other. Ergo, I need to make it so that the images are saved under the user that uploads it. I am a novice Android programmer and just started learning about Firebase and could use the help.
In Registration process,
FirebaseAuth.getInstance()
.createUserWithEmailAndPassword(email, email)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
android.util.Log.e("Firebase", "performFirebaseRegistration: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()) {
AlertUtils.showAlert(MainActivity.this, getString(R.string.sign_up), task.getException().getMessage());
} else {
FirebaseUser firebaseUser = task.getResult().getUser(); // here you will get userDetails
}
}
});
From firebaseUser you can get user id by firebaseUser.getUid().
Once you upload the message,sent to realtime firebase b the user id as below,
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child(ARG_USERS)
.child(firebaseUser.getUid())
.child("image")
.setValue(<you image download url>);
Related
I am a newbie in Firebase. Recently I am trying to save users into Firebase but I can't. When I generate the APK and run it onto the real device(Not Emulator), the new user does not add it into the Firebase. Also, no errors shown up. Task executed properly and go to OTPActivity. Here is my complete code:
public void saveUser()
{
firebaseAuth.createUserWithEmailAndPassword(emailAddress.getText().toString(),password.getText().toString()).addOnCompleteListener(ChatUserSignUpActivity.this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
FirebaseUser user = firebaseAuth.getCurrentUser();
Intent intent = new Intent(ChatUserSignUpActivity.this, OTPActivity.class);
intent.putExtra("phoneNum",emailAddress.getText().toString());
startActivity(intent);
}
else
{
Toast.makeText(ChatUserSignUpActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
Please help me. Thanks in advance.
When you authenticate your users with email and password, no data is saved into Firestore, nor in the Realtime Database. If you need to save the database in the database, you need to write code for that. So once your user is authenticated, you can get the data from the FirebaseUser object and write it to the database of your choice.
i have some question about firebase authentication, is possible to make groups? for example i have an app for a salesman and another for a buyer and i want to save authentication in 2 different groups.
I asking this if is possible i can make a firebase automatically do a difference of tow tipes of credentials.
I'm create a login if password like this;
mAuth.createUserWithEmailAndPassword(email, senha)
.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("TagCerta", "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
comerciante.setUid(user.getUid());
comerciante.salvar();
Intent inicio = new Intent(CadastrarActivity.this, ComercianteActivity.class);
startActivity(inicio);
finish();
} else {
// If sign in fails, display a message to the user.
Log.w("TagErrada", "createUserWithEmail:failure", task.getException());
Toast.makeText(CadastrarActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
You cannot do that in firebase authentication. To be able to do that, you need to use firebase database, then you can do the following:
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("salesman");
ref.child(currentFirebaseUser.getUid()).child("name").setValue("peter sells 💰");
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("buyer");
ref.child(currentFirebaseUser.getUid()).child("name").setValue("peter buys also! 💸");
Then you would have the following database:
salesman
userId
name : peter sells 💰
buyer
userId
name : peter buys also! 💸
I'm using Firebase Authentication in my app (email and password auth).
In the onStart() method of my Login activity I retrieve the current user using:
FirebaseUser currentUser = mAuth.getCurrentUser();
The problem comes when the user is deleted from the database, the mAuth.getCurrentUser() method still retrieves the user and allows authentication.
How can I check if the user still exists?
Thx!
Try using something like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("email").addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// used "email" already exists and is not deleted
} else {
// User does not exist. Add here your logic if the user doesn't exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or check some of the following SO questions and answers:
Firebase authentication for checking if the user exists in the database or not
Firebase Auth - with Email and Password - Check user already registered
You can use getInstance. This worked for me fine. You don't get an instance with it.
private boolean isSignedIn() {
return FirebaseAuth.getInstance().getCurrentUser() != null;
}
Delete the userdata and make the currentuser null:
Follow the below code.
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted.");
//Remove the information f the user from database.
}
}
});
The code below works great on android to confirm if the Firebase Auth user still exists (has not been deleted or disabled) and has valid credentials.
Deleting the Auth user from the firebase console does not revoke auth tokens on devices the user is currently logged in as the token is cached locally. Using reload() forces a check with the firebase auth server.
currentUser.reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
//User still exists and credentials are valid
}else {
//User has been disabled, deleted or login credentials are no longer valid,
//so send them to Login screen
}
}
});
I see in the docs how to update your own email once you are logged in, like so:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail("user#example.com")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
}
}
});
What I want, though, is to be logged in as an user and be able to update the email of another user(The logged in user is an admin). With the approach above that's not possible, because you can get only the current user from FirebaseAuth.
Does anyone know how to achieve that?
There is currently no administrative API for Firebase Authentication. We're working on adding this to our server SDKs, but there is no definitive timeline for its availability yet.
I knew that we can verify the users email with Firebase Auth 3.0. I'm not able to find any documentation regarding email verification on Android. I'm able to find the same for iOS as well as web but not for Android. Any link to the documentation would be helpful.
From the image, it is clear that once the user signs in, he will be intimated regarding that on email to confirm his subscription. I've subscribed myself and also verified in the users section in Auth tab and I am able to see my mail id and firebase generated unique user id. What's missing here is the confirmation email to my email id. Did some one try this or am I too early trying this? Thanks for your help.
Email verification for android is now available in Firebase.
See this release note:
https://firebase.google.com/support/release-notes/android#9.6
Update
Email verification is available in version 9.6 and higher of the Firebase SDK for Android.
Original answer
Email verification is not available for Android yet. Also answered here with more context.
An alternative suggested by the Firebase team
One thing you could do is to add a node to your Firebase Database which contains all email addresses as children. You should make this node only publicly readable (via Firebase security rules).
Then from within your apps, once a user signs up / signs in, you check if the email of that user is on the list, and if not, you sign them out and kick them out of your app (and as a bonus, you could even log the intruder's email address in your database, so you can later check who is trying to access your app).
This will work for initial testing if you know the e-mail ids of the people who are gonna test your app until the e-mail verification makes its way to Android.
Since email verification only works with Email/Password authentication, the best place to send it wold be in the onComplete method of createUserWithEmailAndPassword(...) method, after signup is successful.
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
sendVerificationEmail();
....
The custom sendVerification method is:
public void sendVerificationEmail() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Signup successful.
Verification email sent", Toast.LENGTH_SHORT).show();
}
}
});
}
}
You can then check if the user has verified their email anywhere in your app by calling:
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null ) {
Log.e(TAG, firebaseUser.isEmailVerified() ? "User is signed in and email is verified" : "Email is not verified");
} else {
Log.e(TAG, "onAuthStateChanged:signed_out");
}
}
};