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
35 delete ctx.request.body.old_password;
36 }
37
38 const data = await strapi.plugins['users-permissions'].services.user.edit(
39 {id: user.id},
40 removeUndefined({
41 username,
42 email,
43 password,
44 firstName,
45 lastName,
46 events,
47 })
48 );
49
50 ctx.send({user: data});
51 },
52
53 /**
54 * Retrieve authenticated user.
55 * @return {Object}
56 */
57 async me(ctx) {
58 if (!ctx.state.user) throw new Error('no_user');
59
60 const {id} = ctx.state.user;
61 const user = await strapi.plugins['users-permissions'].services.user.fetch({
62 id,
63 });
64
65 if (!user) {
66 return ctx.badRequest(null, [
67 {messages: [{id: 'No authorization header was found'}]},
68 ]);
69 }
70
71 const data = sanitizeEntity(user, {
72 model: strapi.query('user', 'users-permissions').model,
73 });
74 ctx.send({...ctx.state.user, profile: data});
75 },
76};