Leveraging Firebase Authentication for regulating access to a website

Encountering an issue with Authentication using Firebase and JavaScript.

After following the guidelines provided at: https://firebase.google.com/docs/auth/web/password-auth everything seemed to work as expected.

My configuration is set up in a way that I have a main web page named M.html which requires authentication for access.

In addition, there's a login page called L.html which acts as a gateway to the main page.

Upon visiting the login page, users are prompted to enter credentials before proceeding. Once successfully logged in, they should be directed to the main page.

If a user tries to bypass the login page and goes directly to the main page, a check is performed to verify their login status. If logged in, access is granted; if not, they are redirected back to the login page.

The challenge arises when the main page fails to detect the user's logged-in status, consistently redirecting them back to the login page.

I am seeking assistance on the correct procedure to follow in order for the main page to recognize and acknowledge a successful login from the login page.

Despite multiple attempts to tweak the code, including exploring the use of firebase.auth().getRedirectResult().then..., the desired functionality remains elusive.

To provide clarity, simplified versions of both the main and login pages are presented below along with the respective code snippets. Hopefully, someone can identify where adjustments need to be made to achieve the intended behavior.

The M.html file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8>
<script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.7/firebase.js"></script>
</head>

<body>
<div id="mainPage"></div>

<script>
  // Initialize Firebase.
  var config = {
    apiKey: "myyKeyyy",
    authDomain: "......firebaseapp.com",
    databaseURL: "https://......firebaseio.com",
    projectId: "....",
    storageBucket: "........appspot.com",
    messagingSenderId: "........."
  },
  app = firebase.initializeApp(config);
</script>

<script>
function checkUser() {
let user = firebase.auth().currentUser;

if (user) {setMainPage();}
else {window.open("http://.../L.html",'_self');}
}


function setMainPage() {
let label = document.getElementById("mainPage");
label.innerHTML = "<h1>This is the main page!</h1><br/>";
label.innerHTML += "<h1>I can be here because I am logged in !!</h1>";
}

//setMainPage(); // This would show the contents without checking that a user is logged in.
checkUser();

</script>
</body>
</html>

The L.html file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8>
<script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.7/firebase.js"></script>
</head>

<body>
<script>
  // Initialize Firebase.
  var config = {
    apiKey: "myyKeyyy",
    authDomain: "......firebaseapp.com",
    databaseURL: "https://......firebaseio.com",
    projectId: "....",
    storageBucket: "........appspot.com",
    messagingSenderId: "........."
  },
  app = firebase.initializeApp(config);
</script>

<script>

firebase.auth().signOut().then(function() {
  // Sign-out successful.
  console.log("Sign-out successful.");

  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      // User is signed in.
      window.open("http://.../M.html",'_self');
    }
  });

}).catch(function(error) {
  // An error happened.
  console.log("Sign-out error.");
});


function LogInProcess() {
let theEmail = document.getElementById("EmlAdr").value.trim(),
thePassword = document.getElementById("PsWd").value;

firebase.auth().signInWithEmailAndPassword(theEmail,thePassword).catch(function (error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  console.log("errorCode: " + errorCode);
  console.log("errorMessage: " + errorMessage;
});
}
</script>

Email address: <input type='text' name='EmlAdr' id='EmlAdr' value=''><br/><br/>
Password: <input type='password' name='PsWd' id='PsWd' value=''><br/><br/>
<input type='button' id='LgIn' style='font-size:20px' value='Log In' onClick='LogInProcess()'><br/>

</body>
</html>

Answer №1

To ensure that the user is properly logged in and to avoid receiving incomplete auth object, it is recommended to utilize the onAuthStateChanged observer. You can refer to the most up-to-date documentation here.

Update your existing checkUser function with the following code snippet:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // Display main content
  } else {
    // Redirect to login page
  }
})

After the initialization of the firebase app is complete, this code will trigger, providing you with a user object if authentication was successful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using slideToggle() in conjunction with elements created using jQuery's append(), there is no automatic repositioning

Struggling with using slideToggle(), I'm facing an issue where the DOM elements do not get pushed down as expected; instead, they overlap. Despite trying multiple versions, I haven't been able to resolve this issue. The problem arises when creati ...

I am trying to access the serial number data from an array of objects in ReactJS. Can anyone guide me

Is there a way to extract data from an array of objects, such as getting the serial number in ReactJS? In my current code snippet, I have an array called "number" with values [1, 2, 3]. My goal is to retrieve and display these numbers as a string like th ...

Modify the main element of a component

