I have a working authentication using the angularfire2, I am just wondering if there is another way to check if the user is authenticated after the user recently logged in w/o hitting the server? The way I do this is like this
isAuthenticated():boolean{
this.af.auth.subscribe(data => {
if(data ){
// User is authenticated
return true;
}
});
}
Any help is appreciated
Edit 1:
I decided to still use the original code to check if the user is recently logged in. What @cartant suggested is good enough when you are not checking the user at the start up of your application because it might return null as stated in the firebase official docs. The way I used it here is that I have menu items that should only be shown to authenticated users and using firebase.auth().currentUser
will always return null on the initial load of the page.
Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.
Note that Firebase Auth web sessions are single host origin and will be persisted for a single domain only. Indicates that the state will only persist in the current session or tab, and will be cleared when the tab or window in which the user authenticated is closed.
The AngularFireAuth object has a method that allows you to easily create users within your application. In the grocery list app, I did the following: createUser(email: string, password: string) { this.afAuth.auth.createUserWithEmailAndPassword(email, password)
You can use the prebuilt Route users with AngularFire guards
AngularFireAuthGuard provides a prebuilt canActivate Router Guard using AngularFireAuth.
You can customize the behavior of this AngularFireAuthGuard by passing an RXJS pipe through the route data's authGuardPipe. You can learn more here.
AngularFire2 is currently undergoing some refactoring and significant portions of its authentication API are going to be removed in favour of using the Firebase Web API in conjunction with AngularFire2. There is more information in this issue.
The observable that you have used will remain in AngularFire2 and you can subscribe to it to receive notifications of changes in the authentication state.
However, if all you are interested in is determining whether or not there is a currently authenticated user, there is a currentUser
property in the Firebase Web API that will tell you that:
import * as firebase from "firebase";
...
console.log(firebase.auth().currentUser);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With