首页 > 解决方案 > 在 Firebase 身份验证 NodeJS 中使用电子邮件和密码进行重定向

问题描述

我想使用已在我的 Firebase 身份验证中注册的电子邮件admin@gmail.com登录。

所以我写了登录验证,如果firebase Auth满足电子邮件和密码,它将登录。

const handleLogin = (e) => { 
e.preventDefault(); 
fire.auth()
  .signInWithEmailAndPassword(email, password)
  .then(() => { router.push("/") })
.catch((err) => {
    const message = err.message
    toast({
      title: "An error occured",
      position: "bottom-right",
      description: message,
      status: "error",
      duration: 2000,
      isClosable: true,
    })
  })
setEmail('')
setPassword('')
}

之后,我尝试通过使用我唯一的管理员电子邮件admin@gmail.com来修改它,以便在成功登录到 /admin 目录后重定向页面,否则如果用户不是管理员将重定向到“/”或“ /指数”

这是我修改后的代码

const handleLogin = (e) => { 
e.preventDefault(); 
fire.auth()
  .signInWithEmailAndPassword(email, password)
  .then(() => { 
   fire.firestore().collection("user").where("email","==","admin@gmail.com")
    .get()
    .then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        if (doc.email === 'admin@gmail.com') {
          router.push("/admin")
        } else {
          router.push("/")
        }
      })
})
.catch((err) => {
    const message = err.message
    toast({
      title: "An error occured",
      position: "bottom-right",
      description: message,
      status: "error",
      duration: 2000,
      isClosable: true,
    })
  })
setEmail('')
setPassword('')
}

我无法解决这个问题,因为我对此很陌生,并且一直在寻找答案。我只想这样做,只有一个管理员来控制 Web 应用程序,并且有很多用户会使用它。

标签: node.jsfirebasefirebase-authentication

解决方案


除了这一行之外,第二个示例中的代码看起来应该可以工作

if (doc.email === 'admin@gmail.com') {

应该是

if (doc.data().email === 'admin@gmail.com') {

然后您可以将 where 子句设置为

where("email","==",email)

并且您的代码应该按预期工作。


推荐阅读