我有一个内置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));
}
这一切都很好,花花公子它可以工作,但是当用户刷新页面时,它们会被退回。有没有办法在控制器加载时查看用户是否已登录并自动重定向?谢谢!
答案 0 :(得分:18)
您现在拥有的代码处理用户登录的情况。要处理用户已记录的情况,请监视身份验证状态。来自Firebase documentation on monitoring auth state:
// Create a callback which logs the current auth state
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
} else {
console.log("User is logged out");
}
});
通常,您只想在此功能的else
中显示登录按钮。
答案 1 :(得分:2)
对于任何ReactJS用户,这是我根据此线程中提供的答案创建的一个简单的Hook,如果当前用户未登录,它将重定向用户到登录路由。
import { useEffect } from 'react';
import * as firebase from 'firebase';
import { useHistory } from 'react-router-dom';
export default function useProtectedRoute() {
const history = useHistory();
useEffect(() => {
firebase.auth().onAuthStateChanged(function(user) {
if (!user) {
console.error(
'Access to protected route denied, redirecting to login...'
);
history.push('/auth/login');
}
});
}, [history]);
}
您只需要导入此钩子并在您不希望呈现的任何组件中运行,除非用户已登录。
示例:
import React from 'react';
import useProtectedRoute from 'hooks/useProtectedRoute';
export default function UserDetailsComponent() {
useProtectedRoute();
return <div>This is only visible when user is logged in</div>;
}
答案 2 :(得分:1)
如评论中所述,已接受的答案不再起作用。当前检查用户是否已登录的方法是
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
}
});
(来自https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged)
答案 3 :(得分:0)
如果您使用的是Angular 4,则可以使用AngularFire2 - 官方Firebase集成。
我有一个包装AngularFire2的AuthService。我只是在Service的构造函数中检索AuthSession并在需要时使用它。例如:
@Injectable()
export class AuthenticationService {
private authState: any;
constructor(public afAuth: AngularFireAuth) {
this.afAuth.authState.subscribe((auth) => {
this.authState = auth
});
}
get user(): any {
return this.authenticated ? this.authState : null;
}
}
答案 4 :(得分:0)
我面临的挑战是我的Web应用程序具有带有受保护功能的公共页面。使用以下代码,始终总是先通过Firebase SDK加载用户(如果已登录)。但是,如果该页面需要身份验证,也会重定向到登录页面。可以在页面重新加载时正常工作。
Deterministic
答案 5 :(得分:0)
其他选项 sessionStorage
查看此处:
Angular Firebase auth, how to check if user is logged in to hide login link from navigation?