Auth all users to Firebase - java

I have a firebase app for which I don't need or want user signup or login but I want to setup Auth to make sure database can only be accessed through my app. Is there any way to do so?

You can use Anonymous Authentication for that purpose. Users don't need to enter any details for sign up or login, Firebase will simply give them an uid to access your database and you can still keep your Firebase Security Rules set to auth!=null.
Go ahead, add Firebase Auth to your app and then on your Activity:
Grab an instance of the FirebaseAuth Object:
private FirebaseAuth mAuth; mAuth = FirebaseAuth.getInstance();
Sign the user in, anonymously:
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task){
if(task.isSuccessful()){
Log.d(TAG, "signInAnonymously:success");
}
else
{
Log.w(TAG, "signInAnonymously:failure", task.getException());
Toast.makeText(AnonymousAuthActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
});

Related

Firebase facebook and gmail accounts are not merged

When i sign in to my android app using gmail and facebook, two separate authentication credentials are created at firebase. Is it possible to merge them?
Sign in the user using any authentication provider or method. (Assume your user have already Signed In with Google).
Get the credentials for the new Authentication Provider (Facebook).
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
Pass the AuthCredential object to the signed-in user's ``linkWithCredential``` method.
mAuth.getCurrentUser().linkWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "linkWithCredential:success");
FirebaseUser user = task.getResult().getUser();
updateUI(user);
} else {
Log.w(TAG, "linkWithCredential:failure", task.getException());
Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});

I am trying to make an login page and sign up page with firebase . I want to use firebase realtime database for store username and email

Here mAuth.createUserWithEmailAndPassword this method is working but the database method not working.
i make the values true in realtime database .
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
user u = new user(username,email);
>the below method is not working
database.child(Objects.requireNonNull(mAuth.getCurrentUser()).getUid())
.setValue(u).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(signUp.this,"done",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(signUp.this,"failed",Toast.LENGTH_SHORT).show();
}
}
});
}else{
Toast.makeText(signUp.this,"loginfailed",Toast.LENGTH_SHORT).show();
}
}
});
Things to check:
1) Did you initialize your database reference:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
2) Did you initialize your auth:
FirebaseAuth mAuth = FirebaseAuth.getInstance();
3) Are your security rules for real time database allowing read and write?
4) Are your email and password that are being passed to the function null?
problem solved. The problem is only occurring in the emulator . In the physical device, it works fine

Firebase Authentication with Google Play Games

I am creating a game for android. Each user needs to be authenticated.
Currently, when a new user launches the game, it requests an identification code from my server, and stores it to SharedPreferences. Next time user launches the game, it uses this stored identification code to authenticate. The problem is, when user clears data of this app, there's no way he can get his ID back, so he lost his progress forever.
Is there a way how to generate something like Identification code which is unique and always the same for one player using Firebase Play games auth method?
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestServerAuthCode("MyCID")
.build();
mAuth = FirebaseAuth.getInstance();
super.onCreate(savedInstanceState);
final FirebaseAuth auth = FirebaseAuth.getInstance();
AuthCredential credential = PlayGamesAuthProvider.getCredential("MyCID");
auth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
currentUser = auth.getCurrentUser();
} else {
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
if (currentUser == null) {
cu = "NO UID";
} else {
cu = currentUser.getUid();
}
I tried this code (Where is MyCID: I used the CID from the image below), but no Google Play Games pop-up is shown, I get Authentication Failed toast and cu is set to "NO UID".
Can someone explain how does this work please?
EDIT
Thanks to #crysxd , My app now shows the green google play games popup. But instead of expected "Select an account" popup, as I see in other games which uses google games sign in, I get an error, which says "com.google.android.gms.common.api.ApiException: 4:".
Is there a function which I need to run to show this dialog? Am I missing something or just I have incorrectly configured the game in google play console?
My current code: link
You are skipping an essential step here. The Firebase docs are usually very good, but the Play sign in is poorly described.
You got the first step right: You need to set up GoogleSignInOptions but you miss to pass them to a GoogleSignInClient.
Create a client in onCreate:
private static final int RC_SIGN_IN = 543;
private GoogleSignInClient mGoogleSignInClient;
public void onCreate(Bundle savedInstancestate) {
super.onCreate(savedInstancestate)
// ...
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestServerAuthCode("MyCID")
.build();
mGoogleSignInClient= GoogleSignIn.getClient(this, gso)
}
Call this method when the sign in button is clicked or you want to start sign in. This will cause the sign in dialog to be shown.
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
Get the sign in response and handle it
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from
GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
}
}
}
Finally, your code comes into play. Now we have the GoogleSignInAccount which is required to call PlayGamesAuthProvider.getCredential(...). You passed your Client ID here, but that's the wrong thing. This is how it works: You give your client ID to Google just to tell them who (or which app) you are. They will let the user sign in and give you a special token ("id token") which Firebase can then use to get information about the user from Google Play Games. And that's the token you need to give to Firebase here:
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.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, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}
Hope that helps! You can find the entire code referenced in the docs here and here (these are the files they show the snippets from in the docs).

Android Firebase AuthStateListener Email Verified

I have a SignInActivity with Firebase AuthStateListener.
final FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
final FirebaseAuth.AuthStateListener firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(FirebaseAuth auth) {
FirebaseUser user = auth.getCurrentUser();
if (user != null && user.isEmailVerified()) {
firebaseAuth.removeAuthStateListener(this);
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
}
};
firebaseAuth.addAuthStateListener(firebaseAuthListener);
When I successfully registered a new Account, I setVisibity(View.Visible) a verify page with EditTextEmail & VerifyButton inside the activity (in case someone wants to resend the email verification).
What I want to do is when I verify my email from my email account, I want the page to automatically start my MainActivity instead of just staying idle in my LoginActivity, like SMS verification, when verification code received in SMS, the app reads the SMS and navigate to MainActivity. Is it possible to achieve this with email verification? Because the FirebaseAuthState never changed even after I click on verification link on my email.
I need something like OnFirebaseAuthUserEmailVerifiedListener
I'm new to firebase, please kindly give me advice on how to achieve this or if it is not possible.
This link is really useful.
Because the FirebaseAuthState never changed even after I click on verification link on my email.
That's because the user is cached, and you need to reload the user:
Do note that the FirebaseUser object is cached within an app session, so if you want to check on the verification state of a user, it's a good idea to call .getCurrentUser().reload() for an update.
You need something like this
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.
sendVerificationEmail();
}
}
And method to get emailVerification
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
}
}
});
}
Hope this helps you.

How to verify email id authenticated by Google or not when we signup using the Firebase for android?

When users signup using the Firebase Email/Password SIGN-IN METHOD in android, how can we verify their Emails ?
For Android Email verification, first you can view the documentation by firebase here.
Send a user a verification email
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email Sent.");
}
}
});
In my App whenever a user registers, sendEmailVerification(); is triggered
private void sendEmailVerification() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email verification sent.");
}
}
});
}
Using the previous method, your users will now be provided with a verification Email. And it will look something a lot like this
Did they verify their email ?
private void IsEmailVerified() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isEmailVerified()) {
Log.d(TAG, "Email is verified.");
} else {
Log.d(TAG, "Email is not verified !.");
}
}
Sadly, you may not customize the content/body of your verification Email ( I have been heavily corresponding with Firebase to provide alternative less hideous looking templates ). You may change the title or the message sender ID, but that's all there is to it.
Not unless you relink your application with your own supported Web. Here.

Categories

Resources