Vue.js requires only a single root element for each component, which is typically wrapped in a div tag. However, this can lead to unexpected issues, such as breaking the layout when using Bootstrap and inserting a div between specific elements like <b-r ...

How can I trigger a row click event while a TextInput is in focus? (react-native)

Whenever I tap on a ListView item, the TouchableOpacity functions properly. However, when a TextInput is in focus, it requires two taps for it to work - the first tap only removes the focus from the TextInput. Is there a way to make it work without havin ...

Encountering NaN values in JavaScript arrays

I'm facing an issue with my HTML code that is supposed to make ball(s) bounce around the canvas. However, when I set the arrays storing the coordinates to random positions and test with alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));, it retur ...

Why is the reverse sticky navbar not visible after the position changes from fixed to static?

Scenario In the setup, I've implemented a reverse sticky navbar where it remains in position:fixed at the top. However, once the top of a specific div container touches the bottom of the navbar, I switch it to position:static using jQuery. Challenge ...

gain entry to the chart object within highcharts

Having trouble accessing the chart object in Highcharts using the AngularJS directive HIGHCHARTS-NG. var chart = $scope.chartConfig.getHighcharts(); console.log("chart", chart); Encountering an error: $scope.chartConfig.getHighcharts is not a function. ...

The issue of Nodejs Messenger broadcast message functionality being inoperative

Trying to initiate a broadcast through my Facebook Messenger bot, I have implemented the following code: if (subscribe === true) { // Initiate HTTP request to Messenger Platform request({ "uri": "https://graph.facebook.com/v2.11/me/broadcast_messa ...

tips on displaying a div dynamically in a specific location

Currently, I have implemented HTML textBoxes on my website. However, I am looking to validate these textBoxes using JavaScript. Rather than displaying a traditional alert popup for invalid data input, I would like to show a div next to the specific textBox ...

In search of an effective method for converting circular objects into string format

After some thorough research, I've encountered a plethora of broken links and explanations that were quite complex for me to follow. I am inquiring about this for a gaming application scenario, where an owner possesses an item that is also held by th ...

What is the best way to achieve maximum height?

Currently, I am attempting to obtain the total height of the page in order to apply it to the styles, specifically for the darkMask class. The reason for needing this height is that when a certain action is triggered within the header, a dark overlay is a ...

Challenge of using fullcalendar in production server compared to development machine with Javascript

<div id='calendar'></div> The html tag utilized by fullcalendar to display a calendar and perform its functions. While this tool is usually reliable, it seems that something strange is occurring. My calendar is generated with events ...

Is it logical to have MySQL queries within the app.js file?

Is app.js processed just once? If so, would it be logical to execute setup queries in app.js to avoid running them with every request? I have a countries and regions table that I require for multiple requests. I am considering implementing something alon ...

Guide on filtering a schema in MongoDB and then redirecting to the same page with the filtered data

I'm in the process of developing a website and I need to implement a feature that allows users to filter products by their type. Currently, I have a MongoDB collection containing items with attributes such as id, name, price, and type. The goal is to ...

Submitting late leads to several consecutive submissions

I am working on a jQuery code that aims to introduce a short time delay to allow for the proper execution of an AJAX request: $('#form_id').submit(function(e) { e.preventDefault(); $submit_url = $(this).data('submitUrl'); ...

Node.js expressing caution about the use of backslashes in console logging statements

While this issue may not be considered crucial, I have observed an unexpected behavior when it comes to logging backslashes to the console. To verify the results, please try the following two examples in your terminal. I experimented with versions 0.10 an ...

Deliver a communication from the dialogue box on the MEAN stack website to the task pane

Currently experimenting with the Dialog API within Office addins. Able to successfully trigger a Dialog box from my task pane using: $scope.openDialog = function () { Office.context.ui.displayDialogAsync('https://localhost:3000/home', ...

Even with the addition of a key prop, the console still indicates that the list requires a unique key

I am working with an array of objects and trying to fetch data from it. I have added key props to both the first and second div, but I am still getting a console warning saying: Warning: Each child in a list should have a unique "key" prop. const data ...

How can you compare array values in Vuejs while iterating through them?

WelcomeWorld.vue <template> <div> <div v-for="box in boxes" :key="box.sname"> <BaseAccordian> <template v-slot:title>{{ box.sname }}</template> <temp ...

Changing floating point numbers to text in JavaScript

I'm looking for an efficient way to store an array of THREE.Vector3 objects in local storage using JavaScript. Since JavaScript operates with strings, I need to convert a 32-bit float to a string using the best bit ratio possible, ideally equating 32- ...