reactjs - 监控 Firebase 身份验证对象属性更改?
问题描述
我已经使用 Firebase Auth 和 Firestore 通过自己的电子邮件验证流程来实现,因为我需要使用自定义电子邮件模板。客户端,UI 是用 React 完成的。
过程如下:
1)用户注册,我打电话firebase.auth().createUserWithEmailAndPassword()
2) My Cloud Function 侦听何时使用functions.auth.user().onCreate()
. 它使用其 UID 作为文档 ID 在 Firestore 中生成一条记录,并设置令牌和创建时间。
3) 用户单击电子邮件中的激活链接,加载 UI 视图,该视图调用验证令牌的云功能。验证后,它会为用户更新 auth 对象:
admin.auth().updateUser(uid, {
emailVerified: true
});
4) 在我调用该函数的 UI 中,我等待响应,然后将它们发送到他们可以选择计划的页面
async function actionCode() {
try {
await firebase.functions().httpsCallable('verifyToken')({
token: match.params.token
});
history.push('/select-plan');
} catch (e) {
setAlert({
message: "Error",
description: e.message,
type: "error"
});
setLoading(false);
}
}
我遇到的问题在我的应用程序中,我根据firebase.auth().currentUser
对象进行路由。例如(删除了一些代码..)
function App() {
const [loggedIn, setLoggedIn] = useState(false);
const [user, setUser] = useState(null);
useEffect(() => {
if(firebase.auth().currentUser) setLoggedIn(true);
return firebase.auth().onAuthStateChanged(function(user) {
if (user) {
setUser(user);
setLoggedIn(true);
setLoading(false);
} else {
setLoggedIn(false);
setUser(null);
setLoading(false);
}
});
});
if(loading) return <div></div>
if(!loggedIn) {
return authWrapper(
<Switch>
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
<Redirect to="/login" />
</Switch>
);
}
if(!user.emailVerified) {
return authWrapper(
<Switch>
<Route path="/register-success" component={RegisterSuccess} />
<Route path="/activate-account/:token" component={ActivateAccount} />
<Redirect to="/register-success" />
</Switch>
);
}
return authWrapper(
<div>
Logged In etc
</div>
);
}
我遇到的问题是,当您更改 auth 对象时,它不会反映在 currentUser 对象中,该onAuthStateChanged
函数也没有更新的属性。仅当您重新加载整个应用程序时才会发生这种情况。
有谁知道我可以在这里进步的方式。由于 currentUser 对象没有更新,我的路由中断,用户在重新加载应用程序之前无法继续前进。
解决方案
将电子邮件地址设置为已验证是纯服务器端操作。它不会自动通知客户端用户配置文件已更新。因此,客户端仅在刷新其令牌时才会获取更改,无论是在您重新启动应用程序时,还是在令牌自动刷新时(每小时发生一次)。
如果您想更快地获取更新的属性,您可以通过调用强制刷新令牌User.reload()
。有几种常见的方法可以做到这一点:
- 在您等待验证电子邮件地址时,在您的应用程序中定期调用它。
- 在您的应用程序中有一个按钮,用户单击该按钮以刷新令牌,例如I verified my email address.
- 当应用程序回到前台时,通常用户会通过另一个应用程序中的操作来验证电子邮件地址。
- 通过在验证电子邮件地址后从您的服务器向应用程序发送通知。您可以为此使用 FCM 数据消息,或任何其他客户端到服务器的推送机制。
推荐阅读
- azure - 队列触发的 Azure 函数并不总是记录
- css - 在侧边栏显示目录
- python - Django [Errno 2] 写入日志文件时没有这样的文件或目录
- gem5 - 有没有办法确定 gem5 run 是否成功通过?
- tensorflow - 似乎无法让 tensorflow 的“tflearn.objectives.roc_auc_score (y_pred, y_true)”工作
- python-3.x - 如何在字典列表中只运行 1 个函数?
- c++ - 使用变体类型列表调用 std::function
- lazarus - TIdIPWatch 返回空白 IP(与 TIdStack 一样)
- css - 我的 css 代码中不断出现解析错误。它出什么问题了?
- python - 如何在 Python 中应用正则表达式替换?