【问题标题】:Get a auth user by its uid in Firestore cloud function通过 Firestore 云功能中的 uid 获取身份验证用户
【发布时间】:2018-04-17 11:24:30
【问题描述】:

当一个新对象添加到集合中时,我触发了云功能。它看起来像这样:

exports.emailAdmin = functions.firestore
  .document('user-books/{userId}/books/{ASIN}')
  .onWrite(event => {

event.data.data() 是添加到子集合(“书籍”)的对象。 userId 来自 Firebase 身份验证系统。 IE。用户登录,并使用他/她的“uid”向集合“user-books”添加了一个对象。

我试过了:

firestore
    .collection('users')
    .doc(uid)
    .get()

但是,“当然”失败了,因为没有一个名为“users”的集合。如何进入“认证数据库”?

目的是将“uid”转换为那个人的“email”。

【问题讨论】:

  • 你发现了吗?

标签: node.js firebase google-cloud-platform google-cloud-firestore google-cloud-functions


【解决方案1】:

导入 firebase-admin:

import * as admin from 'firebase-admin';

然后获取授权用户:

const uid = ...;
const authUser = await admin.auth().getUser(uid); // this returns a promise, so use await or .then()

console.log(authUser.email);

【讨论】:

    【解决方案2】:

    您无权访问 firebase 中的用户集合。我所做的是创建一个单独的用户表,在其中存储所有用户数据。我在 onCreate Hook 上将新用户添加到我的集合中,如下所示:

    exports.addNewUserToUserTable = functions.auth.user()
    .onCreate(event => {
        let user = event.data;
        let database = admin.firestore();
    
        return database.collection('user').doc(user.uid).set({
            email: user.email
        });
    

    另一个问题是,目前无法在 Firestore 数据库触发器上获取登录用户的 ID(它适用于实时数据库)。我还在等待这个功能发布...

    【讨论】:

    • 这样做安全吗?我想让 UID 可以从 Firestore 访问,这不安全,是吗?
    • 我在这里看不到任何安全问题。我的用户集合受 Firestore 安全规则保护,我没有在其中存储任何密码。我希望这会有所帮助。
    • 我需要用户访问 UID 以查看他们创建了哪些博客文章(个人资料),所以我想我不能只制定规则,除非我只从云功能访问它。
    • 如果此代码对任何人都不起作用,这里的解决方法是:stackoverflow.com/a/44125209/7387243
    • @Telion - 据我了解,您不会让每个用户都只能访问创建的用户集合中自己的文档。您可以通过在 firestore hocks 上创建云功能来实现这一点,您只需检查用户是否正在访问它自己的 ID。唯一的缺点是,您还无法在 Firestore 数据库触发器中获取用户 UID。 :(我希望这是有道理的。:)
    【解决方案3】:

    您的问题似乎不完整-您引用了未出现在代码 sn-p 中的 event.data.data() 行。如果丢失,您可以查看并添加它吗?

    另外,为了澄清您的目的 - 您希望能够访问已通过身份验证的用户的电子邮件地址,并将其标记到该用户已添加的图书中?

    谢谢。

    【讨论】:

    • event 是第一个代码 sn-p 的最后一行中提到的第一个也是唯一一个参数。
    • 不,这个想法是从云函数中的 uid 追溯获取用户对象。在此上下文中没有浏览器或登录会话。
    【解决方案4】:

    因为 context.auth.uid 不适用于 Firestore。您可以将 userId 分配给文档并在规则中阅读。

    match /collectionA/{docId} {
      allow update: if request.resource.data.userId == request.auth.uid;
    }
    
    exports.createProfile = functions.firestore
    .document('collectionA/{docId}')
    .onCreate((snap, context) => { // or onUpdate
      const newValue = snap.data();
      const {userId} = newValue;
    });
    

    【讨论】:

      猜你喜欢
      • 2018-04-18
      • 2020-08-17
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 2019-06-08
      相关资源
      最近更新 更多