登录后如何修改密码?

Ben*_*ves 1 strapi

我使用以下代码更改密码,但收到“请求失败,状态代码为 400”。有人可以告诉我问题出在哪里吗?

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);
     });
   }
Run Code Online (Sandbox Code Playgroud)

提前致谢

yoh*_*nes 6

另一种替代方法是使用密码重置控制器。该场景是通过POST一个密码对象http://localhost:1337/password,控制器将验证当前password的密码,然后使用给定的密码更新newPassword,并返回一个新的jwt token

我们将发布一个密码对象,如下所示:

{
    "identifier": "yohanes",
    "password": "123456789",
    "newPassword": "123456",
    "confirmPassword": "123456"
}
Run Code Online (Sandbox Code Playgroud)

步骤是:

  1. 创建密码重置路由/api/password/config/routes.json
{
   "routes": [
       {
          "method": "POST",
          "path": "/password",
          "handler": "password.index"
       }
   ]
}
Run Code Online (Sandbox Code Playgroud)
  1. 在以下位置创建密码重置控制器 /api/password/controllers/password.js
module.exports = {
   index: async ctx => {
       return 'Hello World!';
   }
}
Run Code Online (Sandbox Code Playgroud)

注意:不要忘记启用password indexat Roles -> Permission -> Application

  1. 将邮递员指向http://localhost:1337/password. 响应将显示文本Hello World!

  2. 更新密码控制器:

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 }),
          }); 
       }
    }
 }
Run Code Online (Sandbox Code Playgroud)
  1. 一旦密码对象发布,控制器将更新用户密码并返回一个新创建的 jwt 令牌。

完整的代码可以在这里找到。在 Strapi v.3.3.2 上测试


Jim*_*RIE 5

您必须使用该PUT /users/:id路线(来自用户 API)

如果您希望用户使用此路由,则必须创建 isOwner 策略并将其应用于此路由。仅允许当前用户更新其自己的密码,而不是所有用户的密码。

这里有一些文档: