如何调用Strapi中的密码重置功能?
How to call the password reset function in Strapi?
默认情况下,Strapi 有欢迎电子邮件模板和密码重置模板。对于我们正在编写的自定义函数,我们希望创建没有密码的用户(或用户不知道的随机密码)。然后,当我们的功能完成后,我们想向用户发送一封欢迎电子邮件(overwriting/disabling 默认值),并重置密码 link。因此,我们需要调用function/service为用户重设密码,并接收URL在欢迎邮件中发送。
但是,目前我找不到任何关于function/service重置用户密码的信息。我现在看到的唯一方法是使用用户名或电子邮件调用 http://localhost/auth/reset-password
,但我想使用 strapi.services.user.resetPassword(userID)
等服务来取回 URL。
这个功能存在吗and/or这可能吗?
使用 Strapi 3.1.2
我已经移动了我原来的答案 因为它与问题更相关。
要重置用户密码,我们必须提供一个标识符,在本例中为 username
。可能的步骤是:
- 根据标识符查询用户
- 根据提供的随机生成值生成新的哈希密码
- 使用新生成的哈希密码更新用户密码。
控制器的实现可以是这样的:
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 });
...
}
}
不要忘记实施 isOwner
政策,或者如果可以提供旧密码,我们可以使用 isValidPassword
验证流程
// Validate given old password against user query result password
const isValidPassword = await strapi.plugins['users-permissions'].services.user.validatePassword(old.password, user.password);
默认情况下,Strapi 有欢迎电子邮件模板和密码重置模板。对于我们正在编写的自定义函数,我们希望创建没有密码的用户(或用户不知道的随机密码)。然后,当我们的功能完成后,我们想向用户发送一封欢迎电子邮件(overwriting/disabling 默认值),并重置密码 link。因此,我们需要调用function/service为用户重设密码,并接收URL在欢迎邮件中发送。
但是,目前我找不到任何关于function/service重置用户密码的信息。我现在看到的唯一方法是使用用户名或电子邮件调用 http://localhost/auth/reset-password
,但我想使用 strapi.services.user.resetPassword(userID)
等服务来取回 URL。
这个功能存在吗and/or这可能吗?
使用 Strapi 3.1.2
我已经移动了我原来的答案 username
。可能的步骤是:
- 根据标识符查询用户
- 根据提供的随机生成值生成新的哈希密码
- 使用新生成的哈希密码更新用户密码。
控制器的实现可以是这样的:
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 });
...
}
}
不要忘记实施 isOwner
政策,或者如果可以提供旧密码,我们可以使用 isValidPassword
// Validate given old password against user query result password
const isValidPassword = await strapi.plugins['users-permissions'].services.user.validatePassword(old.password, user.password);