【问题标题】:Removing custom claims删除自定义声明
【发布时间】:2021-06-25 13:10:42
【问题描述】:

我正在开发一个项目,该项目使用自定义声明使用户成为管理员。 我的客户希望能够删除用户的管理员权限,但我很难删除它们。目前我的函数有这个代码:

// Remove token

exports.removeToken = functions.https.onCall((data, context) => {
  return admin.auth().getUserByEmail(data.email).then(user => {
    return admin.auth().setCustomUserClaims(user.uid,{
      claim: null
    })
  }).then(()=> {
    return {
      message: `Success! ${data.email} has been removed as an admin.`
    }
  }).catch (err => {
    return err;
  });
});

对于组件本身,代码是这样的

import React, { Component } from 'react'
const firebase = require("firebase");

export default class RemoveAdmin extends Component {

    state = {
        removeAdminEmail: '',
        results: ''
    }

    updateEmail = (e) => {
        this.setState({
            removeAdminEmail: e.target.value
        })
    }

    updateUserStatus = (Email) => {
        firebase.firestore().collection('users').doc(Email).update({
          accountStatus: "User"
        })
      }
    

    removeAdmin = (e) => {
        e.preventDefault();
        const removeAdminRole = firebase.functions().httpsCallable('removeToken');
        removeAdminRole({email: this.state.removeAdminEmail}).then(this.setState({ results: "This user is no longer an admin"}))
        this.updateUserStatus(this.state.removeAdminEmail)
    }

    render() {
        const result = this.state.results ? <div className = "ResultsBox">{this.state.results}</div> : ''
        return (
            <div className = "AddAdminForm">
            <form className = "admin-actions" onSubmit={this.removeAdmin}>
                <p> Remove Admin </p>
                <input type = "email" placeholder = "Enter users email address" id = "admin-email"  onChange={this.updateEmail} required/>
                <button type="submit"> Make Admin </button>
                {result}
                
            </form>
        </div>
        )
    }
}

基本上,管理员输入他们想要删除权限的用户的电子邮件地址,然后给他们一个自定义声明并将数据库中的“accountStatus”字段更改回用户。

我收到以下错误消息

Unhandled Rejection (Error): internal

这并没有给我太多信息!

【问题讨论】:

  • 如果记录错误会得到什么:.catch (err =&gt; { console.log(err);return err;});?
  • 实际上,如果userID 是正确的用户ID,则执行setCustomUserClaims(userID, {claim: null}) 不会产生任何错误。您的电子邮件可能有问题。除了按照上述建议记录错误之外,您能否检查它的值。
  • @RenaudTarnec 感谢您的帮助!我目前在我的控制台中收到此错误```从源'localhost:3000'获取'LINK TO FUNCTION'的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。 ```
  • 您应该尝试同时部署 Cloud Function 和应用程序,或者使用模拟器并将您的应用程序连接到模拟器。见firebase.google.com/docs/emulator-suite/connect_functions
  • @RenaudTarnec 这行得通!我不确定这是否是问题所在,或者是否是因为我不小心部署到项目的不同版本>。

标签: javascript firebase-authentication google-cloud-functions firebase-admin


【解决方案1】:

要删除分配给用户的所有自定义声明,您需要传递一个空对象,如下所示:

return admin.auth().setCustomUserClaims(user.uid, {});

要仅删除分配给用户的自定义声明之一,您需要传递一个包含所有当前自定义声明但要删除的自定义声明的对象,如下所示:

// set two claims
return admin.auth().setCustomUserClaims(user.uid, {admin: true, writer: true});

// remove the Admin claim
return admin.auth().setCustomUserClaims(user.uid, {writer: true});

【讨论】:

    【解决方案2】:

    setCustomUserClaims 始终覆盖所提供用户的现有自定义声明。它接收 uid 作为第一个参数,并接收一个带有用户声明 OR null 的对象作为第二个参数。

    您的错误的解决方案很可能是调用setCustomUserClaims(user.uid, null) 而不是setCustomUserClaims(user.uid, { claim: null })。请注意,这将覆盖用户的所有现有声明。

    如果您想保留用户的其他声明,请先获取声明,然后使用更新的自定义声明对象调用 setCustomUserClaims

    const { customClaims: oldCustomClaims } = await admin.auth().getUser(user.uid)
    
    const updatedCustomClaims = oldCustomClaims
    
    delete updatedCustomClaims.admin
    
    admin.auth().setCustomUserClaims(user.uid, updatedCustomClaims)
    
    

    见:https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth-1#setcustomuserclaims


    从 Firebase 云函数中获取更有用的错误消息

    不要像在云函数中那样简单地返回错误,而是使用 HttpsError 构造函数。

    return new HttpsError("internal", error.message);
    

    这会将错误与错误消息一起正确地传递给客户端。

    【讨论】:

      猜你喜欢
      • 2020-01-07
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 2015-03-02
      • 2021-03-25
      • 2011-07-27
      相关资源
      最近更新 更多