Strapi has the user-permission plugin where it has an endpoint to reset a forgotten password. But I would like to change a known password (as a user) in which sending an email with a verification token is not necessary. In Strapi documentation for the user-permission plugin, I didn't come across such an endpoint. How can I achieve this?
Add a comment
|
2 Answers
After inspecting the user-permission plugin's code I implemented a simpler solution instead of extending the plugin. For this, I created a custom controller (and route) as following:
/api/custom/controllers/custom.js
'use strict';
const _ = require('lodash');
const { sanitizeEntity } = require('strapi-utils');
const sanitizeUser = user =>
sanitizeEntity(user, {
model: strapi.query('user', 'users-permissions').model,
});
module.exports = {
async changePassword(ctx) {
const userFromContext = ctx.state.user;
if (!userFromContext) {
return ctx.badRequest(null, [{ messages: [{ id: 'No authorization header was found' }] }]);
}
const params = _.assign({}, ctx.request.body);
if (
params.currentPassword &&
params.newPassword &&
params.confirmNewPassword &&
params.newPassword === params.confirmNewPassword
) {
const user = await strapi.plugins['users-permissions'].services.user.fetch({
id: userFromContext.id,
}, ['role']);
const validPassword = await strapi.plugins['users-permissions'].services.user.validatePassword(params.currentPassword, user.password);
if (!user) {
return ctx.badRequest('User does not exist');
}
if (!validPassword) {
return ctx.badRequest('Old password does not match.')
}
let updateData = { password: params.newPassword };
const data = await strapi.plugins['users-permissions'].services.user.edit({ id: user.id }, updateData);
return ctx.send(sanitizeUser(data));
}
return ctx.badRequest('New passwords do not match.');
}
};
/api/custom/config/routes.json
{
"routes": [
{
"method": "POST",
"path": "/custom/change-password",
"handler": "custom.changePassword",
"config": {
"policies": []
}
}
]
}
Now I can POST an authenticated request to http://localhost:1337/custom/change-password with the following body in order to change the password for a logged-in user:
{
"currentPassword": "Abcd1234",
"newPassword": "Abcde12345",
"confirmNewPassword": "Abcde12345"
}