簡體   English   中英

如何僅允許類型為 admin 的用戶使用 firestore 數據庫登錄我的 React 網站

[英]How to allow only users of type admin to login in my react website using firestore database

我想創建一個只有管理員類型的用戶才能訪問的登錄頁面。 我的用戶集合中有一個名為級別的字段,如果級別等於管理員,則用戶應該能夠登錄,否則他們不能登錄。

到目前為止,這是我嘗試過的方法,但無法正常工作。

有沒有更好的方法來實現我的要求,或者我的方法可以改進以正常工作嗎? 如何使用 firestore 查詢和驗證管理員用戶?

const Login = () => {
  const navigate = useNavigate();
  const [adminEmail,setAdminEmail] = useState("")
  const [adminPassword,setAdminPassword] = useState("")
  const [adminFBEmail,setAdminFBEmail] = useState("")
  const [adminFBPassword,setAdminFBPassword] = useState("")
 
  useEffect(() => {
    firebase.firestore().collection("Users").get().then((adminSnapshot) => {

      adminSnapshot.forEach((doc) => {
        if(doc.data().level != "admin"){
          alert("not admin")
        }else{
          setAdminFBEmail(doc.data().email)
          setAdminFBPassword(doc.data().password)
        }
      
    })
  })
},[]);

const handleSubmit = () => {
    if(adminEmail == adminFBEmail && adminPassword == adminFBPassword){
      alert("Admin logged in")
      navigate('/app/dashboard', { replace: true });
    }else{
      alert("error")
    }
  }


return (
    <>
      <Helmet>
        <title>Login | Power Cargo</title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
          justifyContent: 'center'
        }}
      >
        <Container maxWidth="sm">
          <Formik
            initialValues={{
              email: '',
              password: ''
            }}
            validationSchema={Yup.object().shape({
              email: Yup.string().email('Must be a valid email').max(255).required('Email is required'),
              password: Yup.string().max(255).required('Password is required')
            })}
            onSubmit={() => {
             
            }}
          >
            {({
              errors,
              handleBlur,
              handleChange,
            
              isSubmitting,
              touched,
              values
            }) => (
              <form onSubmit={handleSubmit} >
                <Box sx={{ mb: 3 }}>
                  <Typography
                    color="textPrimary"
                    variant="h2"
                  >
                    Sign on the internal platform
                  </Typography>
                </Box>
                <TextField
                  error={Boolean(touched.email && errors.email)}
                  fullWidth
                  helperText={touched.email && errors.email}
                  label="Email Address"
                  margin="normal"
                  name="email"
                  onBlur={handleBlur}
                  onChange={(e)=> {
                    setAdminEmail(e.target.value)}}
                  type="email"
                
                  variant="outlined"
                />
                <TextField
                  error={Boolean(touched.password && errors.password)}
                  fullWidth
                  helperText={touched.password && errors.password}
                  label="Password"
                  margin="normal"
                  name="password"
                  onBlur={handleBlur}
                  onChange={(e)=> {
                    setAdminPassword(e.target.value)}}
                  type="password"
                  variant="outlined"
                />
                <Box sx={{ py: 2 }}>
                  <Button
                    color="primary"
                    disabled={isSubmitting}
                    fullWidth
                    size="large"
                    type="submit"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    Sign in now
                  </Button>
                </Box>
              </form>
            )}
          </Formik>
        </Container>
      </Box>
    </>
  );
}

請不要實施您自己的電子郵件+密碼檢查,因為有數十個(如果不是數百個)陷阱,如果您以前從未這樣做過,您很可能會遇到其中的許多陷阱。 而是為此使用專用的提供程序 - 例如Firebase Authentication中的提供程序。

然后,您仍然可以在 Firestore 數據庫中存儲關於哪個用戶是管理員的信息,但您可以通過將用戶 ID(來自 Firebase 身份驗證的 UID)與數據庫中的角色相關聯來實現。 有關此類系統的更多信息,請參閱之前關於該主題的一些問題:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM