The password update encountered an error due to authentication requiring a recent login, even after re-authenticating

I have integrated

"firebase": "^10.13.0"
for user authentication in my project using next.js 14.2 along with typescript.

However, I am encountering an issue where updating the user password results in the auth/requires-recent-login error even after reauthentication.

My assumption was that after successful reauthentication, the user would have a grace period to update their password before being prompted to login again due to it being "too long ago."

To mitigate this, I have attempted to directly invoke the updatePassword function post reauthentication, but unfortunately, the problem persists.

Outlined below is the workflow:

updateUserPassword:

function updateUserPassword(password: string): void {
  const auth = getAuth();
  const user = auth.currentUser;

  if (user) {
    updatePassword(user, password)
      .then(() => {
        console.log("Password updated!");
      })
      .catch((error: Error) => {
        console.log("Error updateUserPassword: " + error.message);
        if (error.message.includes("auth/requires-recent-login")) {
          console.log("reauthUser");
          reauthUser(password);
        }
      });
  } else {
    console.log("User is not authenticated");
  }
}

reauthUser:

const reauthUser = async (password: string): Promise<void> => {
  const auth = getAuth();

  if (auth.currentUser) {
    const providerId = auth.currentUser.providerData[0]?.providerId;
    console.log("providerId: ", providerId);

    if (providerId === "google.com") {
      await reauthWithGoogle();
      updatePassword(auth.currentUser, password)
        .then(() => {
          console.log("Password updated!");
        })
        .catch((error: Error) => {
          console.log(
            "Error updateUserPassword in reauthUser: " + error.message,
          );
        });
    } else {
      alert("Unsupported authentication provider.");
    }
  } else {
    router.push(ROUTES.signin);
  }
};

reauthWithGoogle

const reauthWithGoogle = async (): Promise<void> => {
  const auth = getAuth();
  googleProvider.setCustomParameters({ prompt: "select_account" });

  if (auth.currentUser) {
    reauthenticateWithPopup(auth.currentUser, googleProvider)
      .then(async (result) => {
        console.log("reauthenticateWithPopup");
      })
      .catch((error) => {
        alert("Error reauthenticateWithPopup: " + error.message);
      });
  } else {
    router.push(ROUTES.signin);
  }
};

Answer №1

When dealing with Firebase Authentication, there are certain sensitive operations that need to be performed cautiously. One example is changing a user's password, which is a security-sensitive task requiring recent user login credentials. Therefore, it is vital to reauthenticate the users each time such an operation is carried out.

There are two possible solutions to address this issue: either reauthenticate the user by requesting their credentials without logging them out, or sign the user out and prompt them to authenticate again.

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

Applying Styles to Cells Using the Google Sheets API (v4)

