我有一个内置了firebase和angular的应用程序,我希望能够在刷新页面后保持用户登录。现在我有一个登录屏幕,其中有两个基本的输入字段绑定到一个控制器
this.email = "";
this.pass = "";
this.emessage = "";
this.loginUser = function() {
ref.authWithPassword({
email: this.email,
password: this.pass
}, function(error, authData) {
if (error) {
console.log("Login Failed!", error);
this.emessage = error.message;
$scope.$apply();
} else {
dataStorage.uid = authData.uid;
$location.path('/projects');
$scope.$apply();
}
}.bind(this));
}
这一切都很好,很好用,但是当用户刷新页面时,他们又退出了。有没有什么办法,当控制器加载时,看看用户是否已经登录并自动重定向?谢谢!
6条答案
按热度按时间q43xntqr1#
现在的代码处理用户登录的情况,要处理用户已经登录的情况,可以使用
onAuthStateChanged
方法:通常,您只希望在此函数的else中显示登录按钮。
在较新的(v9及更高版本)模块化SDK中,这将是:
另请参阅firebase.auth.Auth和获取当前登录用户的文档。
z3yyvxxp2#
就像评论中提到的,接受的答案不再起作用了。目前检查用户是否登录的方法是
(from https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged)
enxuqcxy3#
我的web应用程序中有一些公共页面带有受保护的功能,这是我面临的一个挑战。使用下面的代码,用户总是在其他操作之前通过Firebase SDK加载(如果已登录)。但如果页面需要身份验证,用户也会被重定向到登录页面。这在页面重载时效果很好。
jpfvwuh44#
对于任何ReactJS用户,这里有一个简单的Hook,它是我根据这个线程中提供的答案创建的,如果当前用户没有登录,它会将用户重定向到登录路径。
您只需要导入这个钩子,并在任何您不想呈现的组件中运行,除非用户登录。
示例:
pcww981p5#
如果您使用的是Angular 4,则可以使用AngularFire2-官方Firebase集成。
我有一个 Package AngularFire 2的AuthService。我只是在Service的构造函数中检索AuthSession,并在需要时使用它。示例:
完整身份验证服务代码here Full Angular 4,带有Firebase示例here
zlhcx6iw6#
其他选项会话存储
参见此处:
Angular Firebase auth, how to check if user is logged in to hide login link from navigation?