Issues with changing password on Firebase after re-authentication

What is the goal of this task?

  1. To re-authenticate the user by verifying their current password (this.state.currentPassword)
  2. To update the user's password with a new one (this.state.newPassword)

Which issue am I encountering?

  1. Successfully completed STEP 1 (re-authentication process)
  2. Encountering an error during STEP 2 (password update) resulting in an outer try-catch "Error Reauthenticating"

var user = firebaseApp.auth().currentUser;
var credential = firebase.auth.EmailAuthProvider.credential(
    firebaseApp.auth().currentUser.email,
    this.state.currentPassword
);

// Prompt the user to re-enter their credentials

// STEP 1 : re-authenticate user

user.reauthenticateAndRetrieveDataWithCredential(credential).then(function() {
  // User successfully re-authenticated.

  // After re-authentication, proceed to update password

  //STEP 2 : UPDATE PASSWORD

  var newPassword = firebase.getASecureRandomPassword();

  user.updatePassword(newPassword).then(function() {
    alert("SUCCESS")
    // Password updated successfully.
  }).catch(function(error) {
    console.log(error)
    // An error occurred while updating the password.
  });

}).catch(function(error) {
  // An error occurred during re-authentication.
  alert("Error Reauthenticating")
});

Answer №1

Was able to successfully achieve the desired output using the code provided below.

Credit goes to this informative article.

reauthenticate = (currentPassword) => {
  var user = firebase.auth().currentUser;
  var cred = firebase.auth.EmailAuthProvider.credential(
    user.email, currentPassword);
  return user.reauthenticateAndRetrieveDataWithCredential(cred);
}

changePassword = (currentPassword, newPassword) => {
  this.reauthenticate(currentPassword).then(() => {
    var user = firebase.auth().currentUser;
    user.updatePassword(newPassword).then(() => {
      console.log("Password updated!");
    }).catch((error) => {
      console.log(error);
    });
  }).catch((error) => {
    console.log(error);
  });
}

Will confirm if ES6 syntax is necessary and make inquiries tomorrow.

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

Styling with the method in React is a beneficial practice

I am working on a simple React app that includes some components requiring dynamic styling. I am currently using a method to achieve this, but I am wondering if there are other recommended ways to handle dynamic styling in React. Everything seems to be wor ...

Utilize an enum from a shared library by exporting it and incorporating it into a TypeScript project

Currently, I am in the process of developing a library where a React component is being exported along with some interfaces and an enum. After compiling the typescript project, I realized that the library is specifically for React and not typescript, so I ...

Preventing users from inputting the symbols "+" or "-" in a React JS input field

Essentially, the input field should only accept values between 1 and 999 Input Field : <input type="number" value={value} onChange={this.props.onViltMaxUserChange} min="0" max="999" /> onChange : onViltMaxUserChange = _.throttle(e = ...

Problem with Bootstrap slider animation

Currently, I am tackling a bootstrap slider project, where the images are all in place, and they transition every few seconds. Everything appears to be functioning correctly, except for the animation display. The image changes suddenly without any smooth t ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Check to see if the data provided is found in the database and retrieve the matching information

Here is a table defined as DB: city ------- cityID cityname store Next, we have an HTML form: <input type="text" class="store"> Objective: My goal is for JavaScript to display an alert after the store value is entered, if it already exists ...

Methods for incorporating JSON Data into ChartJS

Below is my app.js file: app.js var app = angular.module('myApp', []); app.controller('MainCtrl', function($scope, $http) { $http.get('http://happyshappy.13llama.com/wp- json/llama/v1/stats').then(function(response) ...

Adjust the alignment of an expansion panel header to the right using Vuetify

Incorporating the Vuetify expansion panel, I am aiming to align a specific portion of the content within the <div slote="head"></div> to the right, resulting in this desired layout: https://i.sstatic.net/tbOL8.jpg https://i.sstatic.net/22NTS. ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

Tips on using the Unix "paste" command in Node.js without the need to load entire files into memory

Implementing the basic Unix paste command in Python is straightforward, as shown in the following snippet (which currently processes two files, unlike Unix paste that can handle multiple files): def pasteFiles(file1, file2): with open(file1) as f1: w ...

Sticky positioning with varying column widths

How can I create HTML and CSS columns that stick together without manually specifying the "left:" parameter every time? The current example in the fiddle achieves what I want, but requires manual setting of the "left:" value. Is there a way to make this m ...

I currently possess a certain document stored in the database. Is there a way to create a query using mongoose that will allow me to remove an item from the "cart" array within this document?

In this post request, the intention is to remove the item from the "cart" array by identifying it with the product "id". .post('/delete', async (req, res) => { if (await UserProfile.findOneAndDelete({ 'cart.id': req.body.id })) { ...

The Angular application sent an OPTIONS request instead of a POST request via HTTP

I'm encountering CORS errors while attempting to send HTTP requests from my angular.js application to my server. The code used to make the HTTP request is as follows: functions.test = function(foo, bar) { return $http({ method: 'POS ...

The Present Landscape of Crossplatform JavaScript Unit and Systems Testing

When working on JavaScript projects, which asynchronous system and unit test framework would be best suited for use in both node.js and web browsers? The ideal testing system should have the capability to run specific tests for node.js and web browsers, a ...

Conditions and alternatives in Aurelia.js

Is there a way to dynamically insert a CSS class into the DOM using aurelia.js framework? If my <th> element has either the class attribute set as "aut-asc" or "aut-desc", I would like to also add an additional class called: global The class "aut-a ...

What could be causing my .load() function to fail when attempting to target a specific div element?

My goal is to retrieve and display a div tag from another aspx page within my container div. Here is the jQuery code: function GetDocumentInfo(url) { $('MyContainer').load(url + ".otherdiv"); } This operation is triggered by a click event. ...

React.js: Passing an array as a property to an element results in the transformation of the array into an object

I'm trying to understand why passing an array as a prop to another element results in it getting transformed into an object with the array as its value. I need help understanding if this is a common JavaScript 'quirk' or specific to React an ...

Tips for clearing the Javascript Cache

Currently, I am working on implementing angularjs with i18n for translation. One issue that has arisen is the need to find a solution for versioning as the files are loaded from cache each time. i18n/lang-en.json Is there any suggestion on how I can crea ...

Converting Venn diagram code from JavaScript <script> tags to Angular 2: A step-by-step guide

I am struggling to incorporate a Venn diagram into my Angular 2+ project. I followed the code sample provided at - http://jsfiddle.net/johnpham92/h04sknus/ To begin, I executed the following command - npm install venn.js Then I proceeded with impl ...

I am interested in creating a JavaScript function that can transform an image to either a blue or yellow hue using CSS styling

Check out this code snippet. <svg class="defs-only"> <filter id="monochrome" color-interpolation-filters="sRGB" x="0" y="0" height="100%" width="100%"> <feColorMatrix type="matrix" values="0.00 0 0 0 0 ...