Javascript 如何使用firebase在react中创建管理状态?

Javascript 如何使用firebase在react中创建管理状态?,javascript,reactjs,firebase,google-cloud-firestore,material-ui,Javascript,Reactjs,Firebase,Google Cloud Firestore,Material Ui,我的web应用程序通过firebase使用身份验证。我有一个appbar,它根据用户是否登录显示按钮。如果用户是管理员,我想在appbar上显示另一个按钮。我想知道是否有可能使用用户的uid使他们成为管理员。下面是到目前为止我的代码 import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles';

我的web应用程序通过firebase使用身份验证。我有一个appbar,它根据用户是否登录显示按钮。如果用户是管理员,我想在appbar上显示另一个按钮。我想知道是否有可能使用用户的uid使他们成为管理员。下面是到目前为止我的代码

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import logIn from '../../auth/login.js'
import logOut from '../../auth/logout.js'
import { Link } from 'react-router-dom'
import profilePage from '../pages/profilePage'
import homePage from '../pages/homePage'
import requestService from '../pages/requestService'
import requestedServices from '../pages/requestedServices'
import { Route } from 'react-router-dom';
import firebase, { auth, provider } from '../../config/firebaseConfig.js'



// All the following keys are optional.
// We try our best to provide a great default value.
const theme = createMuiTheme({
  typography: {
  useNextVariants: true,
  },
  palette: {
    primary: {
      main : '#196f3d'
    },
    secondary: {
      main : '#f7f9f9'
    },
    // error: will use the default color
  },
});

const styles = {
  root: {
    flexGrow: 1,
  },
  grow: {
    flexGrow: 1,
  },

};

class ButtonAppBar extends Component {
  static defaultProps = {
    classes: PropTypes.object.isRequired,
  };

  state = { isLoggedIn : false }
  state = { isAdmin : false }
  componentDidMount = () => {
    firebase.auth().onAuthStateChanged(user => {
      this.setState({ isLoggedIn: !!user })
      this.setState({ isAdmin : firebase.auth().user.uid='8uhMGWgWZENwT7S2YFECOlSFrHD2'})
      console.log("user", user)
    })

  }


  render()  {
    const { classes } = this.props;
    return (
      <MuiThemeProvider theme={theme}>
      <div className={classes.root}>
        <AppBar position="static" color='primary' >
          <Toolbar>
          <Typography variant="h5" color="secondary" className={classes.grow}>
              Greene Dog Walking
            </Typography>
            {this.state.isAdmin ? (
              <div>
              <Link to={'./requestedservices'}>
                <Button color="secondary">Requested Services</Button>
              </Link>
              </div>
            ) : (


            ) }


            {this.state.isLoggedIn ? (
              <div>
              <Link to={'./'}>
                <Button color="secondary">Home</Button>
              </Link>
              <Link to={'./service'}>
                <Button color="secondary">Request Service</Button>
              </Link>
              <Link to={'./requestedservices'}>
                <Button color="secondary">Requested Services</Button>
              </Link>
              <Link to={'./profile'}>
                <Button color="secondary">Profile</Button>
              </Link>
              <Button onClick={logOut} color="secondary">Logout</Button>
              </div>
              ) : (
              <div>
              <Link to={'./'}>
                <Button color="secondary">Home</Button>
              </Link>
              <Button onClick={logIn} color="secondary">Login</Button>
              </div>
            )  }
          </Toolbar>
        </AppBar>
      </div>
      </MuiThemeProvider>
    );
  }
}

export default withStyles(styles)(ButtonAppBar);
import React,{Component}来自'React';
从“道具类型”导入道具类型;
从“@material ui/core/styles”导入{withStyles}”;
从'@material ui/core/styles'导入{MuiThemeProvider,createMuiTheme};
从“@material ui/core/AppBar”导入AppBar;
从“@material ui/core/Toolbar”导入工具栏;
从“@material ui/core/Typography”导入排版;
从“@material ui/core/Button”导入按钮;
从“../../auth/logIn.js”导入登录名
从“../../auth/logOut.js”导入注销
从“react router dom”导入{Link}
从“../pages/profilePage”导入profilePage
从“../pages/homePage”导入主页
从“../pages/requestService”导入requestService
从“../pages/requestedServices”导入requestedServices
从'react router dom'导入{Route};
从“../../config/firebaseConfig.js”导入firebase,{auth,provider}
//以下所有键都是可选的。
//我们尽力提供一个很好的默认值。
const theme=createMuiTheme({
排版:{
useNextVariants:正确,
},
调色板:{
主要:{
主要内容:“#196f3d”
},
中学:{
主要名称:“#f7f9f9”
},
//错误:将使用默认颜色
},
});
常量样式={
根目录:{
flexGrow:1,
},
成长:{
flexGrow:1,
},
};
类ButtonAppBar扩展组件{
静态defaultProps={
类:PropTypes.object.isRequired,
};
state={isLoggedIn:false}
状态={isAdmin:false}
componentDidMount=()=>{
firebase.auth().onAuthStateChanged(用户=>{
this.setState({isLoggedIn:!!user})
this.setState({isAdmin:firebase.auth().user.uid='8uhmgwgwzenwt7s2yfecolsrhd2'})
console.log(“用户”,用户)
})
}
render(){
const{classes}=this.props;
返回(
格林遛狗
{this.state.isAdmin(
请求的服务
) : (
) }
{this.state.isLoggedIn(
家
请求服务
请求的服务
轮廓
注销
) : (
家
登录
)  }
);
}
}
导出默认样式(样式)(按钮栏);

如果应用程序只有一名管理员,我认为您的代码是正确的,但是在firebase中存储用户角色而不是决定应用程序中的管理员状态不是更好吗

用户实体具有角色属性,因此您可以通过检查角色属性来确定他/她是管理员

this.setState({ isAdmin : firebase.auth().role='admin'})

正如Eric指出的,如果您有一个用户是管理员,那么这种方法是有效的,但请记住它是不安全的。如果有人能拆开这个应用程序,他们就能找到代码并轻松绕过它。如果你的目的只是为了更好的用户体验而隐藏一个标签,那么这就行了

相反,我建议通过自定义声明控制访问。我做了一个视频,你可以看看。还有一个,一个,还有一个

指南中的一个示例可以让您了解JS中的情况:

firebase.auth().currentUser.getIdTokenResult()
  .then((idTokenResult) => {
     // Confirm the user is an Admin.
     if (!!idTokenResult.claims.admin) {
       // Show admin UI.
       showAdminUI();
     } else {
       // Show regular user UI.
       showRegularUI();
     }
  })
  .catch((error) => {
    console.log(error);
  });

firebase.auth()的
role
属性不存在。实现比这要复杂一些。很抱歉,我很久以前就根据我的项目回答了您的问题。在我再次阅读文档之后,我意识到问题并不是那么简单,但是您可以向用户实体添加新属性