How to update user info in Strapi

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

Hi, i would just create separate route for this, they made the core plugins very difficult to override/update/extend.

hey <@318705719480287235> thanks for the response. Could you please elaborate a bit. I’m pretty new to the strapi and want to learn. Any examples related to what you suggest?
Thanks in advance.

Instead of trying to extend users-permissions routes create separate one use strapi generate cli command and add your logic here in the route controller

thanks. I’ll take a look