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