I'm using a simple custom authentication with angularfire2 and the authentication service from Firebase.
import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';
import { Cookie } from 'ng2-cookies';
@Injectable()
export class GlobalMenuService {
loggedIn: boolean = false;
constructor(private af: AngularFire) { }
login(email: string, password: string) {
this.af.auth.login({
email: email,
password: password
})
.then((success) => {
this.loggedIn = true;
});
}
logout() {
this.af.auth.logout();
this.loggedIn = false;
}
}
Is there a way to save some data in a cookie (token, uid, email or something) to restore the session, i.e. each time the user returns to the app re-login him without him having to write the credentials ?
You should use auth.subscribe(). This function will be called any time there's a change in the authentication state.
this.af.auth.subscribe(user => {
if (user) {
// User is signed in.
... do other stuff
} else {
// No user is signed in.
... do other stuff
}
});
If you are already logged in when you open your app, or you call signInWithEmailAndPassword, this function will be called and auth will contain your logged user data.
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