Jordash
Jordash

Reputation: 3093

How to get the email of any user in Firebase based on user id?

I need to get a user object, specifically the user email, I will have the user id in this format:

simplelogin:6

So I need to write a function something like this:

getUserEmail('simplelogin:6')

Is that possible?

Upvotes: 30

Views: 71770

Answers (6)

kub1x
kub1x

Reputation: 3552

I had the same problem. Needed to replace email in Firestore by uid in order to not keep emails all around the place. It is possible to call it from a script on your computer using Service Account. You don't need Firebase Functions for this.

First Generate service account and download its json key.
Firebase Console > gear icon > Project settings > Service accounts > Generate a new private key button.
https://console.firebase.google.com/u/0/project/MYPROJECT/settings/serviceaccounts/adminsdk

Then create project, add the key and call the Admin SDK.

  1. npm init
  2. npm install dotenv firebase-admin
  3. Place the json key file from above into .keys directory, keeping the project directory clean of keys files. Also .gitignore the directory.
  4. Write the path of the json key file into .env file like this: GOOGLE_APPLICATION_CREDENTIALS=".keys/MYPROJECT-firebase-adminsdk-asdf-234lkjjfsoi.json". We will user dotenv to load it later.
  5. Write following code into index.js:
const admin = require('firebase-admin');

admin.initializeApp({
  credential: admin.credential.applicationDefault(),
});

(async () => {
  const email = "[email protected]";
  const auth = admin.auth();
  const user = await auth.getUserByEmail(email);
  // Or by uid as asked
  //const user = await auth.getUser(uid);
  console.log(user.uid, user.email);
  //const firestore = admin.firestore();
  // Here be dragons...
})();
  1. Run as follows node -r dotenv/config index.js

See the docs

Upvotes: 2

Leonid Shevtsov
Leonid Shevtsov

Reputation: 14179

Current solution as per latest update of Firebase framework:

firebase.auth().currentUser && firebase.auth().currentUser.email

See: https://firebase.google.com/docs/reference/js/firebase.auth.Auth.html#currentuser

Every provider haven't a defined email address, but if user authenticate with email. then it will be a possible way to achieve above solution.

Upvotes: 11

Marcin Frankowski
Marcin Frankowski

Reputation: 35

Current solution (Xcode 11.0)

Auth.auth().currentUser? ?? "Mail"
Auth.auth().currentUser?.email ?? "User"

Upvotes: 0

Qwerty
Qwerty

Reputation: 31919

It is possible with Admin SDK

Admin SDK cannot be used on client, only in Firebase Cloud Functions which you can then call from client. You will be provided with these promises: (it's really easy to set a cloud function up.)

admin.auth().getUser(uid)
admin.auth().getUserByEmail(email)
admin.auth().getUserByPhoneNumber(phoneNumber)

See here https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data


In short, this is what you are looking for

admin.auth().getUser(data.uid)
  .then(userRecord => resolve(userRecord.toJSON().email))
  .catch(error => reject({status: 'error', code: 500, error}))

full snippet

In the code below, I first verify that the user who calls this function is authorized to display such sensitive information about anybody by checking if his uid is under the node userRights/admin.

export const getUser = functions.https.onCall((data, context) => {
  if (!context.auth) return {status: 'error', code: 401, message: 'Not signed in'}

  return new Promise((resolve, reject) => {
    // verify user's rights
    admin.database().ref('userRights/admin').child(context.auth.uid).once('value', snapshot => {
      if (snapshot.val() === true) {
        // query user data
        admin.auth().getUser(data.uid)
          .then(userRecord => {
            resolve(userRecord.toJSON()) // WARNING! Filter the json first, it contains password hash!
          })
          .catch(error => {
            console.error('Error fetching user data:', error)
            reject({status: 'error', code: 500, error})
          })
      } else {
        reject({status: 'error', code: 403, message: 'Forbidden'})
      }
    })
  })
})

BTW, read about difference between onCall() and onRequest() here.

Upvotes: 32

Bhanu Prakash Pasupula
Bhanu Prakash Pasupula

Reputation: 1002

simple get the firebaseauth instance. i created one default email and password in firebase. this is only for the security so that no one can get used other than who knows or who purchased our product to use our app. Next step we are providing singup screen for user account creation.

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    String email = user.getEmail();

every time user opens the app, user redirecting to dashboard if current user is not equal to our default email. below is the code

mAuth = FirebaseAuth.getInstance();
    if (mAuth.getCurrentUser() != null){
        String EMAIL= mAuth.getCurrentUser().getEmail();
            if (!EMAIL.equals("[email protected]")){
                startActivity(new Intent(LoginActivity.this,MainActivity.class));
                finish();
            }
    }

i Am also searching for the same solution finally i got it.

Upvotes: 6

user2124834
user2124834

Reputation:

To get the email address of the currently logged in user, use the getAuth function. For email and password / simplelogin you should be able to get the email like this:

ref = new Firebase('https://YourFirebase.firebaseio.com');
email = ref.getAuth().password.email;

In my opinion, the password object is not very aptly named, since it contains the email field.

I believe it is not a Firebase feature to get the email address of just any user by uid. Certainly, this would expose the emails of all users to all users. If you do want this, you will need to save the email of each user to the database, by their uid, at the time of account creation. Other users will then be able to retrieve the email from the database by the uid .

Upvotes: 8

Related Questions