/
me.ts
212 lines (172 loc) · 5.54 KB
/
me.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable import/no-cycle */
import express from 'express';
import validator from 'validator';
import { LoggerProxy as Logger } from 'n8n-workflow';
import { randomBytes } from 'crypto';
import { Db, InternalHooksManager, ResponseHelper } from '../..';
import { issueCookie } from '../auth/jwt';
import { N8nApp, PublicUser } from '../Interfaces';
import { validatePassword, sanitizeUser, compareHash, hashPassword } from '../UserManagementHelper';
import type { AuthenticatedRequest, MeRequest } from '../../requests';
import { validateEntity } from '../../GenericHelpers';
import { User } from '../../databases/entities/User';
export function meNamespace(this: N8nApp): void {
/**
* Return the logged-in user.
*/
this.app.get(
`/${this.restEndpoint}/me`,
ResponseHelper.send(async (req: AuthenticatedRequest): Promise<PublicUser> => {
return sanitizeUser(req.user);
}),
);
/**
* Update the logged-in user's settings, except password.
*/
this.app.patch(
`/${this.restEndpoint}/me`,
ResponseHelper.send(
async (req: MeRequest.Settings, res: express.Response): Promise<PublicUser> => {
if (!req.body.email) {
Logger.debug('Request to update user email failed because of missing email in payload', {
userId: req.user.id,
payload: req.body,
});
throw new ResponseHelper.ResponseError('Email is mandatory', undefined, 400);
}
if (!validator.isEmail(req.body.email)) {
Logger.debug('Request to update user email failed because of invalid email in payload', {
userId: req.user.id,
invalidEmail: req.body.email,
});
throw new ResponseHelper.ResponseError('Invalid email address', undefined, 400);
}
const { email: currentEmail } = req.user;
const newUser = new User();
Object.assign(newUser, req.user, req.body);
await validateEntity(newUser);
const user = await Db.collections.User.save(newUser);
Logger.info('User updated successfully', { userId: user.id });
await issueCookie(res, user);
const updatedkeys = Object.keys(req.body);
void InternalHooksManager.getInstance().onUserUpdate({
user_id: req.user.id,
fields_changed: updatedkeys,
});
await this.externalHooks.run('user.profile.update', [currentEmail, req.body]);
return sanitizeUser(user);
},
),
);
/**
* Update the logged-in user's password.
*/
this.app.patch(
`/${this.restEndpoint}/me/password`,
ResponseHelper.send(async (req: MeRequest.Password, res: express.Response) => {
const { currentPassword, newPassword } = req.body;
if (typeof currentPassword !== 'string' || typeof newPassword !== 'string') {
throw new ResponseHelper.ResponseError('Invalid payload.', undefined, 400);
}
if (!req.user.password) {
throw new ResponseHelper.ResponseError('Requesting user not set up.');
}
const isCurrentPwCorrect = await compareHash(currentPassword, req.user.password);
if (!isCurrentPwCorrect) {
throw new ResponseHelper.ResponseError(
'Provided current password is incorrect.',
undefined,
400,
);
}
const validPassword = validatePassword(newPassword);
req.user.password = await hashPassword(validPassword);
const user = await Db.collections.User.save(req.user);
Logger.info('Password updated successfully', { userId: user.id });
await issueCookie(res, user);
void InternalHooksManager.getInstance().onUserUpdate({
user_id: req.user.id,
fields_changed: ['password'],
});
await this.externalHooks.run('user.password.update', [user.email, req.user.password]);
return { success: true };
}),
);
/**
* Store the logged-in user's survey answers.
*/
this.app.post(
`/${this.restEndpoint}/me/survey`,
ResponseHelper.send(async (req: MeRequest.SurveyAnswers) => {
const { body: personalizationAnswers } = req;
if (!personalizationAnswers) {
Logger.debug(
'Request to store user personalization survey failed because of empty payload',
{
userId: req.user.id,
},
);
throw new ResponseHelper.ResponseError(
'Personalization answers are mandatory',
undefined,
400,
);
}
await Db.collections.User.save({
id: req.user.id,
personalizationAnswers,
});
Logger.info('User survey updated successfully', { userId: req.user.id });
void InternalHooksManager.getInstance().onPersonalizationSurveySubmitted(
req.user.id,
personalizationAnswers,
);
return { success: true };
}),
);
/**
* Creates an API Key
*/
this.app.post(
`/${this.restEndpoint}/me/api-key`,
ResponseHelper.send(async (req: AuthenticatedRequest) => {
const apiKey = `n8n_api_${randomBytes(40).toString('hex')}`;
await Db.collections.User.update(req.user.id, {
apiKey,
});
const telemetryData = {
user_id: req.user.id,
public_api: false,
};
void InternalHooksManager.getInstance().onApiKeyCreated(telemetryData);
return { apiKey };
}),
);
/**
* Deletes an API Key
*/
this.app.delete(
`/${this.restEndpoint}/me/api-key`,
ResponseHelper.send(async (req: AuthenticatedRequest) => {
await Db.collections.User.update(req.user.id, {
apiKey: null,
});
const telemetryData = {
user_id: req.user.id,
public_api: false,
};
void InternalHooksManager.getInstance().onApiKeyDeleted(telemetryData);
return { success: true };
}),
);
/**
* Get an API Key
*/
this.app.get(
`/${this.restEndpoint}/me/api-key`,
ResponseHelper.send(async (req: AuthenticatedRequest) => {
return { apiKey: req.user.apiKey };
}),
);
}