【问题标题】:Firebase Multiple Admin TypesFirebase 多种管理员类型
【发布时间】:2021-02-04 10:35:54
【问题描述】:

在我正在开发的产品中(使用 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

Index.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;
  });
});

【问题讨论】:

  • 您可能对此article 感兴趣,它展示了如何创建管理模块来管理 Firebase 用户的访问权限和角色。
  • 您的代码让任何人只需调用该函数即可为其分配管理状态。它不安全。
  • @DougStevenson 感谢您提供的信息,我的专长是前端,这是我第一次处理后端事务。你会如何建议我让它更安全?

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


【解决方案1】:

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

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

同样,你可以引入其他两个云函数(在 index.js 中)-> addSuperAdminRoleaddContextAdminRole

然后根据选中的单选按钮调用相关的handler。

【讨论】:

  • 非常感谢您的帮助。明天我会试一试,然后回复你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 2018-01-13
  • 1970-01-01
  • 2019-01-19
  • 2017-07-03
  • 2017-09-23
  • 2019-03-14
相关资源
最近更新 更多