extensions/users-permissions/controllers/CarosterUser.js (view raw)
1const _ = require('lodash');
2
3module.exports = {
4 /**
5 * Update a record.
6 *
7 * @return {Object}
8 */
9 update: async ctx => {
10 console.log('I AM HEREE');
11 const advancedConfigs = await strapi
12 .store({
13 environment: '',
14 type: 'plugin',
15 name: 'users-permissions',
16 key: 'advanced',
17 })
18 .get();
19
20 const {id} = ctx.params;
21 const {
22 email,
23 username,
24 password,
25 firstName,
26 lastName,
27 events = [],
28 } = ctx.request.body;
29
30 const user = await strapi.plugins['users-permissions'].services.user.fetch({
31 id,
32 });
33
34 if (_.has(ctx.request.body, 'email') && !email) {
35 return ctx.badRequest('email.notNull');
36 }
37
38 if (_.has(ctx.request.body, 'firstName') && !firstName) {
39 return ctx.badRequest('firstName.notNull');
40 }
41
42 if (_.has(ctx.request.body, 'lastName') && !lastName) {
43 return ctx.badRequest('lastName.notNull');
44 }
45
46 if (_.has(ctx.request.body, 'username') && !username) {
47 return ctx.badRequest('username.notNull');
48 }
49
50 if (
51 _.has(ctx.request.body, 'password') &&
52 !password &&
53 user.provider === 'local'
54 ) {
55 return ctx.badRequest('password.notNull');
56 }
57
58 if (_.has(ctx.request.body, 'username')) {
59 const userWithSameUsername = await strapi
60 .query('user', 'users-permissions')
61 .findOne({username});
62
63 if (userWithSameUsername && userWithSameUsername.id != id) {
64 return ctx.badRequest(
65 null,
66 formatError({
67 id: 'Auth.form.error.username.taken',
68 message: 'username.alreadyTaken.',
69 field: ['username'],
70 })
71 );
72 }
73 }
74
75 if (_.has(ctx.request.body, 'email') && advancedConfigs.unique_email) {
76 const userWithSameEmail = await strapi
77 .query('user', 'users-permissions')
78 .findOne({email});
79
80 if (userWithSameEmail && userWithSameEmail.id != id) {
81 return ctx.badRequest(
82 null,
83 formatError({
84 id: 'Auth.form.error.email.taken',
85 message: 'Email already taken',
86 field: ['email'],
87 })
88 );
89 }
90 }
91
92 let updateData = {
93 ...ctx.request.body,
94 };
95
96 if (_.has(ctx.request.body, 'password') && password === user.password) {
97 delete updateData.password;
98 }
99
100 if (!_.has(ctx.request.body, 'events')) {
101 updateData.events = [];
102 }
103
104 const data = await strapi.plugins['users-permissions'].services.user.edit(
105 {id},
106 updateData
107 );
108
109 ctx.send({...data});
110 },
111};