Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 616
Jordash Avatar asked Apr 27 '15 07:04

Jordash


People also ask

How can I get user details from Firebase?

If the user login with a custom "email/password" you don't know anything else about that user (apart from the unique user id). If a user login with Facebook, or with Google sign in, you can get other information like the profile picture url. It is explained here: firebase.google.com/docs/auth/android/… .

How do I get all users from Firebase authentication?

If you want to view a list of users that has registered thru Firebase Auth, you may view them in https://console.firebase.google.com/ then go to your project and select authentication , in the Users list is all the users that have registered thru Firebase Auth.


1 Answers

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.

like image 113
Qwerty Avatar answered Oct 24 '22 01:10

Qwerty