Currently, I am working on integrating Firebase with AngularFire 2 and facing an issue.
The problem arises when I try to refresh the page, as the auth instance returns null.
Below is the code snippet for my AuthService:
Everything functions correctly, but every time I reload the page, the auth becomes null which prevents me from accessing the Firebase database due to authentication rules.
export class AuthService {
private userDetails: Users = null;
private dbUsers;
public loginStatus = new BehaviorSubject(false);
public GOOGLE_OATH_SCOPES = 'email, https://www.googleapis.com/auth/drive';
constructor(
private _firebaseAuth: AngularFireAuth,
private router: Router,
private firebase: AngularFireDatabase,
private _userService: UserService
) {
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.setUserFromLocalstorage(currentUser);
_firebaseAuth.authState.subscribe(
(user) => {
console.log("Step 1", user);
if (user) {
}
else {
this.setUserFromLocalstorage(currentUser);
}
}
);
}
setUserFromLocalstorage(currentUser) {
if (currentUser && !_.isEmpty(currentUser)) {
this.userDetails = currentUser;
} else {
this.userDetails = null;
};
}
signInWithGoogle() {
var provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({
prompt: 'select_account'
});
provider.addScope(this.GOOGLE_OATH_SCOPES);
this._firebaseAuth.auth.setPersistence(firebase.auth.Auth.Persistence.NONE).then(() =>
this._firebaseAuth.auth.signInWithPopup(
provider
).then((result) => {
localStorage.setItem('accessToken', result.credential.accessToken);
})
)
}
isLoggedIn() {
if (!this.loginStatus.value) {
return false;
} else {
return true;
}
}
logout() {
this._firebaseAuth.auth.signOut()
.then((res) => {
this.router.navigate(['/'])
localStorage.clear()
this.userDetails = null;
this.loginStatus.next(false);
}
);
}
getLoggedInUser() {
return _.cloneDeep(this.userDetails);
}
setLoggedInUser(user: Users) {
this.userDetails = user;
localStorage.setItem("currentUser", JSON.stringify(user));
}
}
Concerning AngularFireAuth:
export declare class AngularFireAuth {
private zone;
readonly auth: FirebaseAuth;
readonly authState: Observable<User | null>;
readonly idToken: Observable<string | null>;
constructor(config: FirebaseOptions, name: string, platformId: Object, zone: NgZone);
}
Regarding my SignIn Method:
this._firebaseAuth.auth.setPersistence(firebase.auth.Auth.Persistence.None).then(() =>
this._firebaseAuth.auth.signInWithPopup(
provider
).then((result) => {
})
)
I am seeking a solution to overcome this issue. Any suggestions are welcomed!