how to use firebase phone auth without create new uid [duplicate] - flutter

This question already has answers here:
Firebase phone Auth for Android , Can we just verify phone number without creating a user account
(3 answers)
Closed 3 years ago.
How to use firebase auth with phone number to verify phone number without create new uid i want to know just if the input code is correct or not
this the code that i used but it creates new uid
manualVerification() {
print("My Id" + verificationId);
FirebaseAuth.instance
.signInWithPhoneNumber(verificationId: verificationId, smsCode: smsCode)
.then((user) {
print("Verification Successful");
print("$user");
setState(() {
showStatus=3;
});
widget.onVerificationSuccess();
}).catchError((error) {
print("Verification Failed Due to $error");
widget.onVerificationFailure();
});
}

The whole point of Firebase Authentication is to create a user account with a unique ID. There's no way to separate out the process that just verifies the phone number.

Related

How to Get a Current user Information even when the User is Not Logged In ..Firebase Flutter

I'm trying to work on Forgot Password but without using firebase's sendPasswordResetEmail method..
Is it possible to reset firebase user password without logged-in. I am implementing forget-password screen where the user enter their email address and will send OTP to user email address, once OTP is verified then they can reset their password from flutter app itself.
Is there anything I can do to get the user's information while the user is Not Signed In.
Obviously it is returning Null because the user's is not signed in
I tried to get the current user information
Future validatePassword() async {
print("Inside Validate Password");
try {
var auth = FirebaseAuth.instance;
User currentUser = auth.currentUser!;
print("Current User $currentUser");
if (currentUser != null) {
print(currentUser.email);
}
} catch (e) {
print("Current user is Not Found");
}
}

Firebase Auth - forgotten password with phone auth

My app currently allows a user to create their Firebase account via phone number. I'm currently trying to figure out the logic for a password reset when the user created their account with a phone number rather than email.
The only reset password functionality i can find on the Firebase docs requires an email address.
Any help is appreciated!
You can use verifyPhoneNumber:UIDelegate:completion: to send the users another SMS message for verification and then sign in using the verificationID.
Official doc on how to do that -> https://firebase.google.com/docs/auth/ios/phone-auth#send-a-verification-code-to-the-users-phone.
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
if let error = error {
self.showMessagePrompt(error.localizedDescription)
return
}
// Sign in using the verificationID and the code sent to the user
// ...
}
OR
If you have a server, you can use Firebase admin SDK, available in Node.js, Java, Python, Go, and C#, to update the user's password property just with user's uid.
Example in Node.js:
admin.auth().updateUser(uid, {
password: "YOUR_NEW_PWD"
})
.then((userRecord) => {
console.log('Successfully updated user', userRecord.toJSON());
})
.catch((error) => {
console.log('Error updating user:', error);
});

How to get Firebase UID knowing email user?

I am building a Flutter app where the administrator profile can create users to access their company. The code works right, unless the new user was previously created for another company. In this case an error of type ERROR_EMAIL_ALREADY_IN_USE appears from FIREBASE AUTH. What I want to do is simply retrieve the assigned UID from FIREBASE AUTH, which is necessary to assign the user within my database to an additional company.
It's my code...
_register(LoginBloc bloc, BuildContext context) async{
final usuarioBloc = Provider.usuarioBloc(context);
if (!formKey.currentState.validate() ) return;
final info = await usuarioProvider.crearUsuarioFirebase(bloc.email, bloc.password, true);
if (info['ok']) {
final keyUserId = info['localId'];
usuarioProvider.crearUsuarioRaiz(keyUserId, _prefs.idEmpresa, bloc.email);
usuario.idUsuario = info['localId'];
usuario.correo = bloc.email;
usuarioBloc.crearUsuarioEmpresa(usuario, usuario.idUsuario, usuario.idEmpresa); //to create user in the Company
print('******* User was Created *************');
} else { //info['ok'] is false
switch (info['mensaje'].code) {
case 'ERROR_EMAIL_ALREADY_IN_USE':
usuario.correo = bloc.email;
// usuario.idUsuario = ????????
// Here I would like to retrieve the UID to assign it to their additional Company
usuarioBloc.crearUsuarioEmpresa(usuario, usuario.idUsuario, usuario.idEmpresa); //to create user in the Company
print('*** User already in use, the user can use his/her usual password ***');
break;
default:
print(info['mensaje'].message); //If it was a different error
}
}
}
In Provider, I have...
Future <Map<String, dynamic>> crearUsuarioFirebase(String email, String password, [bool desdeAdmin = false]) async {
try {
AuthResult result = await _firebaseAuth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
return {'ok' : true, 'localId':user.uid, 'email' : user.email};
} catch (e) {
print(e);
return {'ok': false, 'mensaje': e};
}
}
How can I programmatically obtain the UID knowing its user email?
There is no way to look up a user's UID from their email address using the Firebase Authentication client-side APIs. Since this lookup is considered a trusted operations, it is only available in the Admin SDK for Firebase Authentication.
The two most common solutions are:
Create a custom server-side API in a trusted environment (such as Cloud Functions) that performs the lookup, and then call that API from your client-side application. You will have to make sure that only authorized users can perform this lookup.
Store the information about each user into a database (like the Realtime Database that you tagged your question with) when their account is created, or whenever they sign in. Then you can look up the UID from the email in the database. Here too, you will have to ensure that the data is only available in ways that fit with your application's data privacy requirements.
Note that if you just need to know whether an email address is in use (and not the specific UID that uses it), you can call the fetchSignInMethodsForEmail method.

How to register user into firebase using phone number without OTP with flutter?

I'm trying to register the user with phone number into firebase, but got an exception PlatformException(error, Cannot create PhoneAuthCredential without either verificationProof, sessionInfo, ortemprary proof., null)
is it possible to register user only with phone number without any OTP?
i tried below code
signIn()async{
AuthCredential credential= PhoneAuthProvider.getCredential(
verificationId: verificationId,
smsCode: smsCode
);
await firebaseAuth.signInWithCredential(credential).then((user){
Navigator.of(context).pushReplacementNamed('/homepage');
print('signed in with phone number successful: user -> $user');
}).catchError((onError){
print(onError);
});
}
the method .signInWithCredential(which actually logs-in the user) requires a parameter of type credentials, these credential are either derived by the method .verifyPhoneNumber in the verificationCompleted case (only in Android, which doesn't send the sms and verify automatically the phone number, care that is not working always and you should always have a UI fallback) or in the codeSent case it returns a verificationId and sends the SMS. These two are the one you should pass to the function PhoneAuthProvider.getCredential.
In the first case you dont need to call the PhoneAuthProvider.getCredential method as you already have a credentials object.

profile.providerId returns firebase instead of the social provider name [duplicate]

This question already has an answer here:
Firebase returns multiple IDs, Which is unique one?
(1 answer)
Closed 6 years ago.
I've successfully create authentication using Twitter with Firebase, but when I do (as indicated here):
if (user != null) {
user.providerData.forEach(function (profile) {
console.log("Sign-in provider: "+profile.providerId)
});
}
it prints out firebase. I expected to read twitter. How do I know which provider the user signed in with)?
Suppose you have this as you refrence variable
var authObj = $firebaseAuth(ref);
And Your using this in your init funtion to check if user is logged in or not
authObj.$onAuth(authDataCallback);
then you should try this for getting provider name and other details
function authDataCallback(authData) {
if (authData) {
console.log(authData.provider);
}
}
Hope it will help you out :)