extensions/users-permissions/controllers/User.js (view raw)
1const {removeUndefined, sanitizeEntity} = require('strapi-utils');
2
3const formatError = error => [
4 {messages: [{id: error.id, message: error.message, field: error.field}]},
5];
6
7module.exports = {
8 /**
9 * Update authenticated user.
10 *
11 * @return {Object}
12 */
13 updateMe: async ctx => {
14 const user = ctx.state.user;
15
16 if (!user) {
17 return ctx.badRequest(null, [
18 {messages: [{id: 'No authorization header was found'}]},
19 ]);
20 }
21
22 const {
23 username,
24 email,
25 password,
26 old_password,
27 firstName,
28 lastName,
29 events,
30 } = ctx.request.body;
31
32 if (password) {
33 const validPassword = strapi.plugins[
34 'users-permissions'
35 ].services.user.validatePassword(old_password, user.password);
36 if (!validPassword)
37 return ctx.badRequest(
38 null,
39 formatError({
40 id: 'Auth.form.error.password.matching',
41 message: 'Passwords do not match.',
42 })
43 );
44
45 delete ctx.request.body.old_password;
46 }
47
48 const data = await strapi.plugins['users-permissions'].services.user.edit(
49 {id: user.id},
50 removeUndefined({
51 username,
52 email,
53 password,
54 firstName,
55 lastName,
56 events,
57 })
58 );
59
60 ctx.send(data);
61 },
62
63 /**
64 * Retrieve authenticated user.
65 * @return {Object}
66 */
67 async me(ctx) {
68 const {id} = ctx.state.user;
69
70 const user = await strapi.plugins['users-permissions'].services.user.fetch({
71 id,
72 });
73
74 if (!user) {
75 return ctx.badRequest(null, [
76 {messages: [{id: 'No authorization header was found'}]},
77 ]);
78 }
79 const data = sanitizeEntity(user, {
80 model: strapi.query('user', 'users-permissions').model,
81 });
82 ctx.send(data);
83 },
84};