Firebase documentation: where is the documentation for FirebaseAuth? - android

I am at https://firebase.google.com/docs/auth/android/start/ and I see this code snippets:
private FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword(email, password)
.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, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
I believe that the "FirebaseAuth" class is not part of the FirebaseUI library. I believe it is a part of the firebase SDK.
So I go to the reference for the firebase SDK (https://firebase.google.com/docs/reference/android/com/google/firebase/package-summary). But I cannot find this class anywhere, or the method .createUserWithEmailAndPassword(email, password).
Can someone point me to the documentation for FirebaseAuth? I guess the answer I am looking for would be a URL, along with a conceptual explanation of how this code is organized.

Here you go: https://developers.google.com/android/reference/com/google/firebase/auth/FirebaseAuth
I don't see where else you would rather find this.

Related

FireBase Auth createUserWithEmailAndPassword().then() not working

I am working on an android application that involves user firebase auth for user sign up. The sign up works but I want to add username to database by implementing it in .then() but my android studio keeps giving "unresolved method then(?)". I am also using catch but that seems to work fine.The code I am writing is as following where firebaseAuth is an object of type FirebaseAuth:
firebaseAuth.createUserWithEmailAndPassword(email,password)
.then( (u) => {
//Implementation of then
})
.catch(error => {
switch (error.code) {
case 'auth/email-already-in-use':
EmailWarning.setText("Email already in use");
case 'auth/invalid-email':
EmailWarning.setText("Invalid Email");
case 'auth/weak-password':
PasswordWarning.setText("Password should be 8 characters or longer");
default:
PasswordWarning.setText("Error during sign up");
}
});
I found a similar problem in following link but even after trying this, it's not working.
I looked further into the firebase documentation and found another implementation which uses on complete listener here however the error codes described in this documentation doesn't seem to work with it.
Update 1:
I ended up implementing on complete listener as following:
firebaseAuth.createUserWithEmailAndPassword(email,password)
.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
FirebaseUser user = firebaseAuth.getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(Username)
.build();
user.updateProfile(profileUpdates);
}
else {
// If sign up fails, display a message to the user.
switch (task.getException()) {
case "auth/email-already-in-use":
EmailWarning.setText("Email already in use");
case "auth/invalid-email":
EmailWarning.setText("Invalid Email");
case "auth/weak-password":
PasswordWarning.setText("Password should be 8 characters or longer");
default:
PasswordWarning.setText("Error during sign up");
}
}
}
});
Now the user adding part works fine but the exception handler doesn't work with strings so I can't find a way to work with error codes given on firebase documentation
I wasn't able to find a solution to .then() issue but after searching more into getExceptions() I found a solution at this link. Now my current implementation looks as following:
firebaseAuth.createUserWithEmailAndPassword(email,password)
.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
FirebaseUser user = firebaseAuth.getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(Username)
.build();
user.updateProfile(profileUpdates);
OpenApp();
}
else {
// If sign up fails, display a message to the user.
String errorCode = ((FirebaseAuthException) task.getException()).getErrorCode();
if (task.getException() instanceof FirebaseAuthUserCollisionException)
EmailWarning.setText("Email already in use");
else if(task.getException() instanceof FirebaseAuthInvalidCredentialsException)
EmailWarning.setText("Invalid Email");
else if(task.getException() instanceof FirebaseAuthWeakPasswordException)
PasswordWarning.setText("Password should be 8 characters or longer");
else
PasswordWarning.setText("Error during sign up");
}
}
});
Also found another alternate implementation by try catch and and getException().getErrorCode() here.
I found this in the docs for you:
firebaseAuth.createUserWithEmailAndPassword(email, password)
.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, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
Looks like you need to use .addOnCompleteListener
Doc -> https://firebase.google.com/docs/auth/android/password-auth
I have found my issue with the help of (task.getException())
So I hope maybe it will helpful for resolving your issue.
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
} else {
Log.d("---->",""+task.getException());
}
}
});

How to make groups in firebase authentication using android?

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! 💸

Logging in with FireBase facebook authentication, getCurrentUser() keeps returning null

I am struggling right now to pass on the CurrentUser when I am logging in with Facebook (with firebase authentication). It has been working before, but as I log into my application now, the currentuser keeps returning null.
I think it might be because I am already logged into the app with Facebook, but the firebase authentication sees me as a new user. However, I am not sure.
My onStart on the LogIn page looks the following:
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
mAuth.addAuthStateListener(mAuthListener);
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null && AccessToken.getCurrentAccessToken() != null) {
Log.d(TAG, "onComplete: We run this 2" + currentUser + mAuth);
ItemHolder.getInstance().setUser(mAuth.getCurrentUser());
updateUI();
}
else{
Log.d(TAG, "onComplete: else run in onstart");
}
}
The ItemHolder object is a singleton used to store the information of the User. However, it never reaches that, because the user is always null.
I have added an AuthStateListener, and it says that there is no currentuser. My problem is that I have no idea how to retrieve the currentUser when it keeps returning null? Everything else in my login activity follows the firebase quick guide provided, to login with Facebook.
Okay I fixed my problem.
So I tried to add the currentUser to actually be apart of my updateUi() method. Then it seemed my problem was, that I updated the UI in my facebookCallback(), which seemed to change the activity before actually handling the login.
So now my code looks the following:
private void facebookCallback() {
FBLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "onComplete: onSuccess");
handleFacebookAccessToken(loginResult.getAccessToken());
}
And
private void handleFacebookAccessToken(AccessToken token) {
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
Log.d(TAG, "onComplete: We run this");
updateUI(user);
}
else{
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LogInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}

Firebase Task<AuthResult> task.isSuccessful always returning false

I was doing Firebase Authentication with email & password in Android Studio, so I followed all setup steps in official documentation (added Firebase my project, add the dependencies, enable Email/Password sign-in). Also, I just copied the sample project from their documentation because I just wanted to see if it works. But, when I click the Register button I get the "Authentication failed." toast. That means the task.isSuccessful() returned false..does someone know why this keeps happening? I'm pretty sure problem lies somewhere in Firebase/Android Studio since I copied 99% of their code.
mAuth.createUserWithEmailAndPassword(email, password)
.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
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(MainActivity.this, "Authentication success.",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});

Firebase Chat using my own server instead

I am working on an application and now i want to implement chat functionality, i learned about firebase. But i need authentication. How do i achieve chat functionality of firebase but using my own server.Now i read about custom authentication but i received error that my Token pattern was wrong. Can someone explain to me that what i want is even possible and if so ,then am i using the correct way i.e custom authentication. And how do i generate a valid token. Thank you.
I know there is nothing wrong with the code but just to be sure.
FirebaseApp.initializeApp(this);
FirebaseAuth mAuth = FirebaseAuth.getInstance();
mAuth.signInWithCustomToken(jsonObject.getString(ResponseParam.AUTH_TOKEN))
.addOnCompleteListener(LoginActivity.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
FirebaseUser firebaseUser = mAuth.getCurrentUser();
try {
saveDataInPreference(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});

Categories

Resources