Firebase AuthUI Smartlock Cleanup - firebase

In Firebase, I am using AuthUI for Sign In. I tried FirebaseAuth.getInstance.signout() to remove the current user credentials, but I think maybe for Google SmartLock credentials, it's not signing out. Help me out.
My Code:
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
if (user.getEmail().equals("example#gmail.com")){
//Codes to implement
} else {
FirebaseAuth.getInstance().signOut();
}
} else {
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
.build(), RC_SIGN_IN
);
}
}
};
}

For me the fix was;
AuthUI.getInstance().setIsSmartLockEnabled(false)...
When logging in, and then;
AuthUI.signOut(context)
When Signing out

Related

Firebase Auth with unity creates new user in every start

I'm using firebase anonymous authantication for my unity project.
As i always did when project is started i'm sending request to firebase for authantication,
but on my last project (which uses firebase sdk 6.16.0) my request creates new user everytime.
Here is some code about how i'm sending my request
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.SignInAnonymouslyAsync().ContinueWith((task =>
{
if (task.IsCanceled)
{
Debug.Log("task cancelled");
return;
}
if (task.IsFaulted)
{
Debug.Log("task cancelled");
return;
}
if (task.IsCompleted)
{
Firebase.Auth.FirebaseUser userr = task.Result;
firebaseUserId = userr.UserId;
Debug.Log("firebaseUserId");
Debug.Log(firebaseUserId);
//every opening returns new uniq id here.
}
}));
On firebase authantication panel i only activated anonymous login. any suggestions?
Or is there any way to downgrade unity firebase version? i've tried to import old version which i was using on my last game (sdk 6.15.2) but there is some errors on resolver.
Basically, every time you call SignInAnonymouslyAsync you'll create a new user and the last one will be basically lost (it's more or less a random hash - anonymous as it's name suggests).
I'll typically do something like:
using System;
using Firebase.Auth;
using UnityEngine;
using UnityEngine.Events;
public class Login : MonoBehaviour
{
public UnityEvent OnSignInFailed = new UnityEvent();
public UserSignedInEvent OnUserSignedIn = new UserSignedInEvent();
public async void TriggerLogin()
{
var auth = FirebaseAuth.DefaultInstance;
var user = auth.CurrentUser;
if (user == null)
{
try
{
user = await auth.SignInAnonymouslyAsync();
}
catch (Exception e)
{
Debug.LogException(e);
OnSignInFailed.Invoke();
return;
}
}
// user definitely should not be null!
if (user == null)
{
OnSignInFailed.Invoke();
Debug.LogWarning("User still null!?");
return;
}
var userName = user.UserId;
OnUserSignedIn.Invoke(userName);
Debug.Log($"Logged in as {userName}");
}
[Serializable]
public class UserSignedInEvent : UnityEvent<string>
{
}
}
Note that for this code snippet, TriggerLogin is a public method so I can chain it off of a UnityEvent in the Unity editor.
Try and Put it some kind of check to find if used is already logged in. If yes, then do a silent login, if no then use anonymous login.
Currently you are straightaway logging in user even if they logged in last time they opened the Application.
Try this link: https://github.com/firebase/quickstart-unity/issues/266#issuecomment-447981995

Best way to read a user on init

I have a problem, when I go to the view of the home in my app I have to instantiate a user from firebase, at the time of obtaining the name is null.
I do not know how to bring a user and expect it to load asynchronously because the initial state of the widget does not allow the asynchronous tag.
If I assign it to 'Then' it is also null
Thank you!
//Home Widget State
User currentUser = widget.userController.getCurrentUser(); //ERROR
//CONTROLLER
Future<User> getCurrentUser() async {
User user = await _db.collection('users').document(await getCurrentUserUID()).get().then((snapshot){
return User.fromJson(snapshot.data);
});
print(user.toString());
return user;
}
I'm assuming you're looking for something like this?
Map _userProfile;
#override
void initState() {
super.initState();
FirebaseAuth.instance.onAuthStateChanged.listen((user) {
if(user != null) _getUserProfile(user.uid);
});
}
void getUserProfile(String uid) {
_db.collection('users').document(uid).get().then((snapshot){
setState(() {
_userProfile = snapshot.data;
});
});
}

Handling asynchronous wifi check in Flutter application

