105 lines
2.2 KiB
JavaScript
Raw Normal View History

2017-11-14 11:11:22 +01:00
'use strict';
/**
* User.js controller
*
* @description: A set of functions called "actions" for managing `User`.
*/
2017-12-04 15:35:45 +01:00
const _ = require('lodash');
const { sanitize } = require('@strapi/utils');
2021-07-08 18:15:32 +02:00
const { getService } = require('../utils');
const adminUserController = require('./user/admin');
const apiUserController = require('./user/api');
2019-09-12 10:50:52 +02:00
const sanitizeUser = (user, ctx) => {
const { auth } = ctx.state;
const userSchema = strapi.getModel('plugin::users-permissions.user');
return sanitize.contentAPI.output(user, userSchema, { auth });
};
2017-12-04 15:35:45 +01:00
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);
};
2017-11-14 11:11:22 +01:00
module.exports = {
create: resolveControllerMethod('create'),
update: resolveControllerMethod('update'),
2017-11-14 11:11:22 +01:00
/**
* Retrieve user records.
* @return {Object|Array}
*/
async find(ctx, next, { populate } = {}) {
2021-07-28 21:03:32 +02:00
const users = await getService('user').fetchAll(ctx.query, populate);
2019-05-21 16:18:18 +02:00
ctx.body = await Promise.all(users.map(user => sanitizeUser(user, ctx)));
},
2017-11-14 11:11:22 +01:00
/**
* Retrieve a user record.
* @return {Object}
*/
async findOne(ctx) {
const { id } = ctx.params;
2021-07-08 22:07:52 +02:00
let data = await getService('user').fetch({ id });
if (data) {
data = await sanitizeUser(data, ctx);
}
2017-11-14 11:11:22 +01:00
ctx.body = data;
2017-11-14 11:11:22 +01:00
},
/**
* Retrieve user count.
* @return {Number}
2017-11-14 11:11:22 +01:00
*/
async count(ctx) {
2021-07-08 18:15:32 +02:00
ctx.body = await getService('user').count(ctx.query);
2017-11-14 11:11:22 +01:00
},
/**
* Destroy a/an user record.
2017-11-14 11:11:22 +01:00
* @return {Object}
*/
async destroy(ctx) {
const { id } = ctx.params;
2021-07-08 18:15:32 +02:00
const data = await getService('user').remove({ id });
const sanitizedUser = await sanitizeUser(data, ctx);
2021-07-08 18:15:32 +02:00
ctx.send(sanitizedUser);
},
2017-11-14 11:11:22 +01:00
/**
* Retrieve authenticated user.
* @return {Object|Array}
2017-11-14 11:11:22 +01:00
*/
async me(ctx) {
const user = ctx.state.user;
if (!user) {
2021-10-20 17:30:05 +02:00
return ctx.unauthorized();
}
ctx.body = await sanitizeUser(user, ctx);
},
2017-11-14 11:11:22 +01:00
};