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 lang,
27 events,
28 } = body;
29
30 if (password) {
31 const validPassword = await strapi.plugins[
32 'users-permissions'
33 ].services.user.validatePassword(old_password, user.password);
34 if (!validPassword) throw new Error('Auth.form.error.password.matching');
35 delete ctx.request.body.old_password;
36 }
37
38 const currentUser = await strapi.plugins[
39 'users-permissions'
40 ].services.user.fetch({id: user.id});
41
42 const updatedEvents = events
43 ? [...currentUser.events, ...events]
44 : currentUser.events;
45
46 const data = await strapi.plugins['users-permissions'].services.user.edit(
47 {id: user.id},
48 removeUndefined({
49 username,
50 email,
51 password,
52 firstName,
53 lastName,
54 lang,
55 events: updatedEvents,
56 })
57 );
58
59 ctx.send({user: data});
60 },
61
62 /**
63 * Retrieve authenticated user.
64 * @return {Object}
65 */
66 async me(ctx) {
67 if (!ctx.state.user) throw new Error('no_user');
68
69 const {id} = ctx.state.user;
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
80 const data = sanitizeEntity(user, {
81 model: strapi.query('user', 'users-permissions').model,
82 });
83 ctx.send({...ctx.state.user, profile: data});
84 },
85};