-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Expand file tree
/
Copy pathsaveUserProfile.ts
More file actions
236 lines (203 loc) · 7.3 KB
/
saveUserProfile.ts
File metadata and controls
236 lines (203 loc) · 7.3 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import { Apps, AppEvents } from '@rocket.chat/apps';
import type { UserStatus } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Users } from '@rocket.chat/models';
import { Accounts } from 'meteor/accounts-base';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { twoFactorRequired } from '../../app/2fa/server/twoFactorRequired';
import { getUserInfo } from '../../app/api/server/helpers/getUserInfo';
import { saveCustomFields } from '../../app/lib/server/functions/saveCustomFields';
import { validateUserEditing } from '../../app/lib/server/functions/saveUser';
import { saveUserIdentity } from '../../app/lib/server/functions/saveUserIdentity';
import { notifyOnUserChange } from '../../app/lib/server/lib/notifyListener';
import { passwordPolicy } from '../../app/lib/server/lib/passwordPolicy';
import { setEmailFunction } from '../../app/lib/server/methods/setEmail';
import { settings as rcSettings } from '../../app/settings/server';
import { setUserStatusMethod } from '../../app/user-status/server/methods/setUserStatus';
import { compareUserPassword } from '../lib/compareUserPassword';
import { compareUserPasswordHistory } from '../lib/compareUserPasswordHistory';
import { removeOtherTokens } from '../lib/removeOtherTokens';
const MAX_BIO_LENGTH = 260;
const MAX_NICKNAME_LENGTH = 120;
async function saveUserProfile(
this: Meteor.MethodThisType,
settings: {
email?: string;
username?: string;
realname?: string;
newPassword?: string;
statusText?: string;
statusType?: string;
bio?: string;
nickname?: string;
},
customFields: Record<string, unknown>,
..._: unknown[]
) {
if (!rcSettings.get<boolean>('Accounts_AllowUserProfileChange')) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'saveUserProfile',
});
}
if (!this.userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'saveUserProfile',
});
}
await validateUserEditing(this.userId, {
_id: this.userId,
email: settings.email,
username: settings.username,
name: settings.realname,
password: settings.newPassword,
statusText: settings.statusText,
});
const user = await Users.findOneById(this.userId);
if (settings.realname || settings.username) {
if (
!(await saveUserIdentity({
_id: this.userId,
name: settings.realname,
username: settings.username,
}))
) {
throw new Meteor.Error('error-could-not-save-identity', 'Could not save user identity', {
method: 'saveUserProfile',
});
}
}
if (settings.statusText || settings.statusText === '') {
await setUserStatusMethod(this.userId, undefined, settings.statusText);
}
if (settings.statusType) {
await setUserStatusMethod(this.userId, settings.statusType as UserStatus, undefined);
}
if (user && settings.bio) {
if (typeof settings.bio !== 'string') {
throw new Meteor.Error('error-invalid-field', 'bio', {
method: 'saveUserProfile',
});
}
if (settings.bio.length > MAX_BIO_LENGTH) {
throw new Meteor.Error('error-bio-size-exceeded', `Bio size exceeds ${MAX_BIO_LENGTH} characters`, {
method: 'saveUserProfile',
});
}
await Users.setBio(user._id, settings.bio.trim());
}
if (user && settings.nickname) {
if (typeof settings.nickname !== 'string') {
throw new Meteor.Error('error-invalid-field', 'nickname', {
method: 'saveUserProfile',
});
}
if (settings.nickname.length > MAX_NICKNAME_LENGTH) {
throw new Meteor.Error('error-nickname-size-exceeded', `Nickname size exceeds ${MAX_NICKNAME_LENGTH} characters`, {
method: 'saveUserProfile',
});
}
await Users.setNickname(user._id, settings.nickname.trim());
}
if (user && settings.email) {
await setEmailFunction(settings.email, user);
}
const canChangePasswordForOAuth = rcSettings.get<boolean>('Accounts_AllowPasswordChangeForOAuthUsers');
if (canChangePasswordForOAuth || user?.services?.password) {
// Should be the last check to prevent error when trying to check password for users without password
if (settings.newPassword && rcSettings.get<boolean>('Accounts_AllowPasswordChange') === true && user?.services?.password?.bcrypt) {
// don't let user change to same password
if (user && (await compareUserPassword(user, { plain: settings.newPassword }))) {
throw new Meteor.Error('error-password-same-as-current', 'Entered password same as current password', {
method: 'saveUserProfile',
});
}
if (user?.services?.passwordHistory && !(await compareUserPasswordHistory(user, { plain: settings.newPassword }))) {
throw new Meteor.Error('error-password-in-history', 'Entered password has been previously used', {
method: 'saveUserProfile',
});
}
passwordPolicy.validate(settings.newPassword);
await Accounts.setPasswordAsync(this.userId, settings.newPassword, {
logout: false,
});
await Users.addPasswordToHistory(
this.userId,
user.services?.password.bcrypt,
rcSettings.get<number>('Accounts_Password_History_Amount'),
);
try {
await removeOtherTokens(this.userId, this.connection?.id || '');
} catch (e) {
Accounts._clearAllLoginTokens(this.userId);
}
}
}
await Users.setProfile(this.userId, {});
if (customFields && Object.keys(customFields).length) {
await saveCustomFields(this.userId, customFields);
}
// App IPostUserUpdated event hook
const updatedUser = await Users.findOneById(this.userId);
// This should never happen, but since `Users.findOneById` might return null, we'll handle it just in case
if (!updatedUser) {
throw new Error('Unexpected error after saving user profile: user not found');
}
void notifyOnUserChange({ clientAction: 'updated', id: updatedUser._id, diff: await getUserInfo(updatedUser) });
await Apps.self?.triggerEvent(AppEvents.IPostUserUpdated, { user: updatedUser, previousUser: user });
return true;
}
const saveUserProfileWithTwoFactor = twoFactorRequired(saveUserProfile, {
requireSecondFactor: true,
});
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
saveUserProfile(
settings: {
email?: string;
username?: string;
realname?: string;
newPassword?: string;
statusText?: string;
statusType?: string;
bio?: string;
nickname?: string;
},
customFields: Record<string, any>,
...args: unknown[]
): boolean;
}
}
export function executeSaveUserProfile(
this: Meteor.MethodThisType,
settings: {
email?: string;
username?: string;
realname?: string;
newPassword?: string;
statusText?: string;
statusType?: string;
bio?: string;
nickname?: string;
},
customFields: Record<string, any> = {},
...args: unknown[]
) {
check(settings, Object);
check(customFields, Match.Maybe(Object));
if (settings.email || settings.newPassword) {
return saveUserProfileWithTwoFactor.call(this, settings, customFields, ...args);
}
return saveUserProfile.call(this, settings, customFields, ...args);
}
Meteor.methods<ServerMethods>({
async saveUserProfile(settings, customFields, ...args) {
check(settings, Object);
check(customFields, Match.Maybe(Object));
if (settings.email || settings.newPassword) {
return saveUserProfileWithTwoFactor.call(this, settings, customFields, ...args);
}
return saveUserProfile.call(this, settings, customFields, ...args);
},
});