javascript - Firebase - 在 localStorage 对象有效时保持用户登录
问题描述
我有一个使用 Ionic、Angular2 和 Firebase 构建的应用程序。
我目前正在做的是,当用户登录或注册时,他们的auth.currentUser
信息将保存在localStorage
. 我的代码当前假设如果用户user
在 set 中设置了该用户也已登录的变量localStorage
。但是,我刚刚意识到事实并非如此。
我的localStorage
变量user
如下所示:
我得到它是这样的:
ngOnInit() {
Promise.all([ //data storage get all..
this.storage.get('user')
])
.then(([user]) => {
this.userData = user; //set the user storage to this.userData
console.log(this.userData)
})
.catch(error => {
console.log("Storage Error.");
});
}
所以我拥有所有用户信息,除了他们实际上没有登录的事实......所以当我这样做时:
this.afAuth.auth.onAuthStateChanged((user) => {
if (user) {
console.log(user)
} else {
console.log("Not logged in")
}
});
它显示用户未登录。当我拥有 localStorage 信息时,我是否可以让用户保持登录状态?
或者,除非用户退出,否则可能只是让登录状态始终处于登录状态?与它永不过期?
此时我该怎么办?任何建议都会很棒!谢谢你。
解决方案
Firebase 经理用户以不同的方式。您不应该依赖 localstorage 来检测用户是否登录它。您应该依靠 firebase 来检查用户是否已登录。由于 firebase 是建立在 web 套接字上的,因此它应该非常快。所以让我们重写ngOnInit
如下:
ngOnInit() {
const user = this.afAuth.auth.currentUser;
if (user) {
this.userData = user;
} else {
// force them to reauthenticate
user.reauthenticateWithCredential(credential)
.then(function() {
// User re-authenticated.
this.userData = this.afAuth.auth.currentUser;
}).catch(function(error) {
// An error happened.
});
}
}
在此处阅读有关在 Firebase 中管理用户的更多信息:https ://firebase.google.com/docs/auth/web/manage-users 。希望这可以帮助。
推荐阅读
- python - 分配给二维列表
- javascript - 无法使用 angularjs 从 json 获取特定 ID 的计数
- c# - .NET 的 X509Store 可以用来从远程 Linux 商店获取证书吗?
- r - 在R中:函数生成从查找表填充并由另一个列表排序的命名数字列表
- javafx-8 - JavaFX RadioButton setSelected()不起作用
- javascript - 如果从SVG 内的脚本标签中的javascript 应用,Chrome 不会呈现旋转
- git - 为什么`git不合并
--squash` 提交? - angular - 使用 TestBed 进行单元测试(?)一个 Angular 6 组件
- python - 从批处理文件 FileNotFoundError 运行 Python 脚本时出错:[Errno 2] 没有这样的文件或目录:'[]'
- c# - WinForms - 使用 alt+shift 列选择实现文本控件