After signing out, the function getRedirectResult in Firebase is being invoked

I'm a bit confused about some interesting behavior I've noticed while working with Firebase. Although I never used the older version, I believe getRedirectResult is a newer feature since they partnered with Google.

Currently, I am using Vue.js along with vue-router and Firebase for my single page application (SPA). The app has a landing page as well as another view where users can be logged in or not. Login is achieved through redirection. Upon loading this second view, I check getRedirectResult in the 'activate' hook of vue-router. If there is a user, I perform further actions based on the user information.

The issue arises as follows:

  1. We are on the second page. The user logs in and getRedirectResult successfully finds the user.
  2. The user then logs out and we return to the landing page.
  3. When we click on a button that takes us back to the second page, getRedirectResult still remembers the previous user. How is this possible?

I couldn't find information on whether I am missing something and need an additional check, or if I should somehow force a page refresh after logout to erase the memory of the last logged-in user. Is this a bug or am I overlooking something? Any help would be greatly appreciated!

Here is the code snippet for calling getRedirectResult on the second page within the vue component router's 'activate' hook:

firebase.auth().getRedirectResult()
    .then((result) => {
        return result.user;
    }).then((user) => {
        // Perform necessary actions.
    });

Update: This issue was resolved by performing a hard page refresh in the logout callback, like so:

firebase.auth().signOut()
    .then(() => {window.location.href = '/'});

Answer №1