Having encountered an issue while using the Google Sheets API (v4) for programmatically creating or updating spreadsheets, I have come across the following problem: According to the documentation (https://developers.google.com/sheets/api/reference/rest/v4 ...

Utilizing jQuery and JSON to showcase the contents of an array

My goal is to display all the items in an array by utilizing JSON and jQuery from the Song of Ice and Fire API. Currently, I am only able to display one item from each of the arrays. If you want to view the codepen, click here: https://codepen.io/frederic ...

Can AJAX function properly when the server-side code is hosted on a separate domain?

After opening Firefox's scratchpad and inputting the following code... function ajaxRequest() { var xmlhttp; var domainName = location.host; var url = 'http://leke.dyndns.org/cgi/dn2ipa/resolve-dns.py?domainName='; url = url + domainName + ...

Having trouble accessing static files in my express application

After encountering issues using the fonts folder files in one of my controller files, I attempted to reference them from within the public folder. Despite referencing code from StackOverflow and adding it to my app.js file, I was unable to make it work suc ...

Converting JSON to objects in Angular 2 using Typescript

Being new to Angular2 and Typescript, I am currently in the learning phase. I am trying to retrieve data from a REST service and then populate a list with this data obtained from the service. The API link I am using is http://jsonplaceholder.typicode.com/u ...

Experiencing extended loading periods on the website while executing an R script

I am currently working on querying a MySQL database within a webpage using an R script. My script contains 4 different "query" functions and multiple calculations that generate statistical graphs based on a variable "N". To achieve this, I am utilizing PHP ...

The data being retrieved from the controller in AngularJS is not displaying as expected

Just started learning AngularJS. Currently following this MEAN Stack Intro: Build an end-to-end application Created a basic html file to test angularjs. index.html <html> <head> <meta charset="utf-8"> <title> ...

Adding files to an Angular ViewModel using DropzoneJS

I am facing a challenge in extracting file content and inserting it into a specific FileViewModel. This is necessary because I need to bundle all files with MainViewModel which contains a list of FileViewModel before sending it from the client (angular) to ...

Having trouble activating Ajax code in jquery

I have integrated the swal (SweetAlert) UI for confirmation messages in my project. In my jQuery code, I have an Ajax function to remove an item when the user clicks on "Yes, Delete It." However, for some reason, the Ajax code is not triggering as expecte ...

How can I exclude TypeScript files generated from js in WebStorm?

Using the Enable Typescript Compiler option results in a .js file being generated for every .ts and .tsx file by the TypeScript compiler. https://i.sstatic.net/Yr0lR.jpg When performing code completion, WebStorm does not recognize that the files were aut ...

Finding out whether the OnsenUI component is compiled during a unit test

My project utilizes the vue-cordova-webpack template. Within my Vue component, I have integrated a v-ons-input element. During the unit testing of my component, I encountered the need to modify the value of v-ons-input. However, this can only be done post- ...

Exploring Model Object Properties with ngFor in Angular

Currently, I am developing an Angular application with a Model object that consists of properties of various types. My goal is to loop through these properties in the component and generate form fields for each property. Unfortunately, the implementation i ...

Navigating to view component in Angular2 Routing: Issue with router-link click event not working

I have set up my app.routes.ts file and imported all the necessary dependencies. Afterward, I connected all the routes to their respective Components as follows: import {ModuleWithProviders} from '@angular/core'; import {Routes, RouterModule} f ...

VARIABLE_NAME isn't functioning properly on the window

The code window.VARIABLE_NAME is not functioning properly and is causing the following error. Can you please provide assistance? Uncaught SyntaxError: Unexpected token. This is the code I have written: var window.testing ...

Issue with Firefox pageMod addon: window.location not functioning properly

I'm developing a unique Firefox Add-on that implements page redirects based on keyboard input. The keyboard detection is functioning properly, however, the redirect functionality seems to be failing. The complete code can be found on GitHub (even thou ...

Incorporate a new CSS class into a DIV using JavaScript

Sample HTML: <div id="bar" class="style_one"></div> Is there a way to include the class style_two without deleting style_one? final outcome: <div id="bar" class="style_one style_two"></div> ...

Which is the better approach: extending properties of a Node module.exports object, or completely replacing the object?

When working in Node.js, which approach is more optimal and why? Is it better to completely replace the module.exports object like this: module.exports = { myFuncOne = function(thing) { console.log(thing); }, myFuncTwo = function(stuff) { c ...

Accessing the property of the scrollbox in Reactjs: How to get the horizontal offset

I am currently working on a scroll view designed as a series of views wrapped horizontally within a container. <div id="scroller" ref="scroller" onClick= {this.onClick.bind(this)} onMouseMove={this._onMouseMove.bind(this)}> {t ...

Starting Array index value at 1 in React js: A step-by-step guide

Is there a way to make the index value start from 1 instead of 0? {props.useraccountListData.useraccountTypeList.map((item, index) => ( {index} ))} The current output is starting from 0, 1, 2. However, I would like it to start from 1, 2, 3... ...

Encountering an endless loop when utilizing cycle-idb with a text field for user input

Struggling to develop a basic test app that captures user input from a text field, displays it, and stores it using cycle-idb. Unfortunately, I've been stuck in an endless loop no matter what steps I take. Below is the complete main function: functi ...