Firebase Chat using my own server instead - android

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();
}
}
});

Related

How to get Firebase auth token in Android login

I'm using Firebase auth to login users to my webapp and android app.
The flow for the webapp lets me log the user in from the client, then pass the Firebase token to my server where I verify with Firebase before adding various user info to my database.
I'm now trying the same thing for Android, but am having some problems getting the token.
Here is the login code:
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
// ...
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener((MainActivity) context, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// ***I want to get the token here***
FirebaseUser fbUser = task.getResult().getUser();
// send user details and token to server
} else {
// If sign in fails, display a message to the user.
}
}
}
});
Elsewhere, I see that in the Firebase docs, there is this snippet that gets the Task<GetTokenResult> , which is what I want, but I can't seem to get this in the createUserWithEmailAndPassword method.
From the firebase docs
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
mUser.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(#NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String idToken = task.getResult().getToken();
// Send token to your backend via HTTPS
// ...
} else {
// Handle error -> task.getException();
}
}
});
How can I get the token in createUserWithEmailAndPassword?
You can use your second bit of code inside the first bit, after the sign-in completes.
// ***I want to get the token here***
FirebaseUser fbUser = task.getResult().getUser();
fbUser.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
// ...
}

Firebase documentation: where is the documentation for FirebaseAuth?

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.

Im Creating Registration with email and Password but with Fullname in Android Studio with Firebase

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();
}
}
});
}

Android- How to upload image to Firebase under specific users

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>);

How to link Multiple Auth Providers to an Firebase Account on Android?

I referenced the documentation in Firebase page. My problem is in this paragraph:
The call to linkWithCredential will fail if the credentials are already linked to another user account. In this situation, you must handle merging the accounts and associated data as appropriate for your app:
FirebaseUser prevUser = currentUser; currentUser = auth.signInWithCredential(credential).await().getUser(); // Merge
prevUser and currentUser accounts and data // ...
I can't figure out how to add this code into my project. When and where do I put this code
auth.signInWithCredential(credential).await().getUser();
into my java file? Android Studio announced me that it can't resolve await() method.
What should I do to resolve that problem. Thank you in advance!
You should handle this part of code when the linkWithCredentials call fails.
Here is a small example :
mAuth.getCurrentUser().linkWithCredential(credentials).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
FirebaseUser prevUser = currentUser;
try {
currentUser = Tasks.await(auth.signInWithCredential(credential)).getUser();
} catch (Exception e) {
e.printStackStrace();
}
// Merge prevUser and currentUser accounts and data
// ...
} else {
}
}
});
NB: Task.await() doesn't exist anymore you should use Tasks.await(...) static method instead.
Suppose that:
One account per email address setting is enabled on firebase authentication
User are logging in with anonymous authentication
The linkWithCredential usually fails with FirebaseAuthUserCollisionException, it could happen either because this credential is used to login before (you can check by searching this email on firebase console) or this email account is used to login before but with different providers ( such as a user logged in with abc#gmail.com by using google sign in before, now he/she uses abc#gmail.com but with Facebook login ) To handle it, you need 2 steps:
Step 1: link with anonymous account
private void linkWithAnonymousAccount(final AuthCredential credential) {
mFirebaseAuth.getCurrentUser().linkWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
getFirebaseToken();
} else {
Exception exception = task.getException();
if (exception instanceof FirebaseAuthUserCollisionException) {
signInWithFirebase(credential);
} else {
Utils.showDialogMessage(mContext, task.getException().getLocalizedMessage());
}
}
}
});
}
Step 2: sign with firebase
private void signInWithFirebase(AuthCredential credential) {
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
getFirebaseToken();
} else {
Utils.showDialogMessage(mContext, task.getException().getLocalizedMessage());
}
}
});
}
Google says the step 2 is merging because after signed in, you need to get information of the previous user and put into the new user.
I hope it helpful.

Categories

Resources