This situation had me feeling frustrated. You can find more information on the issue at this link (https://github.com/firebase/firebase-js-sdk/issues/133), and unfortunately, it seems to be an intentional behavior.

To work around this, I decided to completely avoid using getRedirectResult(), opting instead to achieve the same functionality by checking for the presence of an authenticated Firebase user without waiting for the redirect callback. In Angular, I utilized AngularFire's authState observable for this purpose. This approach ensures that there are no lingering user data in the client memory when you signOut(), as it wasn't stored in getRedirectResult().

The idea is to implement a Route Guard on the login page, allowing access only if there isn't an authenticated user present. Once you log in successfully (note that signInWithRedirect() may take a few seconds), the firebase user data loads into the client, triggering the Route Guard to prevent access to the login page and directing you to your preferred location.

For an added feature, if you wish to retain the returnUrl, you can store that string in local storage before initiating signInWithRedirect(). Subsequently, retrieve it in the Route Guard upon redirection (and remember to delete it from local storage).

I found inspiration for this solution in a Firebase blog post: . Hopefully, you can adapt this concept to your Vue.js development.

If you're interested, here's a snippet demonstrating how the Route Guard looks like in Angular 2:

import { Injectable } from '@angular/core';
import { AuthService } from './auth.service';
import { Router, CanActivate } from '@angular/router';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class LoginGuardService implements CanActivate {

  constructor(
    private auth: AuthService,
    private router: Router
  ) { }

  canActivate() {
    return this.auth.firebaseUser$.
      pipe(map(user => {
        // The firebaseuser determines if user is logged in
        // If logged in, block the route with a redirect
        if (user) {
          console.log('User detected', user);
          const returnUrl = localStorage.getItem('returnUrl');
          // Route user to returnUrl, if none, go to profile
          if (returnUrl && returnUrl !== '/') {
            this.router.navigate([returnUrl]);
          } else {
            this.router.navigate(['profile']);
          }
          return false;
        }
        return true;
      }));
  }
}

Answer №2

To indicate whether getRedirectResult() has been processed, a flag can be used as shown below:

firebase.auth().getRedirectResult()
  .then((result) => {
    return result.user;
  }).then((user) => {
    if (this.redirectProcessed)
      return; // Ignore

    // Perform necessary actions.

    this.redirectProcessed = true; // Mark redirection completed
  });

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

"Troubleshooting: Issue with AngularJS ng-click Functionality Not Working on Re

Having trouble with the ng-click function in AngularJS when using the following HTML code: <tr ng-repeat="ai in alert_instances" ng-click="go('/alert_instance/{{ai.alert_instancne_id}}')"> <td>{{ai.name}}</td> <td>{{a ...

AngularJS (ui-mask) provides a valid input mask feature

i encountered an issue while trying to create an input mask using ui-mask in AngularJs. I want the textarea to turn green when the entered string is correct. However, in my case, the textarea starts off green and then turns red when a word is typed until t ...

Instructions on how to ensure that an AJAX call will only function when the user is logged in within a Rails application

My application allows users to save photos by clicking on them, but this feature is only available when the user is logged in. Strangely, even when a user is logged out, they can still click on a photo and save it because the show page is identical for bot ...

When IntelliJ starts Spring boot, resources folder assets are not served

I'm following a tutorial similar to this one. The setup involves a pom file that manages two modules, the frontend module and the backend module. Tools being used: IDE: Intellij, spring-boot, Vue.js I initialized the frontent module using vue init w ...

Creating dynamic images in Node.js using JavaScript without relying on HTML5 canvas

Hello everyone, I'm excited to be posting my first question on stackoverflow! Hey there, it's wabsol. I've been diving into the world of nodejs and loving every minute of it. I'm interested in creating a window and/or drawing an image ...

Using a JSP page to trigger a JavaScript function

I am attempting to execute an in-page JavaScript function from within a JSP page. Here is the code snippet, however, the JavaScript functions do not appear to be executing when the JSP page loads on the client side. Is there anything incorrect with the a ...

Utilizing Sequelize to Convert and Cast Data in iLike Queries

When using Sequelize for a full-text search, I encountered an issue with applying the iLike operator to columns of INTEGER or DATE type. How can I cast off a column in this case? To illustrate, here is an example of what I am trying to achieve with a Post ...

Creating dynamic content in the Ajax-enabled Smart Admin theme: A step-by-step guide

As I work on developing an application for a client, my focus is on creating a web service using Laravel5 for the backend. To enhance the user interface of this web service, I have chosen to incorporate the Smart Admin Theme, specifically utilizing the Aja ...

Tips for showing a single progress message when uploading multiple files on eleme.io [vuejs]

Tech Stack: Utilizing Vuejs with element.eleme.io framework. Objective: To implement a feature that allows users to upload multiple files while displaying only one "in progress message". To handle image uploads, we are integrating . During the upload pr ...

Extracting data from a MySQL result array

I've encountered an issue with extracting a value from an array containing JSON data. Below is the JSON data I received (printed using console.log(rows[0])): [ { User_ID: 28, Email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

Discover the #ID and apply AddClass through the URL in the Navigation Jquery

I am currently in the process of developing a website and I am looking to navigate from one link to another using IDs. Here is an example of what I am trying to achieve: Page Name: index.html <a href= "collection.html#rings">Rings</a> Page N ...

Pressing the button will activate the Ctrl+z and Ctrl+y key commands

I have created two separate buttons for triggering actions equivalent to pressing Ctrl+z and Ctrl+y. I am attempting to make these actions occur with the click of a single button. However, when trying to set up the functionality to trigger Ctrl+z and Ctr ...

`Why is it important to debug javascript code?`

I have some outdated JavaScript code that surprisingly still works in Internet Explorer from 2000-2002, but refuses to function properly in browsers like Firefox, Chrome, and Opera. I've come across various browser quirks where different browsers inte ...

What is the correct approach for detecting object collisions in Phaser 3?

Hey everyone, I'm facing a problem and could use some assistance. Currently, I am trying to detect when two containers collide in my project. However, the issue is that the collision is being detected before the objects even start moving on screen. It ...

Start the Vuepress build process and run the generated project

I have created a basic Vuepress project with PWA support. Currently, Vuepress only offers two scripts: "scripts": { "docs:dev": "vuepress dev docs", "docs:build": "vuepress build docs" } The de ...

Encountering a 404 error in Codeigniter when making an AJAX call

After successfully implementing an upload form with ajax, I encountered some issues when attempting to delete uploaded photos. Initially, I received a "csrf protection error," which led me to disable csrf protection, only to then encounter a "404 not found ...

Embarking on the journey of transitioning code from server-side to client-side

Currently, I am looking to transition the code behind section of my asp.net web forms application to client-side ajax or javascript - still deciding on which route to take. The main goal for this change is to ensure that the application remains functional ...

Activate an action only upon closing the page

I am looking for a solution in my vue.js app to execute a function only when the user closes the application. I have tried registering an event listener for beforeunload, but it causes the function to also trigger on page reloads, which is not ideal. Is t ...

An error occurred due to a state update being attempted on an unmounted component. The solution is to properly cancel all subscriptions and asynchronous tasks in a

Currently, I am attempting to utilize ListEmptyComponent within a FlatList. If there is no data present, I intend to display ListEmptyComponent={} However, in the Loadingsecond component, I am using useEffect to render when loading is true; if there is s ...

Solution: The issue where the children's onChange event was not updating the parent in Ant Design was discovered to be due to the Select and Table components nested inside a Tab not changing according to the pageSize

I'm facing an issue with updating a parent element when the children's onChange event is triggered. Specifically, I have an Ant Design Select and Table inside a Tab that are not reflecting changes in the pageSize value. Although setPageSize func ...