是否可以通过Axios请求实现onAuthStateChanged()



我目前正在做大学最后一年的项目,它正在使用FERN堆栈和Ionic创建一个显示温度信息的应用程序。我面临的问题是,当我刷新浏览器时,它会将用户注销。

是否可以通过Axios Request将用户身份验证状态更改为onAuthStateChanged((来实现一种检查方法,或者我应该只导入firebase admin,以便在Ionic应用程序中使用身份验证功能?

我已经使用Auth作为API温度请求的中间件,所以我几乎要实现Auth模块两次,但如果它可以更容易地使用onAuthStateChanged((函数,我不介意以这种方式实现它。我还在应用程序的后端执行登录功能和注册功能。

截至目前,我将用户登录并存储一个令牌:

const handleLogin = async () => {
await axios.post('http://localhost:3000/login', {
email: email,
password: password
}).then(res => {
localStorage.setItem('Token', `Bearer ${res.data.token}`);
console.log(res);
onLogin();
}).catch(err => {
console.log(err);
});
}

这是我的loginUser函数,它发回令牌:

exports.loginUser = (req, res) => {
const user = {
email: req.body.email,
password: req.body.password
}
const { valid, errors } = validateLoginData(user);
if (!valid) return res.status(400).json(errors);
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
return data.user.getIdToken();
})
.then((token) => {
return res.json({ token });
})
.catch((error) => {
console.error(error);
return res.status(403).json({ message: 'Invalid email or password.  Please try again'});
})
};

在我的代码中实现onAuthStateChanged((函数的最佳方式是什么?我在一个教程中看到,当他们将用户登录时,会使用IndexedDB来存储authUser密钥和值。我的代码不存储这些信息,只存储令牌。

用户身份验证状态是由Firebase SDK定义和实现的一种机制。您正在调用REST API,这意味着您没有使用Firebase SDK,因此没有身份验证状态更改通知机制。

当然,您可以实现自己的机制,其中包括跟踪ID令牌何时过期,在此之前自动续订,注册侦听器,通知这些侦听器,以及我现在可能忽略的一些事情。

不过,您将重新实现Firebase SDK的重要部分。因此,在这一点上,首先考虑一下为什么不使用Firebase SDK。

相关内容

  • 没有找到相关文章

最新更新