0
votes

I am developing a web application using php and codeigniter and firebase for realtime database.

In my codeigniter views I am using javascript code to manage firebase authentication.

following code I am using to manage firebase sign in with email.

 function login(){

  var userEmail = "[email protected]" ;
  var userPass = "password";

  const fr = firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
    // Handle Errors here.
    console.log("got error");
    var errorCode = error.code;
    var errorMessage = error.message;

    window.alert("Error : " + errorMessage);

    // ...
  });

I have implemented Firebase AuthStateChangeListner when I call login() I am getting user object in following function.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    console.log("signin");
    console.log(user);
  } else {
    // No user is signed in.
    console.log("no sign");
  }
});

On page load I am calling a login function get successful user object.

$(function(){
    login();
});

The issue is now if I move to another page and try to access the current user object like this then I am getting a null.

var user = firebase.auth().currentUser;

how I can manage firebase login session across multiple page redirections?

1

1 Answers

0
votes

To get the current user, always use a state change listener. This is because getting the user profile may take a roundtrip to the server, and thus happens asynchronously.

So in the new page, just use the same code as you had before:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    console.log(user);
  } else {
    console.log("not signed in");
  }
});