简体   繁体   中英

Firebase auth is not detecting logged in user

The problem: I cannot access the user object with firebase.auth().currentUser

The situation: Account creation and login uses firebaseui-web . User is redirected to his account specific pages upon authentication. User cookie is validated server side before each page is rendered and served to authenticated user, ensuring that the right user content is served and that no unauthorized access occurs. However, when accessing the user profile page where I need to access the user object using javascript, I only get a null object. Futhermore, the console logs "user is NOT signed in" and logs "null" for the user.

The question: How can I access the user object? Am I loading something out of sequence? Is there anything else I need to check or double check?

The html page:

<!doctype html>
<html class="no-js h-100" lang="en">
  <head>
    <!-- redacted -->  
    <link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" id="main-stylesheet" data-version="1.1.0" href="/static/dashboard/styles/shards-dashboards.1.1.0.min.css">
    <link rel="stylesheet" href="/static/dashboard/styles/extras.1.1.0.min.css">
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/quill/1.3.6/quill.snow.css"> 
</head>

  <body class="h-100">
    <div class="container">
        <!-- The page content goes here-->
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
    <script src="https://unpkg.com/shards-ui@latest/dist/js/shards.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sharrre/2.0.1/jquery.sharrre.min.js"></script>
    <script src="/static/dashboard/scripts/extras.1.1.0.min.js"></script>
    <script src="/static/dashboard/scripts/shards-dashboards.1.1.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/quill/1.3.6/quill.min.js"></script>
    <script src="/static/dashboard/scripts/app/app-blog-new-post.1.1.0.js"></script>

    <!-- toastr -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>

    
    <script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-analytics.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-auth.js"></script>


    <script>
        // Your web app's Firebase configuration
        var firebaseConfig = {
          apiKey: "MyApiKey",
          authDomain: "MyAuthDomain",
          databaseURL: "myDatabaseURL",
          projectId: "myProjectId",
          storageBucket: "myStorageBucket",
          messagingSenderId: "myMessagingSenderId",
          appId: "myAppId"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
      </script>

    <script>

      $(document).ready(function(){
        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            // User is signed in.
            console.log("user is signed in");
          } else {
            // No user is signed in.
            // The user gets 
            console.log("user is NOT signed in");
          }
        });
        var user = firebase.auth().currentUser;

        console.log(user);
        //logs 'null'

        // additional code redacted
      })
    </script>

  </body>
</html>

You have a race going on. You put both firebase scripts in the body. The second is listening for document ready , which may be triggering before you're connected to the firebase.auth() .

I would put both inside the listener, or connect via script in the <head> , or put them in the <head> under one <script> tag and create a read flag.

Try this (still waiting for doc ready):

<body>
<script>
      $(document).ready(function(){

        // Your web app's Firebase configuration
        var firebaseConfig = {
          apiKey: "MyApiKey",
          authDomain: "MyAuthDomain",
          databaseURL: "myDatabaseURL",
          projectId: "myProjectId",
          storageBucket: "myStorageBucket",
          messagingSenderId: "myMessagingSenderId",
          appId: "myAppId"
        };

        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);

        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            // User is signed in.
            console.log("user is signed in");
          } else {
            // No user is signed in.
            // The user gets 
            console.log("user is NOT signed in");
          }
        });
        var user = firebase.auth().currentUser;

        console.log(user);
        //logs 'null'

        // additional code redacted
      })
</script>

Or this (connect to firebase before writing to DOM):

<head>
<script>
      $(document).ready(function(){

        // Your web app's Firebase configuration
        var firebaseConfig = {
          apiKey: "MyApiKey",
          authDomain: "MyAuthDomain",
          databaseURL: "myDatabaseURL",
          projectId: "myProjectId",
          storageBucket: "myStorageBucket",
          messagingSenderId: "myMessagingSenderId",
          appId: "myAppId"
        };

        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
</script>
</head>

<body>
<script>
        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            // User is signed in.
            console.log("user is signed in");
          } else {
            // No user is signed in.
            // The user gets 
            console.log("user is NOT signed in");
          }
        });
        var user = firebase.auth().currentUser;

        console.log(user);
        //logs 'null'

        // additional code redacted
      })
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM