3

I used the following code to change the password, but I get "Request failed with status code 400". Can someone give me an indication of where the problem is?

axios.post ('http: // localhost: 1337 / auth / reset-password', {
       code: '',
       password: '1234567',
       passwordConfirmation: '1234567',
     }
     , {
       headers: {
           Authorization: `Bearer $ {this.currentUser.jwt}`
       }
     }
     ) .then (response => {
       // Handle success.
       console.log ('Your user \' s password has been changed. ');
     })
     .catch (error => {
       // Handle error.
       console.log ('An error occurred:', error);
     });
   }

Thanks in advance

3 Answers 3

11

Another alternative way is by using a password reset controller. The scenario is by POST a password object to http://localhost:1337/password, the controller will validate the current password then update the password with given newPassword, and return a new jwt token.

We will post a password object as follows:

{
    "identifier": "yohanes",
    "password": "123456789",
    "newPassword": "123456",
    "confirmPassword": "123456"
}

The steps are:

  1. Create password reset route /api/password/config/routes.json:
{
   "routes": [
       {
          "method": "POST",
          "path": "/password",
          "handler": "password.index"
       }
   ]
}
  1. Create password reset controller at /api/password/controllers/password.js
module.exports = {
   index: async ctx => {
       return 'Hello World!';
   }
}

Note: Don't forget to enable password index at Roles -> Permission -> Application.

  1. Point Postman to http://localhost:1337/password. The response will display the text Hello World!.

  2. Update the password controller:

module.exports = { 
   index: async ctx => { 
       // Get posted params
       // const params = JSON.parse(ctx.request.body); //if post raw object using Postman
       const params = ctx.request.body;

       // The identifier is required.
       if (!params.identifier) {
          return ctx.badRequest(
             null,
             formatError({
                id: 'Auth.form.error.email.provide',
                message: 'Please provide your username or your e-mail.',
             })
          );
       }

       // Other params validation
       .
       .
       .

       // Get User based on identifier
       const user = await strapi.query('user', 'users-permissions').findOne({username: params.identifier});

       // Validate given password against user query result password
       const validPassword = await strapi.plugins['users-permissions'].services.user.validatePassword(params.password, user.password);
        
       if (!validPassword) {
          return ctx.badRequest(
             null,
             formatError({
                id: 'Auth.form.error.invalid',
                message: 'Identifier or password invalid.',
             })
          );
       } else {
          // Generate new hash password
          const password = await strapi.plugins['users-permissions'].services.user.hashPassword({password: params.newPassword});
          // Update user password
          await strapi
            .query('user', 'users-permissions')
            .update({ id: user.id }, { resetPasswordToken: null, password });

          // Return new jwt token
          ctx.send({
             jwt: strapi.plugins['users-permissions'].services.jwt.issue({ id: user.id }),
             user: sanitizeEntity(user.toJSON ? user.toJSON() : user, { model: strapi.query('user', 'users-permissions').model }),
          }); 
       }
    }
 }
  1. Once the password object posted, the controller will update the user password and return a newly created jwt token.

The complete code can be found here. Tested on Strapi v.3.3.2

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks you for this, really save my day. Please update await strapi.query('user', 'users permissions') should be await strapi.query('user', 'users-permissions')
+1 for explaining that you don't have to create a new content-type to have an additional api folder. Really opens up doors to understanding how to create new custom APIs for strapi. Thank you for that.
Any idea how to do this in v4? const password = await strapi.plugins['users-permissions'].services.user.hashPassword doesn't seem to be defined in v4...
5

You will have to use the PUT /users/:id route (from the User API)

If you want this route used by a user, you will have to create a isOwner policy and apply it to this route. To let only the current user udpate it's own password and not all users password.

Here some documentation:

6 Comments

Your welcome - let me know if you have other questions.
Jo, I do, I've been working on my strapi project almost every day for a year now. I will definitely have further questions. Many thanks! :)
every day for a year now. woaw, could you email me at [email protected] and tell me more about your project. I'm interested to have your feedback on the usage of Strapi. It will help us to improve the project in the right way.
Hello Jim, "almost" every day for a year now. :) I will send an email this weekend. Best wishes!
I just sent an email to you, unfortunately I didn't manage to write on the weekend. Best regards!
|
2

Here is yohanes's solution adapted to Strapi v4

For some reason the Strapi team has removed the hashPassword method of the users-permission.user service, so we need to generate the hash ourselves now. For this we use the same having method as v3 did. We need to import bcrypt like this: const bcrypt = require("bcryptjs");

Out new changePassword needs to look something like this:

  async changePassword(ctx) {
    const userId = ctx.request.body.userId;
    const currentPassword = ctx.request.body.currentPassword;
    const newPassword = ctx.request.body.newPassword;

    if (!userId || !currentPassword || !newPassword) {
      return ctx.throw(400, "provide-userId-currentPassword-newPassword");
    }

    let user = await strapi
      .query("plugin::users-permissions.user")
      .findOne({ id: userId });

    const validPassword = await strapi
      .service("plugin::users-permissions.user")
      .validatePassword(currentPassword, user.password);

    if (!validPassword) {
      return ctx.throw(401, "wrong-current-password");
    } else {
      // Generate new hashed password
      const password = bcrypt.hashSync(newPassword, 10);

      user = await strapi.query("plugin::users-permissions.user").update({
        where: { id: user.id },
        data: { resetPasswordToken: null, password },
      });

      // Return new jwt token
      ctx.send({
        jwt: strapi.service("plugin::users-permissions.jwt").issue({
          id: user.id,
        }),
        user: sanitizeOutput(user),
      });
    }
  },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.