2020-05-13 12:27:46 +02:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const _ = require('lodash');
|
2020-05-14 11:57:43 +02:00
|
|
|
const { validateUserCreationInput } = require('../validation/user');
|
2020-05-13 12:27:46 +02:00
|
|
|
|
|
|
|
const formatError = error => [
|
|
|
|
{ messages: [{ id: error.id, message: error.message, field: error.field }] },
|
|
|
|
];
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
async create(ctx) {
|
|
|
|
const { body } = ctx.request;
|
|
|
|
|
2020-05-14 11:57:43 +02:00
|
|
|
try {
|
|
|
|
await validateUserCreationInput(body);
|
|
|
|
} catch (err) {
|
|
|
|
return ctx.badRequest(err);
|
2020-05-13 12:27:46 +02:00
|
|
|
}
|
|
|
|
|
2020-05-14 11:57:43 +02:00
|
|
|
const attributes = _.pick(body, ['firstname', 'lastname', 'email', 'roles']);
|
2020-05-13 12:27:46 +02:00
|
|
|
|
|
|
|
const userAlreadyExists = await strapi.admin.services.user.exists({
|
2020-05-14 11:57:43 +02:00
|
|
|
email: attributes.email,
|
2020-05-13 12:27:46 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
if (userAlreadyExists) {
|
|
|
|
return ctx.badRequest(
|
|
|
|
null,
|
|
|
|
formatError({
|
|
|
|
id: 'Auth.form.error.email.taken',
|
|
|
|
message: 'Email already taken',
|
|
|
|
field: ['email'],
|
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const createdUser = await strapi.admin.services.user.create({
|
2020-05-14 11:57:43 +02:00
|
|
|
...attributes,
|
2020-05-14 11:06:16 +02:00
|
|
|
registrationToken: strapi.admin.services.token.createToken(),
|
2020-05-13 12:27:46 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
// Send 201 created
|
2020-05-14 11:57:43 +02:00
|
|
|
ctx.created(strapi.admin.services.user.sanitizeUser(createdUser));
|
2020-05-13 12:27:46 +02:00
|
|
|
},
|
|
|
|
};
|