Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call the password reset function in Strapi?

Tags:

strapi

By default, Strapi has a welcome email template and password reset template. For the custom function we are writing, we want to create users without a password (or random password the user doesn't know). Then, when our function is finished, we want to send the user a welcome email (overwriting/disabling the default), with a password reset link. Therefore, we need to call the function/service to reset the password for the user, and receive the URL to send this in the welcome email.

However, currently I cannot find any information regarding the function/service to reset the user password. The only method I now see is to call http://localhost/auth/reset-password with the username or email, but would like to use a service such as strapi.services.user.resetPassword(userID) to get the URL back.

Does this function exists and/or is this possible?

Using Strapi 3.1.2

like image 673
elJeffe Avatar asked Dec 05 '25 14:12

elJeffe


1 Answers

I have move my original answer here since it was more relevant to the question. To reset a user password, we have to provide an identifier which is in this case the username. The possible steps are:

  1. Query the user based on the identifier
  2. Generate new hash password based on provided randomly generated value
  3. Update the user password with the newly generated hash-password.

The implementation at a controller can be like this:

module.exports = { 
   resetPassword: async ctx => { 
      ....
      
      // Provide identifier and newPassword
      const params = ctx.request.body;
      const identifier = params.identifier
      const newPassword = params.newPassword
      
      // Get User based on identifier
      const user = await strapi.query('user', 'users permissions').findOne({username: identifier});

      // Generate new hash password
      const password = await strapi.plugins['users-permissions'].services.user.hashPassword({password: newPassword});
      
      // Update user password
      await strapi
         .query('user', 'users-permissions')
         .update({ id: user.id }, { resetPasswordToken: null, password });

      ...
   }
}

Don't forget to implement isOwner policy, or if the old password can be provided, we can validate the process using isValidPassword

   // Validate given old password against user query result password
   const isValidPassword = await strapi.plugins['users-permissions'].services.user.validatePassword(old.password, user.password);

like image 142
yohanes Avatar answered Dec 10 '25 02:12

yohanes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!