Sanitization: Unable to sanitize users-permissions.user

System Information
  • Strapi Version: 4.1.5
  • Operating System: Ubuntu
  • Database: PostgreSQL
  • Node Version: 14.18.2
  • NPM Version: 6.14.15
  • Yarn Version:

Hello,

Have just created a me controller to get my user with populated fields. At this current time when performing login, the role is not provided in the response such that I have resorted to created a me endpoint to return that along with other relational fields.

The challenge I’m having is that I’m unable to use the sanitize method to remove fields such as password, resetPasswordToken, and confirmationToken. When trying to use sanitize,

me/routes/me.js

// path: ./src/api/me/routes/me.js

module.exports = {
    routes: [
        {
            method: 'GET',
            path: '/me',
            handler: 'me.index',
        }
    ]
}

me/controllers/me.js


'use strict';

const { sanitizeEntity` } = require('@strapi/utils');

/**
 * A set of functions called "actions" for `me`
 */

module.exports = {

  index: async (ctx, next) => {
    try {

      const { user } = ctx.state;

      if (user) {
        const entity = await strapi.query("plugin::users-permissions.user").findOne({

          where: { id: user.id },

          populate: [
            "role",
... other fields
]

        return await sanitizeEntity(entity, { model: strapi.getModel('plugin::users-permissions.user') });

I found this approach from How can I retrieve logged-in user's role with REST API? - #2 by JeppePepp Thanks!

After verifying that indeed sanitizeEntity does not exist on @strapi/utils and following a bit more research I found

const { sanitizeEntity } = require('strapi-utils');
...
        return sanitizeEntity(entity, { model: strapi.getModel('plugin::users-permissions.user') });

You may have to install strapi-utils

1 Like