如何根据用户ID获取Firebase中任何用户的电子邮件? [英] How to get the email of any user in Firebase based on user id?

查看:80
本文介绍了如何根据用户ID获取Firebase中任何用户的电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取一个用户对象,特别是用户电子邮件,我将使用以下格式的用户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')

有可能吗?

推荐答案

Admin SDK不能在客户端上使用,只能在Firebase Cloud Functions中使用,然后可以从客户端调用.您将获得以下承诺:(设置云功能真的很容易.)

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)

在此处 https://firebase.google.com/docs/auth/admin/manage-users#retrieve_user_data

简而言之,这就是您要寻找的

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

完整代码段

在下面的代码中,我首先通过检查其uid是否在节点userRights/admin下,来验证调用此函数的用户是否有权显示有关任何人的此类敏感信息.

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'})
      }
    })
  })
})

顺便说一句,了解onCall()onRequest()之间的区别这里.

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

这篇关于如何根据用户ID获取Firebase中任何用户的电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