Jean-Sébastien Herbaux 7f285fb755
[V4] Enhanced sanitize & remove restricted relations from content API's payloads (#11411)
* Rework sanitizeEntity, first iteration

* remove console.log

* Remove useless comments

* Fix e2e tests

* Fix up user e2e test

* Fix remove-restricted-relations visitor

* Handle grapqhql resolver, prevent access to restricted relations

* Handle polymorphic relation in the related visitor

* Remove morph attribute if empty

* Use only the find action to check if the relation is allowed
2021-11-04 15:47:53 +01:00

105 lines
2.2 KiB
JavaScript

'use strict';
/**
* User.js controller
*
* @description: A set of functions called "actions" for managing `User`.
*/
const _ = require('lodash');
const { sanitize } = require('@strapi/utils');
const { getService } = require('../utils');
const adminUserController = require('./user/admin');
const apiUserController = require('./user/api');
const sanitizeUser = (user, ctx) => {
const { auth } = ctx.state;
const userSchema = strapi.getModel('plugin::users-permissions.user');
return sanitize.contentAPI.output(user, userSchema, { auth });
};
const resolveController = ctx => {
const {
state: { isAuthenticatedAdmin },
} = ctx;
return isAuthenticatedAdmin ? adminUserController : apiUserController;
};
const resolveControllerMethod = method => ctx => {
const controller = resolveController(ctx);
const callbackFn = controller[method];
if (!_.isFunction(callbackFn)) {
return ctx.notFound();
}
return callbackFn(ctx);
};
module.exports = {
create: resolveControllerMethod('create'),
update: resolveControllerMethod('update'),
/**
* Retrieve user records.
* @return {Object|Array}
*/
async find(ctx, next, { populate } = {}) {
const users = await getService('user').fetchAll(ctx.query, populate);
ctx.body = await Promise.all(users.map(user => sanitizeUser(user, ctx)));
},
/**
* Retrieve a user record.
* @return {Object}
*/
async findOne(ctx) {
const { id } = ctx.params;
let data = await getService('user').fetch({ id });
if (data) {
data = await sanitizeUser(data, ctx);
}
ctx.body = data;
},
/**
* Retrieve user count.
* @return {Number}
*/
async count(ctx) {
ctx.body = await getService('user').count(ctx.query);
},
/**
* Destroy a/an user record.
* @return {Object}
*/
async destroy(ctx) {
const { id } = ctx.params;
const data = await getService('user').remove({ id });
const sanitizedUser = await sanitizeUser(data, ctx);
ctx.send(sanitizedUser);
},
/**
* Retrieve authenticated user.
* @return {Object|Array}
*/
async me(ctx) {
const user = ctx.state.user;
if (!user) {
return ctx.badRequest('Unauthenticated request');
}
ctx.body = await sanitizeUser(user, ctx);
},
};