【问题标题】:How to add Auth Custom claims如何添加身份验证自定义声明
【发布时间】:2022-01-20 10:55:28
【问题描述】:

Firebase 功能

我正在尝试使用可调用函数将我的用户角色设置为管理员:

export const addAdminRole = functions.https.onCall(async (data, context) => {
  admin.auth().setCustomUserClaims(data.uid, {
    admin: true,
    seller: false,
  });
});

城市

这是我在客户端调用函数的方式:

 const register = (email: string, password: string) => {
    createUserWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        // Signed in
        const user = userCredential.user;
        const addAdminRole = httpsCallable(functions, "addAdminRole");
        addAdminRole({ email: user.email, uid: user.uid })
          .then((result) => {
            console.log(result);
          })
          .catch((error) => console.log(error));
        history.push(`/home/${user.uid}`);
      })

      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        // ..
      });
  };

用户已创建,但未添加我的管理员角色

【问题讨论】:

    标签: node.js typescript firebase firebase-authentication google-cloud-functions


    【解决方案1】:

    问题可能来自您没有正确处理 Cloud Function 中 setCustomUserClaims() 方法返回的承诺,因此 Cloud Function 平台可能会在 CF 达到其终止状态之前清理您的 CF。如here in the doc 所述,正确管理云函数的生命周期是关键。

    以下应该可以解决问题:

    export const addAdminRole = functions.https.onCall(async (data, context) => {
        try {
            await admin.auth().setCustomUserClaims(data.uid, {
                admin: true,
                seller: false,
              });
              
              return {result: "Success"}
        } catch (error) {
            // See https://firebase.google.com/docs/functions/callable#handle_errors
        }
      });
    

    另外,你可以重构你的前端代码如下正确chain the promises

    const register = (email: string, password: string) => {
        createUserWithEmailAndPassword(auth, email, password)
          .then((userCredential) => {
            // Signed in
            const user = userCredential.user;
            const addAdminRole = httpsCallable(functions, "addAdminRole");
            return addAdminRole({ email: user.email, uid: user.uid });        
          })
          .then((result) => {
            console.log(result);
            history.push(`/home/${user.uid}`);
          })
          .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            // ..
          });
      };
    

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      相关资源
      最近更新 更多