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

Recursively toggle child elements using JQuery

My knowledge of JQuery is limited, so here's the issue I'm facing. Below is an example of the HTML structure: <ul class="first-class"> <li class="second-class"> <a href="#_"> <i class="fa fa-plus"></i& ...

Ways to identify files with identical names but located in separate subdirectories within a sourcemap

In my VUE project, I am facing an issue where multiple templates with the same filename but located in different sub-folders are not visible when debugging. Currently, I am using webpack 3.12 with devtool set to 'cheap-module-eval-source-map'. W ...

Difficulty displaying data from PapaParse in VueJS despite successful retrieval in console

My first attempt at using PapaParse is running into some issues. I am successfully parsing a remote CSV file and storing the data, as confirmed by console.log. However, when I try to output it with a v-for loop, nothing seems to be working. To achieve thi ...

Partial data sent through Ajax to PHP file

Encountering a peculiar issue with Ajax where the entire string data is not being sent to the php script. Here is the string: "<p class="MsoNormal" style="text-align:justify"><b><u><span lang="DE" style="font-size:10.0pt;mso-bidi-fon ...

Adjusting the size of the iframe to match the dimensions of the window

Is there a way to make the iframe automatically fill up the entire space? For example, only opens the iframe up to half of the window in Mozilla Firefox and IE6. How can I ensure that it takes the maximum size of the screen? Are there any CSS or JavaScr ...

Is it possible that v-parallax in Vue.js Vuetify does not support local files?

When utilizing the v-parallax component with an online image source, everything functions smoothly: <v-parallax dark height="470" src="https://images.unsplash.com/photo-1466916932233-c1b9c82e71c4?ixlib=rb-1.2.1&ixid=eyJ ...

Clicking on the ng-repeat will trigger the ng-click event, which populates all the data using ng

I need help including an HTML page using ng-click within ng-repeat. However, it is currently loading all the content for every ng-repeat element. My specific requirement is to only bind(ng-include) the clicked element. Please see the attachment for m ...

Load VueSimpleSuggest with values from URL parameter upon page initialization

In my Vue JS application, I have integrated the VueSimpleSuggest component like this: <vue-simple-suggest class="input-elements" v-model="chosen" :max-suggestions="0" :list="getList" :filter-by-query=&qu ...

Shade within the autocomplete

Is there a way to make the color property warning work on my autocomplete element at all times, rather than just on focus? Any suggestions or workarounds? Check out this code sandbox for reference. I really want the warning color to be visible constantly ...

Issue TS2349 occurs when attempting to use a combination of boolean and function types within union typing

In my class, there is a property called "isVisible" which can be either a boolean value or a function that returns a boolean. The code snippet below demonstrates what I am currently using. It works fine and achieves the desired result, but during compilat ...

Error encountered when attempting to create a new Vue project using Vue CLI (npm issue)

I'm having trouble creating a new Vue CLI project. It was working fine before, but now it's not working... Vue CLI v4.2.3 ✨ Creating project in /Web develop/Vue Projects/new. ...

Discovering the original value of props in Vue 3 using the Composition API

I am facing an issue with my component where it receives props and emits a custom event. I want the emitted value to be the same as the prop value, but I keep getting a Proxy object instead of the original value. Below is a simplified version of my code: ...

What is the method for HTML inline handlers to retrieve the global window object and the variables contained within it?

During my coding test, I encountered an interesting scenario. I had a function called write and used a button with an inline onclick handler to trigger the write() function. function write(text) { alert(text) } <button onclick='write("Some tex ...

Switching from PHP to JavaScript before returning to PHP to establish and manage sessions

Currently, I am in the process of resolving an issue I am facing. The problem arises when utilizing the following code for someone trying to sign into the admin panel: <script> function myFunction() { //alert('you can type now, end ...

The withRouter function in React Router does not automatically inject the router

Desiring to implement withRouter on my primary React component named 'App'. You can view the documentation here. This is how I utilize it: import React from "react"; import { render } from "react-dom"; import {Router, Link, hashHistory, Rout ...

Animating text with a shake effect using JQuery

I am attempting to create a shake effect on my text input field when validation fails. While I have achieved the shake effect, I am unsure how to customize the default values for direction, distance, and times. Additionally, I believe there is an error i ...

Utilizing Node.js callback for validating JWT tokens

In my Node.js server, I have set up an authentication route to authenticate requests: app.get('/loggedin', auth, function(req, res){ console.log(req.authenticated); res.send(req.authenticated ? req.authenticated: false) }) From what I u ...

Send a property as a string, then transform the string back into JavaScript

I am in the process of creating a versatile carousel that will cater to various conditions. Therefore, I need to set the "imageQuery" on my display page as a string and then make it work as executable javascript within my carousel. The query functions pr ...

Global jQuery variables are unexpectedly coming back as "undefined" despite being declared globally

I need to save a value from a JSON object in a global variable for future use in my code. Despite trying to declare the country variable as global, it seems like it doesn't actually work. $.getJSON(reverseGeoRequestURL, function(reverseGeoResult){ ...

Showing data from a Node.js Express application in a Jade template file

I am encountering an issue with my simple jade page where not all variables passed from the javascript route are displaying correctly. I have attempted to implement the solution described in this answer, but it seems to be ineffective in my case. My goal i ...