首页 > 解决方案 > Firebase 多种管理员类型

问题描述

在我正在开发的产品中(使用 ReactJS 和 Firebase Auth 和 Firestore),我需要设置以下帐户类型:

超级管理员
内容管理员
用户管理员

目前,我有一个表单,一旦输入用户电子邮件,它就会向具有该电子邮件地址的用户提供“管理员”令牌。

我可以用 3 种不同的管理员类型做到这一点的最佳方式是什么?

我已经包含了设置管理员令牌的代码。

AddAdmin.js

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

class AddAdmin extends Component {
    state = {
      superAdminEmail: ''
    }
  
    updateAdminEmail = (e) => {
      this.setState({
        adminEmail: e.target.value
      })
    }
  
    addAdmin = (e) => {
      e.preventDefault();
      const addAdminRole = firebase.functions().httpsCallable('addAdminRole');
      addAdminRole({email: this.state.adminEmail})
        .then(result => {
          console.log(result);
          })
    }
  
    render() {
      return (
          <div className = "AddAdminForm">
              <form className = "admin-actions" onSubmit={this.addAdmin}>
                  <input type = "email" placeholder = "User email" id = "admin-email" value={this.state.adminEmail} onChange={this.updateAdminEmail} required/>
                  <button type="submit"> Make Admin </button>
              </form>
          </div>
        
      )
    }
  }
export default AddAdmin

索引.js

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.addAdminRole = functions.https.onCall((data, context) => {
  // get user and add admin custom claim
  return admin.auth().getUserByEmail(data.email).then(user => {
    return admin.auth().setCustomUserClaims(user.uid, {
      admin: true
    })
  }).then(() => {
    return {
      message: `Success! ${data.email} has been made an admin.`
    }
  }).catch(err => {
    return err;
  });
});

标签: reactjsfirebasefirebase-authenticationgoogle-cloud-functionsfirebase-admin

解决方案


一种方法是通过引入单选按钮来选择角色来扩展您的逻辑,然后在提交时,它将在表单提交时调用特定的处理程序(addAdmin / addSuperAdmin / addContextAdmin)。

如果选择了 User Admin 的无线电 btn,则调用addAdmin后者又调用addAdminRole云函数。

类似地,您可以引入其他两个云函数(在 index.js 中)->addSuperAdminRoleaddContextAdminRole.

然后根据选中的单选按钮调用相关的处理程序。


推荐阅读