-
Notifications
You must be signed in to change notification settings - Fork 11.2k
/
Copy pathindex.js
411 lines (333 loc) · 11.8 KB
/
index.js
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import { Meteor } from 'meteor/meteor';
import { Match } from 'meteor/check';
import { Accounts } from 'meteor/accounts-base';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import _ from 'underscore';
import { escapeRegExp, escapeHTML } from '@rocket.chat/string-helpers';
import * as Mailer from '../../../mailer/server/api';
import { settings } from '../../../settings/server';
import { callbacks } from '../../../callbacks/server';
import { Roles, Users, Settings } from '../../../models/server';
import { Users as UsersRaw } from '../../../models/server/raw';
import { addUserRoles } from '../../../authorization/server';
import { getAvatarSuggestionForUser } from '../../../lib/server/functions';
import {
isValidAttemptByUser,
isValidLoginAttemptByIp,
} from '../lib/restrictLoginAttempts';
import './settings';
import { getClientAddress } from '../../../../server/lib/getClientAddress';
import { getNewUserRoles } from '../../../../server/services/user/lib/getNewUserRoles';
Accounts.config({
forbidClientAccountCreation: true,
});
const updateMailConfig = _.debounce(() => {
Accounts._options.loginExpirationInDays = settings.get('Accounts_LoginExpiration');
Accounts.emailTemplates.siteName = settings.get('Site_Name');
Accounts.emailTemplates.from = `${ settings.get('Site_Name') } <${ settings.get('From_Email') }>`;
}, 1000);
Meteor.startup(() => {
settings.get(/^(Accounts_LoginExpiration|Site_Name|From_Email)$/, updateMailConfig);
});
Accounts.emailTemplates.userToActivate = {
subject() {
const subject = TAPi18n.__('Accounts_Admin_Email_Approval_Needed_Subject_Default');
const siteName = settings.get('Site_Name');
return `[${ siteName }] ${ subject }`;
},
html(options = {}) {
const email = options.reason ? 'Accounts_Admin_Email_Approval_Needed_With_Reason_Default' : 'Accounts_Admin_Email_Approval_Needed_Default';
return Mailer.replace(TAPi18n.__(email), {
name: escapeHTML(options.name),
email: escapeHTML(options.email),
reason: escapeHTML(options.reason),
});
},
};
Accounts.emailTemplates.userActivated = {
subject({ active, username }) {
const activated = username ? 'Activated' : 'Approved';
const action = active ? activated : 'Deactivated';
const subject = `Accounts_Email_${ action }_Subject`;
const siteName = settings.get('Site_Name');
return `[${ siteName }] ${ TAPi18n.__(subject) }`;
},
html({ active, name, username }) {
const activated = username ? 'Activated' : 'Approved';
const action = active ? activated : 'Deactivated';
return Mailer.replace(TAPi18n.__(`Accounts_Email_${ action }`), {
name: escapeHTML(name),
});
},
};
let verifyEmailTemplate = '';
let enrollAccountTemplate = '';
let resetPasswordTemplate = '';
Meteor.startup(() => {
Mailer.getTemplateWrapped('Verification_Email', (value) => {
verifyEmailTemplate = value;
});
Mailer.getTemplateWrapped('Accounts_Enrollment_Email', (value) => {
enrollAccountTemplate = value;
});
Mailer.getTemplateWrapped('Forgot_Password_Email', (value) => {
resetPasswordTemplate = value;
});
});
Accounts.emailTemplates.verifyEmail.html = function(userModel, url) {
return Mailer.replace(verifyEmailTemplate, { Verification_Url: url, name: userModel.name });
};
Accounts.emailTemplates.verifyEmail.subject = function() {
const subject = settings.get('Verification_Email_Subject');
return Mailer.replace(subject || '');
};
Accounts.urls.resetPassword = function(token) {
return Meteor.absoluteUrl(`reset-password/${ token }`);
};
Accounts.emailTemplates.resetPassword.subject = function(userModel) {
return Mailer.replace(settings.get('Forgot_Password_Email_Subject') || '', {
name: userModel.name,
});
};
Accounts.emailTemplates.resetPassword.html = function(userModel, url) {
return Mailer.replacekey(Mailer.replace(resetPasswordTemplate, {
name: userModel.name,
}), 'Forgot_Password_Url', url);
};
Accounts.emailTemplates.enrollAccount.subject = function(user) {
const subject = settings.get('Accounts_Enrollment_Email_Subject');
return Mailer.replace(subject, user);
};
Accounts.emailTemplates.enrollAccount.html = function(user = {}/* , url*/) {
return Mailer.replace(enrollAccountTemplate, {
name: escapeHTML(user.name),
email: user.emails && user.emails[0] && escapeHTML(user.emails[0].address),
});
};
const getLinkedInName = ({ firstName, lastName }) => {
const { preferredLocale, localized: firstNameLocalized } = firstName;
const { localized: lastNameLocalized } = lastName;
// LinkedIn new format
if (preferredLocale && firstNameLocalized && preferredLocale.language && preferredLocale.country) {
const locale = `${ preferredLocale.language }_${ preferredLocale.country }`;
if (firstNameLocalized[locale] && lastNameLocalized[locale]) {
return `${ firstNameLocalized[locale] } ${ lastNameLocalized[locale] }`;
}
if (firstNameLocalized[locale]) {
return firstNameLocalized[locale];
}
}
// LinkedIn old format
if (!lastName) {
return firstName;
}
return `${ firstName } ${ lastName }`;
};
Accounts.onCreateUser(function(options, user = {}) {
callbacks.run('beforeCreateUser', options, user);
user.status = 'offline';
user.active = user.active !== undefined ? user.active : !settings.get('Accounts_ManuallyApproveNewUsers');
if (!user.name) {
if (options.profile) {
if (options.profile.name) {
user.name = options.profile.name;
} else if (options.profile.firstName) {
// LinkedIn format
user.name = getLinkedInName(options.profile);
}
}
}
if (user.services) {
const verified = settings.get('Accounts_Verify_Email_For_External_Accounts');
for (const service of Object.values(user.services)) {
if (!user.name) {
user.name = service.name || service.username;
}
if (!user.emails && service.email) {
user.emails = [{
address: service.email,
verified,
}];
}
}
}
if (!user.active) {
const destinations = [];
Roles.findUsersInRole('admin').forEach((adminUser) => {
if (Array.isArray(adminUser.emails)) {
adminUser.emails.forEach((email) => {
destinations.push(`${ adminUser.name }<${ email.address }>`);
});
}
});
const email = {
to: destinations,
from: settings.get('From_Email'),
subject: Accounts.emailTemplates.userToActivate.subject(),
html: Accounts.emailTemplates.userToActivate.html(options),
};
Mailer.send(email);
}
return user;
});
Accounts.insertUserDoc = _.wrap(Accounts.insertUserDoc, function(insertUserDoc, options, user) {
const noRoles = !user?.hasOwnProperty('globalRoles');
const globalRoles = [];
if (Match.test(user.globalRoles, [String]) && user.globalRoles.length > 0) {
globalRoles.push(...user.globalRoles);
}
delete user.globalRoles;
if (user.services && !user.services.password) {
const defaultAuthServiceRoles = String(settings.get('Accounts_Registration_AuthenticationServices_Default_Roles')).split(',');
if (defaultAuthServiceRoles.length > 0) {
globalRoles.push(...defaultAuthServiceRoles.map((s) => s.trim()));
}
}
const roles = getNewUserRoles(globalRoles);
if (!user.type) {
user.type = 'user';
}
if (settings.get('Accounts_TwoFactorAuthentication_By_Email_Auto_Opt_In')) {
user.services = user.services || {};
user.services.email2fa = {
enabled: true,
changedAt: new Date(),
};
}
const _id = insertUserDoc.call(Accounts, options, user);
user = Meteor.users.findOne({
_id,
});
if (user.username) {
if (options.joinDefaultChannels !== false && user.joinDefaultChannels !== false) {
Meteor.runAsUser(_id, function() {
return Meteor.call('joinDefaultChannels', options.joinDefaultChannelsSilenced);
});
}
if (user.type !== 'visitor') {
Meteor.defer(function() {
return callbacks.run('afterCreateUser', user);
});
}
if (settings.get('Accounts_SetDefaultAvatar') === true) {
const avatarSuggestions = getAvatarSuggestionForUser(user);
Object.keys(avatarSuggestions).some((service) => {
const avatarData = avatarSuggestions[service];
if (service !== 'gravatar') {
Meteor.runAsUser(_id, function() {
return Meteor.call('setAvatarFromService', avatarData.blob, '', service);
});
return true;
}
return false;
});
}
}
if (noRoles || roles.length === 0) {
const hasAdmin = Users.findOne({
roles: 'admin',
type: 'user',
}, {
fields: {
_id: 1,
},
});
if (hasAdmin) {
roles.push('user');
} else {
roles.push('admin');
if (settings.get('Show_Setup_Wizard') === 'pending') {
Settings.updateValueById('Show_Setup_Wizard', 'in_progress');
}
}
}
addUserRoles(_id, roles);
return _id;
});
Accounts.validateLoginAttempt(function(login) {
login = callbacks.run('beforeValidateLogin', login);
if (!Promise.await(isValidLoginAttemptByIp(getClientAddress(login.connection)))) {
throw new Meteor.Error('error-login-blocked-for-ip', 'Login has been temporarily blocked For IP', {
function: 'Accounts.validateLoginAttempt',
});
}
if (!Promise.await(isValidAttemptByUser(login))) {
throw new Meteor.Error('error-login-blocked-for-user', 'Login has been temporarily blocked For User', {
function: 'Accounts.validateLoginAttempt',
});
}
if (login.allowed !== true) {
return login.allowed;
}
if (login.user.type === 'visitor') {
return true;
}
if (login.user.type === 'app') {
throw new Meteor.Error('error-app-user-is-not-allowed-to-login', 'App user is not allowed to login', {
function: 'Accounts.validateLoginAttempt',
});
}
if (!!login.user.active !== true) {
throw new Meteor.Error('error-user-is-not-activated', 'User is not activated', {
function: 'Accounts.validateLoginAttempt',
});
}
if (!login.user.roles || !Array.isArray(login.user.roles)) {
throw new Meteor.Error('error-user-has-no-roles', 'User has no roles', {
function: 'Accounts.validateLoginAttempt',
});
}
if (login.user.roles.includes('admin') === false && login.type === 'password' && settings.get('Accounts_EmailVerification') === true) {
const validEmail = login.user.emails.filter((email) => email.verified === true);
if (validEmail.length === 0) {
throw new Meteor.Error('error-invalid-email', 'Invalid email __email__');
}
}
login = callbacks.run('onValidateLogin', login);
Users.updateLastLoginById(login.user._id);
Meteor.defer(function() {
return callbacks.run('afterValidateLogin', login);
});
return true;
});
Accounts.validateNewUser(function(user) {
if (user.type === 'visitor') {
return true;
}
if (settings.get('Accounts_Registration_AuthenticationServices_Enabled') === false && settings.get('LDAP_Enable') === false && !(user.services && user.services.password)) {
throw new Meteor.Error('registration-disabled-authentication-services', 'User registration is disabled for authentication services');
}
return true;
});
Accounts.validateNewUser(function(user) {
if (user.type === 'visitor') {
return true;
}
let domainWhiteList = settings.get('Accounts_AllowedDomainsList');
if (_.isEmpty(domainWhiteList?.trim())) {
return true;
}
domainWhiteList = domainWhiteList.split(',').map((domain) => domain.trim());
if (user.emails && user.emails.length > 0) {
const email = user.emails[0].address;
const inWhiteList = domainWhiteList.some((domain) => email.match(`@${ escapeRegExp(domain) }$`));
if (inWhiteList === false) {
throw new Meteor.Error('error-invalid-domain');
}
}
return true;
});
export const MAX_RESUME_LOGIN_TOKENS = parseInt(process.env.MAX_RESUME_LOGIN_TOKENS) || 50;
Accounts.onLogin(async ({ user }) => {
if (!user || !user.services || !user.services.resume || !user.services.resume.loginTokens) {
return;
}
if (user.services.resume.loginTokens.length < MAX_RESUME_LOGIN_TOKENS) {
return;
}
const { tokens } = (await UsersRaw.findAllResumeTokensByUserId(user._id))[0];
if (tokens.length >= MAX_RESUME_LOGIN_TOKENS) {
const oldestDate = tokens.reverse()[MAX_RESUME_LOGIN_TOKENS - 1];
Users.removeOlderResumeTokensByUserId(user._id, oldestDate.when);
}
});