Maintain user authentication in Firebase as long as the localStorage object remains active

I am currently working on an app using Ionic, Angular2, and Firebase.

My approach involves saving the auth.currentUser information in the localStorage when a user logs in or registers. However, I recently discovered that having the user variable set in the localStorage doesn't necessarily mean the user is signed in.

This is how my localStorage variable user looks:

https://i.sstatic.net/REdpv.png

And this is how I retrieve it:

ngOnInit() {
  Promise.all([ //data storage get all..
    this.storage.get('user')
  ])
  .then(([user]) => {
    this.userData = user; //set the user storage to this.userData
    console.log(this.userData)
  })
  .catch(error => {
    console.log("Storage Error.");
  });
}

I have all the user's information stored, but they are not actually signed in. When I check using:

this.afAuth.auth.onAuthStateChanged((user) => {
  if (user) {
    console.log(user)
  } else {
    console.log("Not logged in")
  }
});

It shows that the user isn't logged in. Is there a way for me to maintain the user's login status while utilizing the localStorage information?

Alternatively, can I ensure that the login state remains logged in unless the user explicitly signs out? Without any expiration?

What steps should I take from here? Any suggestions would be greatly appreciated! Thank you.

Answer №1

When it comes to managing users in Firebase, it is important to handle user authentication properly. Relying on local storage to determine if a user is logged in may not be the most secure approach. Instead, utilize Firebase's capabilities to check the user's login status efficiently since Firebase operates on web sockets. Here is an updated version of the ngOnInit function:

ngOnInit() {
    const user = this.afAuth.auth.currentUser;

    if (user) {
      this.userData = user;
    } else {
      // force them to reauthenticate
      user.reauthenticateWithCredential(credential)
        .then(function() {
          // User re-authenticated.
          this.userData = this.afAuth.auth.currentUser;
        }).catch(function(error) {
         // An error happened.
        });
    }
}

To learn more about effectively managing users in Firebase, refer to: https://firebase.google.com/docs/auth/web/manage-users. Hopefully, this information proves useful.

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

`vue.js: li element tag numbers not displaying correctly`

Issue with Number list not displaying correctly using Vue.js I have tried sending it like this. Is there a fix for this problem? This is the code snippet I used to output in Vue.js: p(v-html="selectedProduct.description") Snapsho ...

Can we verify the availability of an Angular library during runtime?

I am in the process of creating a custom Angular library, let's name it libA, which has the capability to utilize another Angular library, named libB, for an optional feature. Essentially, if the Angular application does not include libB, then the fea ...

Acquire a numerical value from a text source and increment it by one using Jquery

I have a simple task of extracting a single number from a particular div. Once obtained, I intend to increment the number by one. However, despite successfully retrieving the number, my attempts to add one to it are not working as expected. For example: ...

Why won't Vanilla JavaScript work with my Rails application?

Having trouble implementing a full screen menu, no Rails errors but not working when project is run. Error received: Cannot read property 'addEventListener' of null JS code snippet: (function() { var Menu = (function() { var burger = d ...

How can I customize the color of the disabled state in a mat-slide-toggle?

I am trying to customize the disabled state color of a mat-slide-toggle. This is what my slide toggle currently looks like: https://i.sstatic.net/Lhz0U.png Here is the code I have been using: <div> <mat-slide-toggle>Slide me!</mat-slide ...

Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest(). Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to ...

Displaying a JQuery loading image on a webpage for a designated amount of time

I am trying to display an image in a div once a price calculation function is called. The image should cover the whole page. Can someone assist me with this? <div class="Progress_Layout" style="display:none"> <div class="Progress_Content"> ...

What causes the discrepancy in calculating marginTop on a desktop browser compared to a mobile browser?

In the top screenshot, you can see a representation of my Pixel 6XL connected to my laptop in USB debug mode. The checkered area represents the URL bar on the Chrome browser displayed on my Pixel device. Below that, the second screenshot shows the view fr ...

Place the second division beneath the first within a single navigation bar that adjusts accordingly to all screen sizes

I am experiencing an issue with the layout of my page that has 2 divs within one nav element. When the screen width is greater than 1024px, everything looks fine. However, when I reduce the width to less than 768px, the two divs merge into one line instead ...

Sending files asynchronously using Angular and ng-file-upload through a RESTful API

I have a form with multiple file upload fields. Here is the process: User fills out the form User selects the files to upload User clicks submit Now, here is what I would like to achieve: Submit the form to the server and receive an ID in return Uploa ...

Encountering an error message stating "Buffer is not defined" while working with gray-matter

Encountering an issue when trying to utilize gray-matter in Angular 9, the error message displayed is: ReferenceError: Buffer is not defined at Object.push../node_modules/gray-matter/lib/utils.js.exports.toBuffer (utils.js:32) at push../node_modul ...

Which is better for toggling between images/icons: a switch statement or a ternary operator?

I have a unique challenge where I am dealing with a dynamic list of thumbnails. Some of the items in this list are images, while others need to be represented by icons. My goal is to display either an image or an icon based on the contentType of each item. ...

Drop Down Automation with Selenium IDE

Currently in the process of automating a User Acceptance Testing (UAT) for a software project at my company. I've completed all the typical tasks like recording actions and clicking on buttons, but ran into an issue with a drop-down menu. The problem ...

What steps can be taken to disable Angular's automatic trimming of fields?

Is there a global way to prevent Angular from automatically trimming input fields throughout the entire application? I know that I can avoid it for specific fields using the ngTrim directive, but it's not ideal to add this directive to every text fiel ...

The div remains unchanged when the button is clicked

My webpage is filled with several large div elements. There's a button on the page that, when clicked, should switch to the next div. Despite my efforts, the code I've written doesn't seem to be working as expected. :( This is the HTML st ...

grunt-webpack claims to have completed without any errors, yet it has failed to bundle any files

Over the past week, I've been attempting to get grunt, babel, and webpack to work together smoothly. Despite trying various solutions that I found during my research, nothing seems to be working as intended. Below is the relevant portion of my gruntfi ...

Using Node with Express and TypeScript to serialize date types as epoch milliseconds universally

I am looking to update my node-based API backend to serialize all Date types as Epoch milliseconds instead of ISO format. For instance, if I have the following interface: export interface Profile { updatedAt: Date; updatedBy: string; } And when I ...

Issue encountered with the Selenium JavaScript Chrome WebDriver

When it comes to testing an application, I always rely on using Selenium chromewebdriver. For beginners like me, the starting point was following this insightful Tutorial: https://code.google.com/p/selenium/wiki/WebDriverJs#Getting_Started After download ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

Tips for utilizing React.GA.plugin.require with multiple trackers:

Can you help me figure out how to enable the ecommerce plugin with multiple trackers using the react-ga package? This is the code I've been using to initialize the trackers: const initTracker = (trackerId, name) => ({ trackingId: trackerId, g ...