Get Identifier field from Firebase Auth Console - firebase

I'm trying to get the email from the user that's currently authenticated using the Facebook Firebase provider. The email is listed under the Identifier field inside the Project's Firebase Authentication Console:
However when I invoke firebase.auth().currentUser the user information loads, however the email field is null. Any ideas on how to get the Identifier (which is where I see the email address) from Firebase? Is this even possible?
Below is the code I'm using:
componentDidMount() {
let user = firebase.auth().currentUser;
let name, email, photoUrl, uid, emailVerified;
if (user !== null) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
emailVerified = user.emailVerified;
uid = user.uid;
console.log(name, email, photoUrl, emailVerified, uid);
}
}
Note: Prevent creation of multiple accounts with the same email address is enabled in Firebase. Also, Facebook API permissions are set to ['public_profile', 'email']

After some testing and debugging I found that the email field will be populated if you're using a regular Firebase Email/Password Sign In method. However, if you're using another Sign In provider method such as Facebook, the email field will appear null (not sure why).
Further inspection of the user object revealed a providerData property.
It's an array that contains all the provider information (including the email address):
So, I updated my code to accommodate this:
componentDidMount() {
let user = firebase.auth().currentUser;
let name, email, photoUrl, uid, emailVerified;
if (user) {
name = user.displayName;
email = user.email;
photoUrl = user.photoURL;
emailVerified = user.emailVerified;
uid = user.uid;
if (!email) {
email = user.providerData[0].email;
}
console.log(name, email, photoUrl, emailVerified, uid);
}
}

In my case, the getEmail() method always returns data for three sign-in possibilities (if user gave authorization to my app to show/use email): Sign in with Email, Sign in with Google, Sign in with Facebook.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
Log.v(TAG,"user.getEmail():"+user.getEmail());
if (user.getEmail() == null){
// User did not authorize the app to show/user email
}
else {
Log.v(TAG,"user.getEmail():"+user.getEmail());
}

Related

Change password of firebase user in flutter

I want to change the password of a firebase account. To do that the user should enter the old password before. If it is correct then he is allowed to change pass. I used this code which is only for changing the pass and not comparing the old one.
void _changePassword(String password) async{
//Create an instance of the current user.
FirebaseUser user = await FirebaseAuth.instance.currentUser();
//Pass in the password to updatePassword.
user.updatePassword(password).then((_){
print("Successfully changed password");
}).catchError((error){
print("Password can't be changed" + error.toString());
//This might happen, when the wrong password is in, the user isn't found, or if the user hasn't logged in recently.
});
}
The idea is to verify old password by resigning in user using firebaseAuth, you can get user email by passing user.email to string, and let user input old password. If sign in proccess failed, password change shouldn't happen.
void _changePassword(String password) async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
String email = user.email;
//Create field for user to input old password
//pass the password here
String password = "password";
String newPassword = "password";
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
user.updatePassword(newPassword).then((_){
print("Successfully changed password");
}).catchError((error){
print("Password can't be changed" + error.toString());
//This might happen, when the wrong password is in, the user isn't found, or if the user hasn't logged in recently.
});
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
}
it will not allow you to verify its previous or old password . it will directly send email for forgot and there you need to add your new password . and and you have to back again to application and your password will be updated as you wil try to login .
If the user hasn't signed in recently, Firebase will automatically require them to reauthenticate before they can change their password (or perform other sensitive operations). So you typically should only require the user to reauthenticate when Firebase tells you to.
When that happens, follow the steps in the documentation on reauthenticating a user.

How to get Facebook Email from flutter_facebook_login in Firebase?

I am using flutter_facebook_login plugin(3.0.0). But my Facebook email doesn't appear inside my Firebase user identifier column; instead, I see this "--". Please help!
Future loginWithFacebook() async {
FacebookLogin facebookLogin = FacebookLogin();
final result = await facebookLogin.logIn(['email', 'public_profile']);
//result.accessToken.
final token = result.accessToken.token;
print('Facebook token userID : ${result.accessToken.permissions}');
final graphResponse = await http.get(
'https://graph.facebook.com/v2.12/me?fields=name,first_name,last_name,email&access_token=${token}');
final profile = jsonDecode(graphResponse.body);
print(profile);
if (result.status == FacebookLoginStatus.loggedIn) {
final credential = FacebookAuthProvider.getCredential(accessToken: token);
FirebaseUser fbUser = (await _auth.signInWithCredential(credential)).user;
//print('Our credential is : $credential');
print('Facebook firebase user ${fbUser.}');
}
return _userFromFacebookLogin(profile);
}
}
Possible Points.
Some Facebook accounts are created using Mobile numbers, so whenever we request for email address we get an empty string.
Email was set to "--" on firebase auth due to missing permission to read email, which fixed by:
final FacebookLoginResult facebookLoginResult = await facebook_Login.logIn(['email', 'public_profile']);
After reading post in firebase-talk google group here https://groups.google.com/forum/#!topic/firebase-talk/gPGNq-IkTLo, I found out the answer. The issue was happened because I'm using "Allow creation of multiple accounts with the same email address" in Firebase Auth sign-in method.
So I change the option into: "Prevent creation of multiple accounts with the same email address" can it's working properly now. It's simple as that. It's true I need more logic to merge accounts having the same email address, but it's okay.
Maybe everyone else having the same issue, can also try this, and hopefully it's solved as well.

Custom username and password login using Flutter firebase

Anyone knows how to have a custom username and password login for flutter using firebase or any other service?
I am not talking about email verification. The user just have to make a username with a password and login.
You can set up a authentication to Firebase with the firebase_auth plugin for Flutter https://pub.dev/packages/firebase_auth
After that you can utilize Firestore to save the user to a collection called users for example with new fields (username in this case) which is assigned to the user.
Which means that on login you need to also map the custom fields from Firestore to the user object in Flutter. The process of getting Firestore data at the same time you being logged in would look something like this (user is a Firebase User object).
AuthService() {
user = Observable(_auth.onAuthStateChanged);
profile = user.switchMap((FirebaseUser u) {
if (u != null) {
return _db
.collection('users')
.document(u.uid)
.snapshots()
.map((snap) => snap.data);
} else {
return Observable.just({});
}
});
}

How to get logged in user's email in Flutter using Firebase

I want to get the email of the logged in user in a Flutter app which uses Firebase for authentication.
I can get the current user by
final user = await _auth.currentUser();
But if I try this to get the mail
final mailID = await _auth.currentUser().email.toString();
I get the following error:
The getter 'email' isn't defined for the type 'Future<FirebaseUser>'.
Try importing the library that defines 'email', correcting the name to the name of an existing getter, or defining a getter or field named 'email'.
How to get the logged in user's email in this case?
Get the user before trying to get the email. code below
<FirebaseUser> user = await _auth.currentUser();
final mailID = user.email;
it's working for me.
import 'package:firebase_auth/firebase_auth.dart';
FirebaseAuth auth = FirebaseAuth.instance;
FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
}
});

Asp.Net Identity OWIN Facebook ExternalLoginInfo Email is always null

I create auth with next code
app.UseFacebookAuthentication(new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
{
AppId = "1058223614196813",
AppSecret = "dd208098e2cac42996581ba2bb59e5d1",
Scope = { "email" },
});
when I try get user email, logininfo return emain null
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
but user name show me. This code work fine some time.
Facebook will not return the email for those users whose email is pending for confirmation, when a user creates new account on facebook a confirmation email is sent to the user, but if user didn't confirm his email, facebook will not return his email in user info even you added email permission in scope, until user confirms his email.

Resources