Ensure the Firebase real-time database in Javascript purges the active session upon tab or browser closure

I need to implement a feature in my Firebase real-time database project using JavaScript where the current session is logged out automatically after closing the tab or browser.

When I log in with my email and password, if I copy the URL and paste it into a new tab, it currently displays the same page instead of redirecting to the login screen. I want it to log out the user's session when they close the tab, close the browser, or try to access the page again in a new tab so that they always see the login screen.

 function login() {
    var email = document.getElementById("email");
    var password = document.getElementById("password");

    firebase.auth().signInWithEmailAndPassword(email.value, password.value)
        .then((result) => {

            alert("Login Successful");
            console.log(result);
            if (email.value == "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e7e4e5b7b4b5c6e1ebe7efeaa8e5e9eb">[email protected]</a>") {
                window.location.href = "dpr.html"
            } else if (email.value == "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="39585b5a080b0a0d795e54585055175a5654">[email protected]</a>") {
                window.location.href = "gpr.html"
            } else if (email.value == "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2c3c0c19390919697e2c5cfc3cbce8cc1cdcf">[email protected]</a>") {
                window.location.href = "cargo.html"
            } else if (email.value == "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="58393a3b696a6b6c6d6e183f35393134763b3735">[email protected]</a>") {
                window.location.href = "admin.html"
            }
        })
        .catch(function (error) {
            var errorCode = error.code;
            console.log(errorCode);
            var errorMessage = error.message;
            alert("Please Enter the correct password")
        })
}

Answer №1

When using Firebase Authentication, the user's authentication state is stored in local storage by default. However, if you want to change this behavior, you can modify the auth state persistence settings. To ensure that the auth state is only saved for the current session, you can use the following code snippet:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)

For more details and a comprehensive explanation, refer to the official documentation provided in the link above.

Answer №2

It might be 3 years too late, but this solution was a lifesaver for me:

https://firebase.google.com/docs/auth/web/auth-state-persistence#web-namespaced-api

By using firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION), I was able to ensure that existing and future Auth states are now persisted in the current session only. This means that even if a user forgets to sign out or closes the window, their authentication state will still be maintained. Additionally, any new sign-ins will also be persisted with session persistence. Here is a snippet of the code I used:
return firebase.auth().signInWithEmailAndPassword(email, password)
  .catch((error) => {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
  });

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

Retrieve the current date and time in JSON format using moment.js for the local

Below is the code snippet I am working with: var startTime = moment("2020-09-08 16:00:00").toDate(); console.log(startTime) const data = {start: startTime} console.log(JSON.stringify(data) After running it, the result is as follows: Tue Sep 08 ...

Ways to superimpose images

Everything seems to be functioning correctly in my code, but I would like the output images to overlap slightly. This could possibly be achieved using margins, padding, or some other script. Additionally, is there a way to incorporate z-index so that the ...

Swapping out components or features within AngularJS

Is it possible to make my dependencies interchangeable in AngularJS? For example, if I have a service named myService stored within the module myDependency, how can I switch out myDependency with a new service without disrupting the main application? Shou ...

Axios is experiencing challenges in transmitting the cookie

Even after attempting to include {withCredentials: true}, I am still facing issues with sending the cookie to the backend server. return await axios.post(`${API_URL}/posts/category/${id}`, { withCredentials: true }) https://i.stack.imgur.com/Cr8xv.png ...

troubles encountered in implementing JavaScript to toggle the display of content upon clicking a link

Here is the code below. Upon page load, the form data will be hidden. When clicking on the comment link, it will toggle the visibility of the form content. Clicking on the comment link again will show the hidden content once more. What is desired is to ha ...

Is it possible to utilize JavaScript to access a .php file located in a separate directory?

Although I have been searching all day, I couldn't find a workout that specifically addresses my issue. I'm new to JavaScript and AJAX. Currently, I am exploring a web app called calendar.php located in the directory C:\xampp\htdocs&bs ...

Permit the use of HTML tags within an Angular controller or view

My controller : LandingApp.controller('LandingCtrl2', function($scope){ $scope.articles = [ { 'imageSrc' : IMG_DIR + 'spec9.jpg', 'title' : 'Stencils', ...

Obtain an individual item from the reducer array

I am working on a company reducer that will store an array of companies. To optimize performance, I aim to fetch only the necessary company object from my API when a user navigates to /company/name. This way, if a user visits the same company page multiple ...

Configuring CORS in an Angular JS controller

Having a controller with a service that retrieves JSON from another server, I encountered the following issue: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the ...

Utilize the "incorporate" feature to include any string within an array

I am currently working on improving the search function in my application. This particular search function takes input from a search bar and is designed to handle multiple search terms. For example, it should be able to handle queries like "javascript reac ...

Tips for adjusting the color of multiple classes that have a common class using a toggle feature

I am working on a simple website using bootstrap 4 and SCSS. I want to include a toggler that switches between dark and light modes on the webpage. However, I'm facing an issue with changing the background color of 6 Bootstrap cards, footer, and the t ...

Optional parameters in Sammy.js

Utilizing ajax for paging has led me to choose Sammy.js, which works well. However, incorporating checkboxes to filter results poses a challenge. While defining a route for Sammy to intercept is feasible, the issue arises when I wish to avoid displaying ce ...

Retrieving the selected value from a dropdown menu before it is altered using vanilla JavaScript

I am trying to implement a feature where the previous value of a dropdown is captured when it is changed. Essentially, I need to compare the previous and current values of the dropdown and perform an action based on that information. For example, if Option ...

recoil struggles to manage the error thrown by an asynchronous selector

Recoil offers the ability for users to throw errors in async selectors. For more information, please refer to the documentation. Both "<ErrorBoundary>" and "useRecoilValueLoadable()" can handle errors from async selectors, but I encountered issues w ...

I keep encountering a persistent net::ERR_CONNECTION_REFUSED error when attempting to make a POST request to https://localhost:5000/users/add. Despite trying various solutions recommended online, I still cannot

I'm currently developing a workout tracker app using the MERN stack. As part of this project, I have a React JS component that is responsible for adding a new user to the database when the submit button is clicked. To achieve this functionality, I am ...

Conceal overflow in SVG after stroke is applied to top rectangle border

Is there a way to conceal the overflowing red color in this SVG? I attempted repositioning it before the rect with the stroke, but that didn't solve the issue. Check out the code and screenshot below. <br><br> <svg _ngcontent-fdl-c1 ...

Embed a service within an Angular 1.5 component

I'm struggling with initializing a test.service.js file from an angular1.5 component and I'm not entirely sure how to accomplish it. Below is the structure I have used for my angular components: var testComponent = { templateUrl: "app/compo ...

What is the appropriate time to end a connection in MongoDB?

Utilizing Node.js Express and MongoDB for my API, I encountered an issue with the mongoClient connection. The data fetching process worked smoothly at first, but without refreshing it threw an error stating "Topology is closed." const express=require("e ...

Ways to show the existing value of a <select> in a label without altering the function

I currently have a label that changes to display the selected option from a dynamic select dropdown, but it only updates when the selection is changed. I would like it to also display the current value when the page first loads. I attempted to change &apos ...

The response from Axios in NodeJs is displaying incorrect encoding

Having some trouble executing a REST call using Axios and receiving an unexpected response. try { const response = await axios.get("https://api.predic8.de/shop/products/"); console.log(response.data); } catch (error) { console.log(`[Error] -> ...