I’m trying to extend the users-permissions plugin in Strapi for updating user information. However, the new endpoint is not appearing under the roles and permissions section.
const _ = require("lodash");
const utils = require("@strapi/utils");
const { ApplicationError, ValidationError } = utils.errors;
module.exports = (plugin) => {
plugin.controllers.user.updateMe = async (ctx) => {
if (!ctx.state.user || !ctx.state.user.id) {
throw new ApplicationError("You need to be logged");
}
if (
!_.has(ctx.request.body, "username") ||
ctx.request.body.username === ""
) {
throw new ValidationError("Invalid data");
}
const allowedProperties = ["username"];
const bodyKeys = Object.keys(ctx.request.body);
if (bodyKeys.filter((key) => !allowedProperties.includes(key)).length > 0) {
throw new ValidationError("Invalid data");
}
const newBody = {};
bodyKeys.map(
(key) =>
(newBody[key] = ctx.request.body[key].trim().replace(/[<>]/g, ""))
);
if (_.has(ctx.request.body, "username")) {
const userWithSameUsername = await strapi
.query("plugin::users-permissions.user")
.findOne({ where: { username: ctx.request.body.username } });
if (
userWithSameUsername &&
_.toString(userWithSameUsername.id) !== _.toString(ctx.state.user.id)
) {
throw new ApplicationError("Username already taken");
}
}
await strapi
.query("plugin::users-permissions.user")
.update({
where: { id: ctx.state.user.id },
data: newBody,
})
.then((res) => {
ctx.response.body = { username: res.username };
ctx.response.status = 200;
});
};
plugin.routes["content-api"].routes.push({
method: "PUT",
path: "/user/me",
handler: "user.updateMe",
config: {
prefix: "",
policies: [],
},
});
return plugin;
};
What am I doing wrong?
This topic has been created from a Discord post (1260850047877124118) to give it more visibility.
It will be on Read-Only mode here.
Join the conversation on Discord