I'm making a Flutter App where I want to check whether or not a user has wifi enabled before proceeding to a different action.
if (wifiEnabled) {
//Do stuff
}
else {
//Tell the user to turn on wifi
}
I have a code snippet that allows me to check whether a user has an internet connection from this post. Check whether there is an Internet connection available on Flutter app
void _checkWifi() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
_wifiEnabled = true;
}
} on SocketException catch (_) {
print('not connected');
_wifiEnabled = false;
}
}
The issue I am having though is that because the checkWifi function is asynchronous. If the user goes from having no wifi to having wifi the boolean isn't updated by the time the if(wifiEnabled) code is checked so according to the logic wifiEnabled will be false, despite the user having wifi.
If the user were to try again however they would have wifi as the wifiEnabled will be updated to true. I've tried using Timer and Future.delayed but I haven't been able to solve my issue so far.
Any advice for dealing with the issue or async calls in general would be very helpful. Thanks
Hope below code helps you to get the idea.
class YourWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
showWifiAlert();
return ...
}
void showWifiAlert() async {
var wifiEnabled = await getWifiStatus();
if (wifiEnabled) {
//Do stuff
}
else {
//Ask user to enable internet
}
}
Future<bool> getWifiStatus() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
return true;
}
} on SocketException catch (_) {
print('not connected');
return false;
}
}
}

Changing phone number for Firebase Phone Auth creates a new user UID? [duplicate]

I am using Android Firebase Auth Ui for providing Phone Number based sign in option in an android app. I am trying to provide an additional option to signed in users to switch their signed in phone number to another number keeping the same user account.
But as per Firebase Docs for Phone number there are no options to change the signed in number.
There are options for linking different auth providers like email, google or Facebook login etc to same account. But there is no way mentioned about how to change the phone number or email id keeping the same user id.
Is there a workaround or method by which we can achieve this?
An API exists for updating the phone number of a current user: FirebaseUser#updatePhoneNumber(PhoneAuthCredential credential)
I also had this challenge to update user phone number and when I go on documentation I got something by using I have done this task.
you can go for documentation by click here
Now the method you can use : - for java android project.
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential( "+91-98298XXXX2", "OTP_CODE" );
// Update Mobile Number...
firebaseAuth.getCurrentUser().updatePhoneNumber(phoneAuthCredential)
.addOnCompleteListener(new OnCompleteListener <Void>() {
#Override
public void onComplete(#NonNull Task <Void> task) {
if (task.isSuccessful()) {
// Update Successfully
} else {
// Failed
}
}
}
);
val options = PhoneAuthOptions.newBuilder(FirebaseAuth.getInstance())
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(100L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(activity) // Activity (for callback binding)
.setCallbacks(returnCallBack()) // OnVerificationStateChangedCallbacks
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
private fun returnCallBack() = object : PhoneAuthProvider
.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
FirebaseAuth.getCurrentUser()?.updatePhoneNumber(credential)
}
override fun onVerificationFailed(e: FirebaseException) {
// This callback is invoked in an invalid request for verification is made,
// for instance if the the phone number format is not valid.
Log.e("phone", e.toString())
}
override fun onCodeSent(verificationId: String, token: PhoneAuthProvider.ForceResendingToken) {
//You need this to pass as a parameter for the update method call.
vericationSent = verificationId
}
}
fun confirmChange(code: String, context: Context?) {
if(code.contains(Regex(onlyNumber))) {
Log.d("codeSent" , "Right code : $code")
FirebaseAuth.getCurrentUser()
?.updatePhoneNumber(PhoneAuthProvider.getCredential(vericationSent, code))
?.addOnCompleteListener {task ->
//it worked if you reach here.
}?.addOnFailureListener {
//Show the error to user
}
}
vericationSent = EMPTY
} else {
Log.d("codeSent" , "wrong code : $code")
}
}
Try this
//Send otp to phone number
String verificationId;
private void startLoginFirebase(){
PhoneAuthProvider.getInstance(firebaseAuth).verifyPhoneNumber(phone, 90L, TimeUnit.SECONDS, PhoneAuthActivity.this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
updatePhoneNum();
}
#Override
public void onCodeAutoRetrievalTimeOut(#NonNull String s) {
super.onCodeAutoRetrievalTimeOut(s);
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
processFurther(e.getLocalizedMessage().toString(), 0);
}
});
}
//Verify Otp
private void updatePhoneNum(){
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(verificationId, otp);
firebaseAuth.getCurrentUser().updatePhoneNumber(phoneAuthCredential).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
Apparently - according to the project maintainers - FirebaseUI-Android doesn't support this feature, and it looks like they have no plans of doing it any time soon :(

Sign In With Email and Password method in Firebase has a bug

I have one account including email and password in firebase authenication. But when I use this code, the firebase always return "Sign in successfully", even when I input wrong email and password. I look fowarding to your help. Thank you very much!
private void signIn(){
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isComplete()){
Toast.makeText(MainActivity.this,"Sign in successfull",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this,"Sign in failed",Toast.LENGTH_SHORT).show();
}
}
});
}
That's because you're using isComplete which will always be true since you're running it under onComplete. Use isSuccessful instead.
if(task.isSuccessful()){
Toast.makeText(MainActivity.this,"Sign in successfull",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this,"Sign in failed",Toast.LENGTH_SHORT).show();
}

Resources