【问题标题】:Implementing custom claims for an Angular5(AngularFire2)/Cloud Firestore app with Firebase Auth使用 Firebase Auth 为 Angular5(AngularFire2)/Cloud Firestore 应用程序实施自定义声明
【发布时间】:2018-05-20 21:08:48
【问题描述】:

我正在尝试使用 Firebase Auth 在我的 Angular5(AngularFire2)/Cloud Firestore 应用中实现自定义声明。我希望应用以下业务规则。

云功能会更新来自所有来源(Google、电子邮件和密码、Twitter 等)的所有新创建的 Firebase 身份验证用户,以使自定义声明集播放器为真,禁用为假。

    exports.processSignUpNewUser = functions.auth.user().onCreate(event => {
    const user = event.data; // The Firebase user.
    // Check if user meets role criteria.
    if (user.email &&
        user.emailVerified) {
      const customClaims = {
        player: true,
        disabled: false
      };
      // Set custom user claims on this newly created user.
      return admin.auth().setCustomUserClaims(user.uid, customClaims)
        .then(() => {
          // Update real-time database to notify client to force refresh.
          const metadataRef = admin.database().ref("metadata/" + user.uid);
          // Set the refresh time to the current UTC timestamp.
          // This will be captured on the client to force a token refresh.
          return metadataRef.set({refreshTime: new Date().getTime()});
        })
        .catch(error => {
          console.log(error);
        });
    }
  });

Firebase 文档中的这个函数示例为实时数据库做了一些我不确定是否适用于 Cloud Firestore 的事情。对于 Cloud Firestore,我需要做些什么不同的事情?

我想要另一个云功能来更新用户文档角色部分以进行显示

exports.createUserAddDefaultRoles = functions.firestore
        .document('users/{userId}')
        .onCreate
        ((event) => {
        const data = event.data.data();

        const roles = '{ "disabled": false, "player": true }';

        return event.data.ref.set({
            roles: roles
        }, {merge: true});

如何锁定用户文档的角色部分,以便只有云功能可以对其进行更新,同时仍允许用户阅读其个人资料中的信息并编辑用户文档的所有其他属性?
每次用户的自定义声明更改时,我可以编写更好的函数来更新角色部分吗?

【问题讨论】:

    标签: firebase-authentication google-cloud-functions angularfire2 google-cloud-firestore angular5


    【解决方案1】:

    问题 1: 该示例对数据库的作用是告诉客户端刷新其身份验证令牌,以便新声明在发出请求时起作用。这基本上意味着当您更新自定义声明时,您必须告诉客户致电firebase.auth().currentUser.getIdToken(true);

    问题 2: 您只能控制对特定文档的访问,而不是文档属性,因此我的建议是为您不希望用户编辑的内容创建不同的文档集合。 您需要将您的 Firestore 规则更新为:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{userid}{
          allow read, write, update: if request.auth.uid == userid
        }
        match /userClaims/{userid}{
          allow read: if request.auth.uid == userid
        }
      }
    }
    

    问题 3: 由于自定义声明只能在服务器上更改,因此请确保每次更改它们时,您还可以通过调用 firestore 函数或在相同的代码中更改 firestore 文档。

    来源: Firebase docs

    【讨论】:

      猜你喜欢
      • 2018-11-14
      • 2020-01-20
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 2019-12-05
      • 2020-02-02
      • 1970-01-01
      相关资源
      最近更新 更多