From 6f749bcbab2d3a72782138ff260408e63bb17d4f Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 21 Jan 2019 18:58:42 -0200 Subject: [PATCH 01/18] Move integrations models to rc-models --- packages/rocketchat-integrations/server/index.js | 2 -- packages/rocketchat-lib/server/models/index.js | 6 +++++- packages/rocketchat-models/server/index.js | 4 ++++ .../server/models/IntegrationHistory.js | 9 ++++++--- .../server/models/Integrations.js | 8 +++++--- 5 files changed, 20 insertions(+), 9 deletions(-) rename packages/{rocketchat-integrations => rocketchat-models}/server/models/IntegrationHistory.js (85%) rename packages/{rocketchat-integrations => rocketchat-models}/server/models/Integrations.js (73%) diff --git a/packages/rocketchat-integrations/server/index.js b/packages/rocketchat-integrations/server/index.js index efaed5238b66..dae9d993637c 100644 --- a/packages/rocketchat-integrations/server/index.js +++ b/packages/rocketchat-integrations/server/index.js @@ -1,8 +1,6 @@ import '../lib/rocketchat'; import './logger'; import './lib/validation'; -import './models/Integrations'; -import './models/IntegrationHistory'; import './publications/integrations'; import './publications/integrationHistory'; import './methods/incoming/addIncomingIntegration'; diff --git a/packages/rocketchat-lib/server/models/index.js b/packages/rocketchat-lib/server/models/index.js index a5602f4dfe8a..a7620e0667d1 100644 --- a/packages/rocketchat-lib/server/models/index.js +++ b/packages/rocketchat-lib/server/models/index.js @@ -10,8 +10,10 @@ import { UserDataFiles, Users, CustomSounds, + Integrations, + IntegrationHistory, + Base as _Base, } from 'meteor/rocketchat:models'; -import { Base as _Base } from 'meteor/rocketchat:models'; Object.assign(RocketChat.models, { _Base, @@ -26,4 +28,6 @@ Object.assign(RocketChat.models, { UserDataFiles, Users, CustomSounds, + Integrations, + IntegrationHistory, }); diff --git a/packages/rocketchat-models/server/index.js b/packages/rocketchat-models/server/index.js index d504e4720ca2..524abe1f5db4 100644 --- a/packages/rocketchat-models/server/index.js +++ b/packages/rocketchat-models/server/index.js @@ -14,6 +14,8 @@ import Statistics from './models/Statistics'; import Permissions from './models/Permissions'; import Roles from './models/Roles'; import CustomSounds from './models/CustomSounds'; +import Integrations from './models/Integrations'; +import IntegrationHistory from './models/IntegrationHistory'; export { Base, @@ -32,4 +34,6 @@ export { Permissions, Roles, CustomSounds, + Integrations, + IntegrationHistory, }; diff --git a/packages/rocketchat-integrations/server/models/IntegrationHistory.js b/packages/rocketchat-models/server/models/IntegrationHistory.js similarity index 85% rename from packages/rocketchat-integrations/server/models/IntegrationHistory.js rename to packages/rocketchat-models/server/models/IntegrationHistory.js index 138979e29939..bda9b16c5388 100644 --- a/packages/rocketchat-integrations/server/models/IntegrationHistory.js +++ b/packages/rocketchat-models/server/models/IntegrationHistory.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from './_Base'; -RocketChat.models.IntegrationHistory = new class IntegrationHistory extends RocketChat.models._Base { +export class IntegrationHistory extends Base { constructor() { super('integration_history'); } @@ -37,4 +37,7 @@ RocketChat.models.IntegrationHistory = new class IntegrationHistory extends Rock removeByIntegrationId(integrationId) { return this.remove({ 'integration._id': integrationId }); } -}; +} + +export default new IntegrationHistory(); + diff --git a/packages/rocketchat-integrations/server/models/Integrations.js b/packages/rocketchat-models/server/models/Integrations.js similarity index 73% rename from packages/rocketchat-integrations/server/models/Integrations.js rename to packages/rocketchat-models/server/models/Integrations.js index 8759d25a1ca0..7686e7d56326 100644 --- a/packages/rocketchat-integrations/server/models/Integrations.js +++ b/packages/rocketchat-models/server/models/Integrations.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from './_Base'; -RocketChat.models.Integrations = new class Integrations extends RocketChat.models._Base { +export class Integrations extends Base { constructor() { super('integrations'); } @@ -17,4 +17,6 @@ RocketChat.models.Integrations = new class Integrations extends RocketChat.model disableByUserId(userId) { return this.update({ userId }, { $set: { enabled: false } }, { multi: true }); } -}; +} + +export default new Integrations(); From 5dec8ce3e316ff01f4eeac8702d5f6516d4bd7fd Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 21 Jan 2019 18:59:34 -0200 Subject: [PATCH 02/18] Move composeMessage function to rc-utils --- packages/rocketchat-lib/package.js | 2 +- .../functions/composeMessageObjectWithUser.js | 20 ---------------- .../composeMessageObjectWithUser_import.js | 3 +++ packages/rocketchat-utils/server/index.js | 1 + .../lib/composeMessageObjectWithUser.js | 23 +++++++++++++++++++ 5 files changed, 28 insertions(+), 21 deletions(-) delete mode 100644 packages/rocketchat-lib/server/functions/composeMessageObjectWithUser.js create mode 100644 packages/rocketchat-lib/server/functions/composeMessageObjectWithUser_import.js create mode 100644 packages/rocketchat-utils/server/lib/composeMessageObjectWithUser.js diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 9784e41bedd6..1226e21e76e0 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -111,7 +111,7 @@ Package.onUse(function(api) { api.addFiles('server/functions/archiveRoom.js', 'server'); api.addFiles('server/functions/checkUsernameAvailability.js', 'server'); api.addFiles('server/functions/checkEmailAvailability.js', 'server'); - api.addFiles('server/functions/composeMessageObjectWithUser.js', 'server'); + api.addFiles('server/functions/composeMessageObjectWithUser_import.js', 'server'); api.addFiles('server/functions/createRoom.js', 'server'); api.addFiles('server/functions/cleanRoomHistory.js', 'server'); api.addFiles('server/functions/deleteMessage.js', 'server'); diff --git a/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser.js b/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser.js deleted file mode 100644 index bb67bf6a9d9c..000000000000 --- a/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser.js +++ /dev/null @@ -1,20 +0,0 @@ -const getUser = (userId) => RocketChat.models.Users.findOneById(userId); - -RocketChat.composeMessageObjectWithUser = function(message, userId) { - if (message) { - if (message.starred && Array.isArray(message.starred)) { - message.starred = message.starred.filter((star) => star._id === userId); - } - if (message.u && message.u._id && RocketChat.settings.get('UI_Use_Real_Name')) { - const user = getUser(message.u._id); - message.u.name = user && user.name; - } - if (message.mentions && message.mentions.length && RocketChat.settings.get('UI_Use_Real_Name')) { - message.mentions.forEach((mention) => { - const user = getUser(mention._id); - mention.name = user && user.name; - }); - } - } - return message; -}; diff --git a/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser_import.js b/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser_import.js new file mode 100644 index 000000000000..89aab2f420ec --- /dev/null +++ b/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser_import.js @@ -0,0 +1,3 @@ +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; + +RocketChat.composeMessageObjectWithUser = composeMessageObjectWithUser; diff --git a/packages/rocketchat-utils/server/index.js b/packages/rocketchat-utils/server/index.js index 48af9bdf8458..c40c7e4517dc 100644 --- a/packages/rocketchat-utils/server/index.js +++ b/packages/rocketchat-utils/server/index.js @@ -14,3 +14,4 @@ export { getAvatarColor } from '../lib/getAvatarColor'; export { getURL } from '../lib/getURL'; export { getValidRoomName } from '../lib/getValidRoomName'; export { placeholders } from '../lib/placeholders'; +export { composeMessageObjectWithUser } from './lib/composeMessageObjectWithUser'; diff --git a/packages/rocketchat-utils/server/lib/composeMessageObjectWithUser.js b/packages/rocketchat-utils/server/lib/composeMessageObjectWithUser.js new file mode 100644 index 000000000000..af9c90df5ed9 --- /dev/null +++ b/packages/rocketchat-utils/server/lib/composeMessageObjectWithUser.js @@ -0,0 +1,23 @@ +import { Users } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; + +const getUser = (userId) => Users.findOneById(userId); + +export const composeMessageObjectWithUser = function(message, userId) { + if (message) { + if (message.starred && Array.isArray(message.starred)) { + message.starred = message.starred.filter((star) => star._id === userId); + } + if (message.u && message.u._id && settings.get('UI_Use_Real_Name')) { + const user = getUser(message.u._id); + message.u.name = user && user.name; + } + if (message.mentions && message.mentions.length && settings.get('UI_Use_Real_Name')) { + message.mentions.forEach((mention) => { + const user = getUser(mention._id); + mention.name = user && user.name; + }); + } + } + return message; +}; From 583cb878796f19646f5ce151bd7060b42c4faf37 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 21 Jan 2019 19:00:38 -0200 Subject: [PATCH 03/18] Move PushNotifications class to push-notifications package --- packages/rocketchat-lib/package.js | 5 ++--- .../server/lib/PushNotification_import.js | 3 +++ packages/rocketchat-push-notifications/package.js | 2 ++ packages/rocketchat-push-notifications/server/index.js | 5 +++++ .../server/lib/PushNotification.js | 10 ++++++---- 5 files changed, 18 insertions(+), 7 deletions(-) create mode 100644 packages/rocketchat-lib/server/lib/PushNotification_import.js rename packages/{rocketchat-lib => rocketchat-push-notifications}/server/lib/PushNotification.js (77%) diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 1226e21e76e0..9604a53f4ceb 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -49,8 +49,7 @@ Package.onUse(function(api) { api.use('konecty:multiple-instances-status'); api.use('rocketchat:file'); api.use('rocketchat:file-upload'); - api.use('rocketchat:push'); - api.use('rocketchat:push-notifications', { unordered: true }); + api.use('rocketchat:push-notifications'); api.use('templating', 'client'); api.use('kadira:flow-router'); @@ -137,7 +136,7 @@ Package.onUse(function(api) { // SERVER LIB api.addFiles('server/lib/configLogger.js', 'server'); - api.addFiles('server/lib/PushNotification.js', 'server'); + api.addFiles('server/lib/PushNotification_import.js', 'server'); api.addFiles('server/lib/defaultBlockedDomainsList.js', 'server'); api.addFiles('server/lib/interceptDirectReplyEmails.js', 'server'); api.addFiles('server/lib/loginErrorMessageOverride.js', 'server'); diff --git a/packages/rocketchat-lib/server/lib/PushNotification_import.js b/packages/rocketchat-lib/server/lib/PushNotification_import.js new file mode 100644 index 000000000000..05c2ab4b2d11 --- /dev/null +++ b/packages/rocketchat-lib/server/lib/PushNotification_import.js @@ -0,0 +1,3 @@ +import { PushNotification } from 'meteor/rocketchat:push-notifications'; + +RocketChat.PushNotification = PushNotification; diff --git a/packages/rocketchat-push-notifications/package.js b/packages/rocketchat-push-notifications/package.js index acf4b16dabff..b920d7734a26 100644 --- a/packages/rocketchat-push-notifications/package.js +++ b/packages/rocketchat-push-notifications/package.js @@ -13,7 +13,9 @@ Package.onUse(function(api) { 'rocketchat:models', 'rocketchat:custom-sounds', 'rocketchat:settings', + 'rocketchat:metrics', 'rocketchat:ui', + 'rocketchat:push', 'templating', ]); api.addFiles('client/stylesheets/pushNotifications.css', 'client'); diff --git a/packages/rocketchat-push-notifications/server/index.js b/packages/rocketchat-push-notifications/server/index.js index 7ee7efc55a06..c7499a51ee6a 100644 --- a/packages/rocketchat-push-notifications/server/index.js +++ b/packages/rocketchat-push-notifications/server/index.js @@ -1 +1,6 @@ import './methods/saveNotificationSettings'; +import PushNotification from './lib/PushNotification'; + +export { + PushNotification, +}; diff --git a/packages/rocketchat-lib/server/lib/PushNotification.js b/packages/rocketchat-push-notifications/server/lib/PushNotification.js similarity index 77% rename from packages/rocketchat-lib/server/lib/PushNotification.js rename to packages/rocketchat-push-notifications/server/lib/PushNotification.js index fea610a53521..e1da63d9a9f4 100644 --- a/packages/rocketchat-lib/server/lib/PushNotification.js +++ b/packages/rocketchat-push-notifications/server/lib/PushNotification.js @@ -1,8 +1,10 @@ import { Push } from 'meteor/rocketchat:push'; +import { settings } from 'meteor/rocketchat:settings'; +import { metrics } from 'meteor/rocketchat:metrics'; -class PushNotification { +export class PushNotification { getNotificationId(roomId) { - const serverId = RocketChat.settings.get('uniqueID'); + const serverId = settings.get('uniqueID'); return this.hash(`${ serverId }|${ roomId }`); // hash } @@ -47,9 +49,9 @@ class PushNotification { }; } - RocketChat.metrics.notificationsSent.inc({ notification_type: 'mobile' }); + metrics.notificationsSent.inc({ notification_type: 'mobile' }); return Push.send(config); } } -RocketChat.PushNotification = new PushNotification(); +export default new PushNotification(); From 039e7cd839fba05d243fc17d2097b879951f8684 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 21 Jan 2019 19:02:00 -0200 Subject: [PATCH 04/18] Import variables to remove dependency of RC namespace --- .../functions/addUserToDefaultChannels.js | 18 +++++--- .../server/functions/addUserToRoom.js | 21 +++++---- .../server/functions/archiveRoom.js | 8 ++-- .../functions/checkUsernameAvailability.js | 4 +- .../server/functions/cleanRoomHistory.js | 12 ++--- .../server/functions/createRoom.js | 28 +++++++----- .../server/functions/deleteMessage.js | 30 +++++++------ .../server/functions/deleteUser.js | 44 ++++++++++--------- .../server/functions/getFullUserData.js | 15 ++++--- .../getRoomByNameOrIdWithOptionToJoin.js | 15 ++++--- .../server/functions/isTheLastMessage.js | 4 +- .../server/functions/loadMessageHistory.js | 16 ++++--- .../server/functions/notifications/audio.js | 10 +++-- .../server/functions/notifications/desktop.js | 14 +++--- .../server/functions/notifications/email.js | 36 ++++++++------- .../server/functions/notifications/index.js | 5 ++- .../server/functions/notifications/mobile.js | 22 ++++++---- .../server/functions/removeUserFromRoom.js | 16 ++++--- .../server/functions/saveCustomFields.js | 3 +- .../saveCustomFieldsWithoutValidation.js | 12 ++--- .../server/functions/saveUser.js | 37 +++++++++------- .../server/functions/sendMessage.js | 13 +++--- .../server/functions/setEmail.js | 8 ++-- .../server/functions/setRealName.js | 16 ++++--- .../server/functions/setUserAvatar.js | 8 ++-- .../server/functions/setUsername.js | 33 +++++++------- .../server/functions/unarchiveRoom.js | 6 ++- .../server/functions/updateMessage.js | 17 ++++--- .../server/functions/validateCustomFields.js | 5 ++- 29 files changed, 278 insertions(+), 198 deletions(-) diff --git a/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js b/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js index 0ad51cea050e..df411a6d0616 100644 --- a/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js +++ b/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js @@ -1,18 +1,22 @@ +import { Rooms, Subscriptions, Messages } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { callbacks } from 'meteor/rocketchat:callbacks'; + RocketChat.addUserToDefaultChannels = function(user, silenced) { - RocketChat.callbacks.run('beforeJoinDefaultChannels', user); - const defaultRooms = RocketChat.models.Rooms.findByDefaultAndTypes(true, ['c', 'p'], { fields: { usernames: 0 } }).fetch(); + callbacks.run('beforeJoinDefaultChannels', user); + const defaultRooms = Rooms.findByDefaultAndTypes(true, ['c', 'p'], { fields: { usernames: 0 } }).fetch(); defaultRooms.forEach((room) => { // put user in default rooms - const muted = room.ro && !RocketChat.authz.hasPermission(user._id, 'post-readonly'); + const muted = room.ro && !hasPermission(user._id, 'post-readonly'); if (muted) { - RocketChat.models.Rooms.muteUsernameByRoomId(room._id, user.username); + Rooms.muteUsernameByRoomId(room._id, user.username); } - if (!RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id)) { + if (!Subscriptions.findOneByRoomIdAndUserId(room._id, user._id)) { // Add a subscription to this user - RocketChat.models.Subscriptions.createWithRoomAndUser(room, user, { + Subscriptions.createWithRoomAndUser(room, user, { ts: new Date(), open: true, alert: true, @@ -23,7 +27,7 @@ RocketChat.addUserToDefaultChannels = function(user, silenced) { // Insert user joined message if (!silenced) { - RocketChat.models.Messages.createUserJoinWithRoomIdAndUser(room._id, user); + Messages.createUserJoinWithRoomIdAndUser(room._id, user); } } }); diff --git a/packages/rocketchat-lib/server/functions/addUserToRoom.js b/packages/rocketchat-lib/server/functions/addUserToRoom.js index 26f8649c0f49..c9e22dbad3b0 100644 --- a/packages/rocketchat-lib/server/functions/addUserToRoom.js +++ b/packages/rocketchat-lib/server/functions/addUserToRoom.js @@ -1,25 +1,28 @@ import { Meteor } from 'meteor/meteor'; +import { Rooms, Subscriptions, Messages } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.addUserToRoom = function(rid, user, inviter, silenced) { const now = new Date(); - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); // Check if user is already in room - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id); if (subscription) { return; } if (room.t === 'c' || room.t === 'p') { - RocketChat.callbacks.run('beforeJoinRoom', user, room); + callbacks.run('beforeJoinRoom', user, room); } - const muted = room.ro && !RocketChat.authz.hasPermission(user._id, 'post-readonly'); + const muted = room.ro && !hasPermission(user._id, 'post-readonly'); if (muted) { - RocketChat.models.Rooms.muteUsernameByRoomId(rid, user.username); + Rooms.muteUsernameByRoomId(rid, user.username); } - RocketChat.models.Subscriptions.createWithRoomAndUser(room, user, { + Subscriptions.createWithRoomAndUser(room, user, { ts: now, open: true, alert: true, @@ -30,7 +33,7 @@ RocketChat.addUserToRoom = function(rid, user, inviter, silenced) { if (!silenced) { if (inviter) { - RocketChat.models.Messages.createUserAddedWithRoomIdAndUser(rid, user, { + Messages.createUserAddedWithRoomIdAndUser(rid, user, { ts: now, u: { _id: inviter._id, @@ -38,13 +41,13 @@ RocketChat.addUserToRoom = function(rid, user, inviter, silenced) { }, }); } else { - RocketChat.models.Messages.createUserJoinWithRoomIdAndUser(rid, user, { ts: now }); + Messages.createUserJoinWithRoomIdAndUser(rid, user, { ts: now }); } } if (room.t === 'c' || room.t === 'p') { Meteor.defer(function() { - RocketChat.callbacks.run('afterJoinRoom', user, room); + callbacks.run('afterJoinRoom', user, room); }); } diff --git a/packages/rocketchat-lib/server/functions/archiveRoom.js b/packages/rocketchat-lib/server/functions/archiveRoom.js index 26d756bd5e6e..c906746c9c42 100644 --- a/packages/rocketchat-lib/server/functions/archiveRoom.js +++ b/packages/rocketchat-lib/server/functions/archiveRoom.js @@ -1,8 +1,10 @@ import { Meteor } from 'meteor/meteor'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.archiveRoom = function(rid) { - RocketChat.models.Rooms.archiveById(rid); - RocketChat.models.Subscriptions.archiveByRoomId(rid); + Rooms.archiveById(rid); + Subscriptions.archiveByRoomId(rid); - RocketChat.callbacks.run('afterRoomArchived', RocketChat.models.Rooms.findOneById(rid), Meteor.user()); + callbacks.run('afterRoomArchived', Rooms.findOneById(rid), Meteor.user()); }; diff --git a/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js b/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js index 1aba54ba77f6..6a3027b773b3 100644 --- a/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js +++ b/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js @@ -1,12 +1,12 @@ import { Meteor } from 'meteor/meteor'; import s from 'underscore.string'; - +import { settings } from 'meteor/rocketchat:settings'; let usernameBlackList = []; const toRegExp = (username) => new RegExp(`^${ s.escapeRegExp(username).trim() }$`, 'i'); -RocketChat.settings.get('Accounts_BlockedUsernameList', (key, value) => { +settings.get('Accounts_BlockedUsernameList', (key, value) => { usernameBlackList = value.split(',').map(toRegExp); }); diff --git a/packages/rocketchat-lib/server/functions/cleanRoomHistory.js b/packages/rocketchat-lib/server/functions/cleanRoomHistory.js index c668b32191e2..2004db0157c0 100644 --- a/packages/rocketchat-lib/server/functions/cleanRoomHistory.js +++ b/packages/rocketchat-lib/server/functions/cleanRoomHistory.js @@ -1,5 +1,7 @@ import { TAPi18n } from 'meteor/tap:i18n'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { Messages, Rooms } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; RocketChat.cleanRoomHistory = function({ rid, latest = new Date(), oldest = new Date('0001-01-01T00:00:00Z'), inclusive = true, limit = 0, excludePinned = true, filesOnly = false, fromUsers = [] }) { const gt = inclusive ? '$gte' : '$gt'; @@ -10,7 +12,7 @@ RocketChat.cleanRoomHistory = function({ rid, latest = new Date(), oldest = new const text = `_${ TAPi18n.__('File_removed_by_prune') }_`; let fileCount = 0; - RocketChat.models.Messages.findFilesByRoomIdPinnedTimestampAndUsers( + Messages.findFilesByRoomIdPinnedTimestampAndUsers( rid, excludePinned, ts, @@ -20,18 +22,18 @@ RocketChat.cleanRoomHistory = function({ rid, latest = new Date(), oldest = new FileUpload.getStore('Uploads').deleteById(document.file._id); fileCount++; if (filesOnly) { - RocketChat.models.Messages.update({ _id: document._id }, { $unset: { file: 1 }, $set: { attachments: [{ color: '#FD745E', text }] } }); + Messages.update({ _id: document._id }, { $unset: { file: 1 }, $set: { attachments: [{ color: '#FD745E', text }] } }); } }); if (filesOnly) { return fileCount; } - const count = limit ? RocketChat.models.Messages.removeByIdPinnedTimestampLimitAndUsers(rid, excludePinned, ts, limit, fromUsers) : RocketChat.models.Messages.removeByIdPinnedTimestampAndUsers(rid, excludePinned, ts, fromUsers); + const count = limit ? Messages.removeByIdPinnedTimestampLimitAndUsers(rid, excludePinned, ts, limit, fromUsers) : Messages.removeByIdPinnedTimestampAndUsers(rid, excludePinned, ts, fromUsers); if (count) { - RocketChat.models.Rooms.resetLastMessageById(rid); - RocketChat.Notifications.notifyRoom(rid, 'deleteMessageBulk', { + Rooms.resetLastMessageById(rid); + Notifications.notifyRoom(rid, 'deleteMessageBulk', { rid, excludePinned, ts, diff --git a/packages/rocketchat-lib/server/functions/createRoom.js b/packages/rocketchat-lib/server/functions/createRoom.js index f901eb3e1b24..33293ceead7e 100644 --- a/packages/rocketchat-lib/server/functions/createRoom.js +++ b/packages/rocketchat-lib/server/functions/createRoom.js @@ -1,4 +1,8 @@ import { Meteor } from 'meteor/meteor'; +import { Users, Rooms, Subscriptions } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { hasPermission, addUserRoles } from 'meteor/rocketchat:authorization'; +import { getValidRoomName } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import s from 'underscore.string'; @@ -11,7 +15,7 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData throw new Meteor.Error('error-invalid-name', 'Invalid name', { function: 'RocketChat.createRoom' }); } - owner = RocketChat.models.Users.findOneByUsername(owner, { fields: { username: 1 } }); + owner = Users.findOneByUsername(owner, { fields: { username: 1 } }); if (!owner) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { function: 'RocketChat.createRoom' }); } @@ -27,7 +31,7 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData const now = new Date(); let room = Object.assign({ - name: RocketChat.getValidRoomName(name), + name: getValidRoomName(name), fname: name, t: type, msgs: 0, @@ -62,21 +66,21 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData } if (type === 'c') { - RocketChat.callbacks.run('beforeCreateChannel', owner, room); + callbacks.run('beforeCreateChannel', owner, room); } - room = RocketChat.models.Rooms.createWithFullRoomData(room); + room = Rooms.createWithFullRoomData(room); for (const username of members) { - const member = RocketChat.models.Users.findOneByUsername(username, { fields: { username: 1, 'settings.preferences': 1 } }); + const member = Users.findOneByUsername(username, { fields: { username: 1, 'settings.preferences': 1 } }); const isTheOwner = username === owner.username; if (!member) { continue; } // make all room members (Except the owner) muted by default, unless they have the post-readonly permission - if (readOnly === true && !RocketChat.authz.hasPermission(member._id, 'post-readonly') && !isTheOwner) { - RocketChat.models.Rooms.muteUsernameByRoomId(room._id, username); + if (readOnly === true && !hasPermission(member._id, 'post-readonly') && !isTheOwner) { + Rooms.muteUsernameByRoomId(room._id, username); } const extra = { open: true }; @@ -85,22 +89,22 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData extra.ls = now; } - RocketChat.models.Subscriptions.createWithRoomAndUser(room, member, extra); + Subscriptions.createWithRoomAndUser(room, member, extra); } - RocketChat.authz.addUserRoles(owner._id, ['owner'], room._id); + addUserRoles(owner._id, ['owner'], room._id); if (type === 'c') { Meteor.defer(() => { - RocketChat.callbacks.run('afterCreateChannel', owner, room); + callbacks.run('afterCreateChannel', owner, room); }); } else if (type === 'p') { Meteor.defer(() => { - RocketChat.callbacks.run('afterCreatePrivateGroup', owner, room); + callbacks.run('afterCreatePrivateGroup', owner, room); }); } Meteor.defer(() => { - RocketChat.callbacks.run('afterCreateRoom', owner, room); + callbacks.run('afterCreateRoom', owner, room); }); if (Apps && Apps.isLoaded()) { diff --git a/packages/rocketchat-lib/server/functions/deleteMessage.js b/packages/rocketchat-lib/server/functions/deleteMessage.js index 1f05cdd2975c..d34152a0e95b 100644 --- a/packages/rocketchat-lib/server/functions/deleteMessage.js +++ b/packages/rocketchat-lib/server/functions/deleteMessage.js @@ -1,10 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { settings } from 'meteor/rocketchat:settings'; +import { Messages, Uploads, Rooms } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.deleteMessage = function(message, user) { - const keepHistory = RocketChat.settings.get('Message_KeepHistory'); - const showDeletedStatus = RocketChat.settings.get('Message_ShowDeletedStatus'); - const deletedMsg = RocketChat.models.Messages.findOneById(message._id); + const keepHistory = settings.get('Message_KeepHistory'); + const showDeletedStatus = settings.get('Message_ShowDeletedStatus'); + const deletedMsg = Messages.findOneById(message._id); if (deletedMsg && Apps && Apps.isLoaded()) { const prevent = Promise.await(Apps.getBridges().getListenerBridge().messageEvent('IPreMessageDeletePrevent', deletedMsg)); @@ -15,17 +19,17 @@ RocketChat.deleteMessage = function(message, user) { if (keepHistory) { if (showDeletedStatus) { - RocketChat.models.Messages.cloneAndSaveAsHistoryById(message._id); + Messages.cloneAndSaveAsHistoryById(message._id); } else { - RocketChat.models.Messages.setHiddenById(message._id, true); + Messages.setHiddenById(message._id, true); } if (message.file && message.file._id) { - RocketChat.models.Uploads.update(message.file._id, { $set: { _hidden: true } }); + Uploads.update(message.file._id, { $set: { _hidden: true } }); } } else { if (!showDeletedStatus) { - RocketChat.models.Messages.removeById(message._id); + Messages.removeById(message._id); } if (message.file && message.file._id) { @@ -34,21 +38,21 @@ RocketChat.deleteMessage = function(message, user) { } Meteor.defer(function() { - RocketChat.callbacks.run('afterDeleteMessage', deletedMsg); + callbacks.run('afterDeleteMessage', deletedMsg); }); // update last message - if (RocketChat.settings.get('Store_Last_Message')) { - const room = RocketChat.models.Rooms.findOneById(message.rid, { fields: { lastMessage: 1 } }); + if (settings.get('Store_Last_Message')) { + const room = Rooms.findOneById(message.rid, { fields: { lastMessage: 1 } }); if (!room.lastMessage || room.lastMessage._id === message._id) { - RocketChat.models.Rooms.resetLastMessageById(message.rid, message._id); + Rooms.resetLastMessageById(message.rid, message._id); } } if (showDeletedStatus) { - RocketChat.models.Messages.setAsDeletedByIdAndUser(message._id, user); + Messages.setAsDeletedByIdAndUser(message._id, user); } else { - RocketChat.Notifications.notifyRoom(message.rid, 'deleteMessage', { _id: message._id }); + Notifications.notifyRoom(message.rid, 'deleteMessage', { _id: message._id }); } if (Apps && Apps.isLoaded()) { diff --git a/packages/rocketchat-lib/server/functions/deleteUser.js b/packages/rocketchat-lib/server/functions/deleteUser.js index 363a49f1c9e0..85a0445c7756 100644 --- a/packages/rocketchat-lib/server/functions/deleteUser.js +++ b/packages/rocketchat-lib/server/functions/deleteUser.js @@ -1,9 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { Users, Subscriptions, Messages, Rooms, Integrations } from 'meteor/rocketchat:models'; +import { hasRole, getUsersInRole } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; RocketChat.deleteUser = function(userId) { - const user = RocketChat.models.Users.findOneById(userId, { + const user = Users.findOneById(userId, { fields: { username: 1, avatarOrigin: 1 }, }); @@ -12,7 +16,7 @@ RocketChat.deleteUser = function(userId) { const roomCache = []; // Iterate through all the rooms the user is subscribed to, to check if they are the last owner of any of them. - RocketChat.models.Subscriptions.db.findByUserId(userId).forEach((subscription) => { + Subscriptions.db.findByUserId(userId).forEach((subscription) => { const roomData = { rid: subscription.rid, t: subscription.t, @@ -22,9 +26,9 @@ RocketChat.deleteUser = function(userId) { // DMs can always be deleted, so let's ignore it on this check if (roomData.t !== 'd') { // If the user is an owner on this room - if (RocketChat.authz.hasRole(user._id, 'owner', subscription.rid)) { + if (hasRole(user._id, 'owner', subscription.rid)) { // Fetch the number of owners - const numOwners = RocketChat.authz.getUsersInRole('owner', subscription.rid).fetch().length; + const numOwners = getUsersInRole('owner', subscription.rid).fetch().length; // If it's only one, then this user is the only owner. if (numOwners === 1) { // If the user is the last owner of a public channel, then we need to abort the deletion @@ -35,7 +39,7 @@ RocketChat.deleteUser = function(userId) { } // For private groups, let's check how many subscribers it has. If the user is the only subscriber, then it will be eliminated and doesn't need to abort the deletion - roomData.subscribers = RocketChat.models.Subscriptions.findByRoomId(subscription.rid).count(); + roomData.subscribers = Subscriptions.findByRoomId(subscription.rid).count(); if (roomData.subscribers > 1) { throw new Meteor.Error('error-user-is-last-owner', `To delete this user you'll need to set a new owner to the following room: ${ subscription.name }.`, { @@ -49,47 +53,47 @@ RocketChat.deleteUser = function(userId) { roomCache.push(roomData); }); - const messageErasureType = RocketChat.settings.get('Message_ErasureType'); + const messageErasureType = settings.get('Message_ErasureType'); switch (messageErasureType) { case 'Delete': const store = FileUpload.getStore('Uploads'); - RocketChat.models.Messages.findFilesByUserId(userId).forEach(function({ file }) { + Messages.findFilesByUserId(userId).forEach(function({ file }) { store.deleteById(file._id); }); - RocketChat.models.Messages.removeByUserId(userId); + Messages.removeByUserId(userId); break; case 'Unlink': - const rocketCat = RocketChat.models.Users.findOneById('rocket.cat'); + const rocketCat = Users.findOneById('rocket.cat'); const nameAlias = TAPi18n.__('Removed_User'); - RocketChat.models.Messages.unlinkUserId(userId, rocketCat._id, rocketCat.username, nameAlias); + Messages.unlinkUserId(userId, rocketCat._id, rocketCat.username, nameAlias); break; } roomCache.forEach((roomData) => { if (roomData.subscribers === null && roomData.t !== 'd' && roomData.t !== 'c') { - roomData.subscribers = RocketChat.models.Subscriptions.findByRoomId(roomData.rid).count(); + roomData.subscribers = Subscriptions.findByRoomId(roomData.rid).count(); } // Remove DMs and non-channel rooms with only 1 user (the one being deleted) if (roomData.t === 'd' || (roomData.t !== 'c' && roomData.subscribers === 1)) { - RocketChat.models.Subscriptions.removeByRoomId(roomData.rid); - RocketChat.models.Messages.removeFilesByRoomId(roomData.rid); - RocketChat.models.Messages.removeByRoomId(roomData.rid); - RocketChat.models.Rooms.removeById(roomData.rid); + Subscriptions.removeByRoomId(roomData.rid); + Messages.removeFilesByRoomId(roomData.rid); + Messages.removeByRoomId(roomData.rid); + Rooms.removeById(roomData.rid); } }); - RocketChat.models.Subscriptions.removeByUserId(userId); // Remove user subscriptions - RocketChat.models.Rooms.removeDirectRoomContainingUsername(user.username); // Remove direct rooms with the user + Subscriptions.removeByUserId(userId); // Remove user subscriptions + Rooms.removeDirectRoomContainingUsername(user.username); // Remove direct rooms with the user // removes user's avatar if (user.avatarOrigin === 'upload' || user.avatarOrigin === 'url') { FileUpload.getStore('Avatars').deleteByName(user.username); } - RocketChat.models.Integrations.disableByUserId(userId); // Disables all the integrations which rely on the user being deleted. - RocketChat.Notifications.notifyLogged('Users:Deleted', { userId }); + Integrations.disableByUserId(userId); // Disables all the integrations which rely on the user being deleted. + Notifications.notifyLogged('Users:Deleted', { userId }); } - RocketChat.models.Users.removeById(userId); // Remove user from users database + Users.removeById(userId); // Remove user from users database }; diff --git a/packages/rocketchat-lib/server/functions/getFullUserData.js b/packages/rocketchat-lib/server/functions/getFullUserData.js index dfe562daf9e3..78ccac34e372 100644 --- a/packages/rocketchat-lib/server/functions/getFullUserData.js +++ b/packages/rocketchat-lib/server/functions/getFullUserData.js @@ -1,5 +1,8 @@ import s from 'underscore.string'; import { Logger } from 'meteor/rocketchat:logger'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; const logger = new Logger('getFullUserData'); @@ -28,7 +31,7 @@ const fullFields = { let publicCustomFields = {}; let customFields = {}; -RocketChat.settings.get('Accounts_CustomFields', (key, value) => { +settings.get('Accounts_CustomFields', (key, value) => { publicCustomFields = {}; customFields = {}; @@ -52,9 +55,9 @@ RocketChat.settings.get('Accounts_CustomFields', (key, value) => { RocketChat.getFullUserData = function({ userId, filter, limit: l }) { const username = s.trim(filter); - const userToRetrieveFullUserData = RocketChat.models.Users.findOneByUsername(username); + const userToRetrieveFullUserData = Users.findOneByUsername(username); const isMyOwnInfo = userToRetrieveFullUserData && userToRetrieveFullUserData._id === userId; - const viewFullOtherUserInfo = RocketChat.authz.hasPermission(userId, 'view-full-other-user-info'); + const viewFullOtherUserInfo = hasPermission(userId, 'view-full-other-user-info'); const limit = !viewFullOtherUserInfo ? 1 : l; if (!username && limit <= 1) { @@ -72,11 +75,11 @@ RocketChat.getFullUserData = function({ userId, filter, limit: l }) { }; if (!username) { - return RocketChat.models.Users.find({}, options); + return Users.find({}, options); } if (limit === 1) { - return RocketChat.models.Users.findByUsername(username, options); + return Users.findByUsername(username, options); } const usernameReg = new RegExp(s.escapeRegExp(username), 'i'); - return RocketChat.models.Users.findByUsernameNameOrEmailAddress(usernameReg, options); + return Users.findByUsernameNameOrEmailAddress(usernameReg, options); }; diff --git a/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js b/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js index 89a88f11ad53..5a0ff29f2ed5 100644 --- a/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js +++ b/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { Rooms, Users, Subscriptions } from 'meteor/rocketchat:models'; import _ from 'underscore'; RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOptionToJoin({ currentUserId, nameOrId, type = '', tryDirectByUserIdOnly = false, joinChannel = true, errorOnEmpty = true }) { @@ -7,22 +8,22 @@ RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOp // If the nameOrId starts with #, then let's try to find a channel or group if (nameOrId.startsWith('#')) { nameOrId = nameOrId.substring(1); - room = RocketChat.models.Rooms.findOneByIdOrName(nameOrId); + room = Rooms.findOneByIdOrName(nameOrId); } else if (nameOrId.startsWith('@') || type === 'd') { // If the nameOrId starts with @ OR type is 'd', then let's try just a direct message nameOrId = nameOrId.replace('@', ''); let roomUser; if (tryDirectByUserIdOnly) { - roomUser = RocketChat.models.Users.findOneById(nameOrId); + roomUser = Users.findOneById(nameOrId); } else { - roomUser = RocketChat.models.Users.findOne({ + roomUser = Users.findOne({ $or: [{ _id: nameOrId }, { username: nameOrId }], }); } const rid = _.isObject(roomUser) ? [currentUserId, roomUser._id].sort().join('') : nameOrId; - room = RocketChat.models.Rooms.findOneById(rid); + room = Rooms.findOneById(rid); // If the room hasn't been found yet, let's try some more if (!_.isObject(room)) { @@ -38,12 +39,12 @@ RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOp room = Meteor.runAsUser(currentUserId, function() { const { rid } = Meteor.call('createDirectMessage', roomUser.username); - return RocketChat.models.Rooms.findOneById(rid); + return Rooms.findOneById(rid); }); } } else { // Otherwise, we'll treat this as a channel or group. - room = RocketChat.models.Rooms.findOneByIdOrName(nameOrId); + room = Rooms.findOneByIdOrName(nameOrId); } // If no room was found, handle the room return based upon errorOnEmpty @@ -67,7 +68,7 @@ RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOp // If the room type is channel and joinChannel has been passed, try to join them // if they can't join the room, this will error out! if (room.t === 'c' && joinChannel) { - const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, currentUserId); + const sub = Subscriptions.findOneByRoomIdAndUserId(room._id, currentUserId); if (!sub) { Meteor.runAsUser(currentUserId, function() { diff --git a/packages/rocketchat-lib/server/functions/isTheLastMessage.js b/packages/rocketchat-lib/server/functions/isTheLastMessage.js index c2bc6d0717f2..5fe73fb08de6 100644 --- a/packages/rocketchat-lib/server/functions/isTheLastMessage.js +++ b/packages/rocketchat-lib/server/functions/isTheLastMessage.js @@ -1 +1,3 @@ -RocketChat.isTheLastMessage = (room, message) => RocketChat.settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id); +import { settings } from 'meteor/rocketchat:settings'; + +RocketChat.isTheLastMessage = (room, message) => settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id); diff --git a/packages/rocketchat-lib/server/functions/loadMessageHistory.js b/packages/rocketchat-lib/server/functions/loadMessageHistory.js index 3110114b2f60..873a5aff01d9 100644 --- a/packages/rocketchat-lib/server/functions/loadMessageHistory.js +++ b/packages/rocketchat-lib/server/functions/loadMessageHistory.js @@ -1,6 +1,10 @@ +import { settings } from 'meteor/rocketchat:settings'; +import { Messages } from 'meteor/rocketchat:models'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; + const hideMessagesOfType = []; -RocketChat.settings.get(/Message_HideType_.+/, function(key, value) { +settings.get(/Message_HideType_.+/, function(key, value) { const type = key.replace('Message_HideType_', ''); const types = type === 'mute_unmute' ? ['user-muted', 'user-unmuted'] : [type]; @@ -25,7 +29,7 @@ RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, limit, }; - if (!RocketChat.settings.get('Message_ShowEditedStatus')) { + if (!settings.get('Message_ShowEditedStatus')) { options.fields = { editedAt: 0, }; @@ -33,11 +37,11 @@ RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, let records; if (end != null) { - records = RocketChat.models.Messages.findVisibleByRoomIdBeforeTimestampNotContainingTypes(rid, end, hideMessagesOfType, options).fetch(); + records = Messages.findVisibleByRoomIdBeforeTimestampNotContainingTypes(rid, end, hideMessagesOfType, options).fetch(); } else { - records = RocketChat.models.Messages.findVisibleByRoomIdNotContainingTypes(rid, hideMessagesOfType, options).fetch(); + records = Messages.findVisibleByRoomIdNotContainingTypes(rid, hideMessagesOfType, options).fetch(); } - const messages = records.map((record) => RocketChat.composeMessageObjectWithUser(record, userId)); + const messages = records.map((record) => composeMessageObjectWithUser(record, userId)); let unreadNotLoaded = 0; let firstUnread; @@ -47,7 +51,7 @@ RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, if ((firstMessage != null ? firstMessage.ts : undefined) > ls) { delete options.limit; - const unreadMessages = RocketChat.models.Messages.findVisibleByRoomIdBetweenTimestampsNotContainingTypes(rid, ls, firstMessage.ts, hideMessagesOfType, { + const unreadMessages = Messages.findVisibleByRoomIdBetweenTimestampsNotContainingTypes(rid, ls, firstMessage.ts, hideMessagesOfType, { limit: 1, sort: { ts: 1, diff --git a/packages/rocketchat-lib/server/functions/notifications/audio.js b/packages/rocketchat-lib/server/functions/notifications/audio.js index 44b89a4acc64..737fbe219619 100644 --- a/packages/rocketchat-lib/server/functions/notifications/audio.js +++ b/packages/rocketchat-lib/server/functions/notifications/audio.js @@ -1,3 +1,7 @@ +import { metrics } from 'meteor/rocketchat:metrics'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; + export function shouldNotifyAudio({ disableAllMessageNotifications, status, @@ -17,7 +21,7 @@ export function shouldNotifyAudio({ return false; } - if (!audioNotifications && RocketChat.settings.get('Accounts_Default_User_Preferences_audioNotifications') === 'all') { + if (!audioNotifications && settings.get('Accounts_Default_User_Preferences_audioNotifications') === 'all') { return true; } @@ -25,8 +29,8 @@ export function shouldNotifyAudio({ } export function notifyAudioUser(userId, message, room) { - RocketChat.metrics.notificationsSent.inc({ notification_type: 'audio' }); - RocketChat.Notifications.notifyUser(userId, 'audioNotification', { + metrics.notificationsSent.inc({ notification_type: 'audio' }); + Notifications.notifyUser(userId, 'audioNotification', { payload: { _id: message._id, rid: message.rid, diff --git a/packages/rocketchat-lib/server/functions/notifications/desktop.js b/packages/rocketchat-lib/server/functions/notifications/desktop.js index 9ed6e61b1331..d95c833f6240 100644 --- a/packages/rocketchat-lib/server/functions/notifications/desktop.js +++ b/packages/rocketchat-lib/server/functions/notifications/desktop.js @@ -1,3 +1,7 @@ +import { metrics } from 'meteor/rocketchat:metrics'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { roomTypes } from 'meteor/rocketchat:utils'; /** * Send notification to user * @@ -16,10 +20,10 @@ export function notifyDesktopUser({ duration, notificationMessage, }) { - const { title, text } = RocketChat.roomTypes.getConfig(room.t).getNotificationDetails(room, user, notificationMessage); + const { title, text } = roomTypes.getConfig(room.t).getNotificationDetails(room, user, notificationMessage); - RocketChat.metrics.notificationsSent.inc({ notification_type: 'desktop' }); - RocketChat.Notifications.notifyUser(userId, 'notification', { + metrics.notificationsSent.inc({ notification_type: 'desktop' }); + Notifications.notifyUser(userId, 'notification', { title, text, duration, @@ -57,10 +61,10 @@ export function shouldNotifyDesktop({ } if (!desktopNotifications) { - if (RocketChat.settings.get('Accounts_Default_User_Preferences_desktopNotifications') === 'all') { + if (settings.get('Accounts_Default_User_Preferences_desktopNotifications') === 'all') { return true; } - if (RocketChat.settings.get('Accounts_Default_User_Preferences_desktopNotifications') === 'nothing') { + if (settings.get('Accounts_Default_User_Preferences_desktopNotifications') === 'nothing') { return false; } } diff --git a/packages/rocketchat-lib/server/functions/notifications/email.js b/packages/rocketchat-lib/server/functions/notifications/email.js index 98abcff2b18a..64ed6e2c7968 100644 --- a/packages/rocketchat-lib/server/functions/notifications/email.js +++ b/packages/rocketchat-lib/server/functions/notifications/email.js @@ -2,11 +2,15 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; import s from 'underscore.string'; import * as Mailer from 'meteor/rocketchat:mailer'; +import { settings } from 'meteor/rocketchat:settings'; +import { roomTypes } from 'meteor/rocketchat:utils'; +import { metrics } from 'meteor/rocketchat:metrics'; +import { callbacks } from 'meteor/rocketchat:callbacks'; let advice = ''; let goToMessage = ''; Meteor.startup(() => { - RocketChat.settings.get('email_style', function() { + settings.get('email_style', function() { goToMessage = Mailer.inlinecss('

{Offline_Link_Message}

'); }); Mailer.getTemplate('Email_Footer_Direct_Reply', (value) => { @@ -15,10 +19,10 @@ Meteor.startup(() => { }); function getEmailContent({ message, user, room }) { - const lng = (user && user.language) || RocketChat.settings.get('language') || 'en'; + const lng = (user && user.language) || settings.get('language') || 'en'; - const roomName = s.escapeHTML(`#${ RocketChat.roomTypes.getRoomName(room.t, room) }`); - const userName = s.escapeHTML(RocketChat.settings.get('UI_Use_Real_Name') ? message.u.name || message.u.username : message.u.username); + const roomName = s.escapeHTML(`#${ roomTypes.getRoomName(room.t, room) }`); + const userName = s.escapeHTML(settings.get('UI_Use_Real_Name') ? message.u.name || message.u.username : message.u.username); const header = TAPi18n.__(room.t === 'd' ? 'User_sent_a_message_to_you' : 'User_sent_a_message_on_channel', { username: userName, @@ -33,7 +37,7 @@ function getEmailContent({ message, user, room }) { messageContent = TAPi18n.__('Encrypted_message', { lng }); } - message = RocketChat.callbacks.run('renderMessage', message); + message = callbacks.run('renderMessage', message); if (message.tokens && message.tokens.length > 0) { message.tokens.forEach((token) => { token.text = token.text.replace(/([^\$])(\$[^\$])/gm, '$1$$$2'); @@ -78,7 +82,7 @@ function getEmailContent({ message, user, room }) { } export function sendEmail({ message, user, subscription, room, emailAddress, hasMentionToUser }) { - const username = RocketChat.settings.get('UI_Use_Real_Name') ? message.u.name : message.u.username; + const username = settings.get('UI_Use_Real_Name') ? message.u.name : message.u.username; let subjectKey = 'Offline_Mention_All_Email'; if (room.t === 'd') { @@ -87,9 +91,9 @@ export function sendEmail({ message, user, subscription, room, emailAddress, has subjectKey = 'Offline_Mention_Email'; } - const emailSubject = Mailer.replace(RocketChat.settings.get(subjectKey), { + const emailSubject = Mailer.replace(settings.get(subjectKey), { user: username, - room: RocketChat.roomTypes.getRoomName(room.t, room), + room: roomTypes.getRoomName(room.t, room), }); const content = getEmailContent({ message, @@ -97,29 +101,29 @@ export function sendEmail({ message, user, subscription, room, emailAddress, has room, }); - const room_path = RocketChat.roomTypes.getURL(room.t, subscription); + const room_path = roomTypes.getURL(room.t, subscription); const email = { to: emailAddress, subject: emailSubject, - html: content + goToMessage + (RocketChat.settings.get('Direct_Reply_Enable') ? advice : ''), + html: content + goToMessage + (settings.get('Direct_Reply_Enable') ? advice : ''), data: { room_path, }, }; const from = room.t === 'd' ? message.u.name : room.name; // using user full-name/channel name in from address - email.from = `${ String(from).replace(/@/g, '%40').replace(/[<>,]/g, '') } <${ RocketChat.settings.get('From_Email') }>`; + email.from = `${ String(from).replace(/@/g, '%40').replace(/[<>,]/g, '') } <${ settings.get('From_Email') }>`; // If direct reply enabled, email content with headers - if (RocketChat.settings.get('Direct_Reply_Enable')) { - const replyto = RocketChat.settings.get('Direct_Reply_ReplyTo') || RocketChat.settings.get('Direct_Reply_Username'); + if (settings.get('Direct_Reply_Enable')) { + const replyto = settings.get('Direct_Reply_ReplyTo') || settings.get('Direct_Reply_Username'); email.headers = { // Reply-To header with format "username+messageId@domain" - 'Reply-To': `${ replyto.split('@')[0].split(RocketChat.settings.get('Direct_Reply_Separator'))[0] }${ RocketChat.settings.get('Direct_Reply_Separator') }${ message._id }@${ replyto.split('@')[1] }`, + 'Reply-To': `${ replyto.split('@')[0].split(settings.get('Direct_Reply_Separator'))[0] }${ settings.get('Direct_Reply_Separator') }${ message._id }@${ replyto.split('@')[1] }`, }; } - RocketChat.metrics.notificationsSent.inc({ notification_type: 'email' }); + metrics.notificationsSent.inc({ notification_type: 'email' }); return Mailer.send(email); } @@ -150,7 +154,7 @@ export function shouldNotifyEmail({ } // default server preference is disabled - if (RocketChat.settings.get('Accounts_Default_User_Preferences_emailNotificationMode') === 'nothing') { + if (settings.get('Accounts_Default_User_Preferences_emailNotificationMode') === 'nothing') { return false; } } diff --git a/packages/rocketchat-lib/server/functions/notifications/index.js b/packages/rocketchat-lib/server/functions/notifications/index.js index e2316590a351..8d71d8b28240 100644 --- a/packages/rocketchat-lib/server/functions/notifications/index.js +++ b/packages/rocketchat-lib/server/functions/notifications/index.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; +import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; /** @@ -9,13 +10,13 @@ import s from 'underscore.string'; */ export function parseMessageTextPerUser(messageText, message, receiver) { if (!message.msg && message.attachments && message.attachments[0]) { - const lng = receiver.language || RocketChat.settings.get('language') || 'en'; + const lng = receiver.language || settings.get('language') || 'en'; return message.attachments[0].image_type ? TAPi18n.__('User_uploaded_image', { lng }) : TAPi18n.__('User_uploaded_file', { lng }); } if (message.msg && message.t === 'e2e') { - const lng = receiver.language || RocketChat.settings.get('language') || 'en'; + const lng = receiver.language || settings.get('language') || 'en'; return TAPi18n.__('Encrypted_message', { lng }); } diff --git a/packages/rocketchat-lib/server/functions/notifications/mobile.js b/packages/rocketchat-lib/server/functions/notifications/mobile.js index 9bcf0ac494af..4460f4106eb4 100644 --- a/packages/rocketchat-lib/server/functions/notifications/mobile.js +++ b/packages/rocketchat-lib/server/functions/notifications/mobile.js @@ -1,16 +1,20 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { roomTypes } from 'meteor/rocketchat:utils'; +import { PushNotification } from 'meteor/rocketchat:push-notifications'; const CATEGORY_MESSAGE = 'MESSAGE'; const CATEGORY_MESSAGE_NOREPLY = 'MESSAGE_NOREPLY'; let alwaysNotifyMobileBoolean; -RocketChat.settings.get('Notifications_Always_Notify_Mobile', (key, value) => { +settings.get('Notifications_Always_Notify_Mobile', (key, value) => { alwaysNotifyMobileBoolean = value; }); let SubscriptionRaw; Meteor.startup(() => { - SubscriptionRaw = RocketChat.models.Subscriptions.model.rawCollection(); + SubscriptionRaw = Subscriptions.model.rawCollection(); }); async function getBadgeCount(userId) { @@ -34,11 +38,11 @@ function canSendMessageToRoom(room, username) { export async function sendSinglePush({ room, message, userId, receiverUsername, senderUsername, senderName, notificationMessage }) { let username = ''; - if (RocketChat.settings.get('Push_show_username_room')) { - username = RocketChat.settings.get('UI_Use_Real_Name') === true ? senderName : senderUsername; + if (settings.get('Push_show_username_room')) { + username = settings.get('UI_Use_Real_Name') === true ? senderName : senderUsername; } - RocketChat.PushNotification.send({ + PushNotification.send({ roomId: message.rid, payload: { host: Meteor.absoluteUrl(), @@ -49,9 +53,9 @@ export async function sendSinglePush({ room, message, userId, receiverUsername, messageType: message.t, messageId: message._id, }, - roomName: RocketChat.settings.get('Push_show_username_room') && room.t !== 'd' ? `#${ RocketChat.roomTypes.getRoomName(room.t, room) }` : '', + roomName: settings.get('Push_show_username_room') && room.t !== 'd' ? `#${ roomTypes.getRoomName(room.t, room) }` : '', username, - message: RocketChat.settings.get('Push_show_message') ? notificationMessage : ' ', + message: settings.get('Push_show_message') ? notificationMessage : ' ', badge: await getBadgeCount(userId), usersTo: { userId, @@ -82,10 +86,10 @@ export function shouldNotifyMobile({ } if (!mobilePushNotifications) { - if (RocketChat.settings.get('Accounts_Default_User_Preferences_mobileNotifications') === 'all') { + if (settings.get('Accounts_Default_User_Preferences_mobileNotifications') === 'all') { return true; } - if (RocketChat.settings.get('Accounts_Default_User_Preferences_mobileNotifications') === 'nothing') { + if (settings.get('Accounts_Default_User_Preferences_mobileNotifications') === 'nothing') { return false; } } diff --git a/packages/rocketchat-lib/server/functions/removeUserFromRoom.js b/packages/rocketchat-lib/server/functions/removeUserFromRoom.js index f09aea6ad2ed..2eb8ceed6737 100644 --- a/packages/rocketchat-lib/server/functions/removeUserFromRoom.js +++ b/packages/rocketchat-lib/server/functions/removeUserFromRoom.js @@ -1,27 +1,29 @@ import { Meteor } from 'meteor/meteor'; +import { Rooms, Messages, Subscriptions } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.removeUserFromRoom = function(rid, user) { - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (room) { - RocketChat.callbacks.run('beforeLeaveRoom', user, room); + callbacks.run('beforeLeaveRoom', user, room); - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id, { fields: { _id: 1 } }); if (subscription) { const removedUser = user; - RocketChat.models.Messages.createUserLeaveWithRoomIdAndUser(rid, removedUser); + Messages.createUserLeaveWithRoomIdAndUser(rid, removedUser); } if (room.t === 'l') { - RocketChat.models.Messages.createCommandWithRoomIdAndUser('survey', rid, user); + Messages.createCommandWithRoomIdAndUser('survey', rid, user); } - RocketChat.models.Subscriptions.removeByRoomIdAndUserId(rid, user._id); + Subscriptions.removeByRoomIdAndUserId(rid, user._id); Meteor.defer(function() { // TODO: CACHE: maybe a queue? - RocketChat.callbacks.run('afterLeaveRoom', user, room); + callbacks.run('afterLeaveRoom', user, room); }); } }; diff --git a/packages/rocketchat-lib/server/functions/saveCustomFields.js b/packages/rocketchat-lib/server/functions/saveCustomFields.js index 7336a6056c53..86f9f3dab82a 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFields.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFields.js @@ -1,7 +1,8 @@ +import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; RocketChat.saveCustomFields = function(userId, formData) { - if (s.trim(RocketChat.settings.get('Accounts_CustomFields')) !== '') { + if (s.trim(settings.get('Accounts_CustomFields')) !== '') { RocketChat.validateCustomFields(formData); return RocketChat.saveCustomFieldsWithoutValidation(userId, formData); } diff --git a/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js b/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js index f1c418193a34..e73019e5c14f 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js @@ -1,21 +1,23 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users, Subscriptions } from 'meteor/rocketchat:models'; import s from 'underscore.string'; RocketChat.saveCustomFieldsWithoutValidation = function(userId, formData) { - if (s.trim(RocketChat.settings.get('Accounts_CustomFields')) !== '') { + if (s.trim(settings.get('Accounts_CustomFields')) !== '') { let customFieldsMeta; try { - customFieldsMeta = JSON.parse(RocketChat.settings.get('Accounts_CustomFields')); + customFieldsMeta = JSON.parse(settings.get('Accounts_CustomFields')); } catch (e) { throw new Meteor.Error('error-invalid-customfield-json', 'Invalid JSON for Custom Fields'); } const customFields = {}; Object.keys(customFieldsMeta).forEach((key) => customFields[key] = formData[key]); - RocketChat.models.Users.setCustomFields(userId, customFields); + Users.setCustomFields(userId, customFields); // Update customFields of all Direct Messages' Rooms for userId - RocketChat.models.Subscriptions.setCustomFieldsDirectMessagesByUserId(userId, customFields); + Subscriptions.setCustomFieldsDirectMessagesByUserId(userId, customFields); Object.keys(customFields).forEach((fieldName) => { if (!customFieldsMeta[fieldName].modifyRecordField) { @@ -32,7 +34,7 @@ RocketChat.saveCustomFieldsWithoutValidation = function(userId, formData) { update.$set[modifyRecordField.field] = customFields[fieldName]; } - RocketChat.models.Users.update(userId, update); + Users.update(userId, update); }); } }; diff --git a/packages/rocketchat-lib/server/functions/saveUser.js b/packages/rocketchat-lib/server/functions/saveUser.js index e165382816cc..14aa68429611 100644 --- a/packages/rocketchat-lib/server/functions/saveUser.js +++ b/packages/rocketchat-lib/server/functions/saveUser.js @@ -4,6 +4,11 @@ import _ from 'underscore'; import s from 'underscore.string'; import * as Mailer from 'meteor/rocketchat:mailer'; import { Gravatar } from 'meteor/jparker:gravatar'; +import { getRoles, hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import PasswordPolicy from '../lib/PasswordPolicyClass'; + +const passwordPolicy = new PasswordPolicy(); let html = ''; Meteor.startup(() => { @@ -13,16 +18,16 @@ Meteor.startup(() => { }); function validateUserData(userId, userData) { - const existingRoles = _.pluck(RocketChat.authz.getRoles(), '_id'); + const existingRoles = _.pluck(getRoles(), '_id'); - if (userData._id && userId !== userData._id && !RocketChat.authz.hasPermission(userId, 'edit-other-user-info')) { + if (userData._id && userId !== userData._id && !hasPermission(userId, 'edit-other-user-info')) { throw new Meteor.Error('error-action-not-allowed', 'Editing user is not allowed', { method: 'insertOrUpdateUser', action: 'Editing_user', }); } - if (!userData._id && !RocketChat.authz.hasPermission(userId, 'create-user')) { + if (!userData._id && !hasPermission(userId, 'create-user')) { throw new Meteor.Error('error-action-not-allowed', 'Adding user is not allowed', { method: 'insertOrUpdateUser', action: 'Adding_user', @@ -36,7 +41,7 @@ function validateUserData(userId, userData) { }); } - if (userData.roles && _.indexOf(userData.roles, 'admin') >= 0 && !RocketChat.authz.hasPermission(userId, 'assign-admin-role')) { + if (userData.roles && _.indexOf(userData.roles, 'admin') >= 0 && !hasPermission(userId, 'assign-admin-role')) { throw new Meteor.Error('error-action-not-allowed', 'Assigning admin is not allowed', { method: 'insertOrUpdateUser', action: 'Assign_admin', @@ -60,7 +65,7 @@ function validateUserData(userId, userData) { let nameValidation; try { - nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + nameValidation = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); } catch (e) { nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$'); } @@ -100,38 +105,38 @@ function validateUserData(userId, userData) { function validateUserEditing(userId, userData) { const editingMyself = userData._id && userId === userData._id; - const canEditOtherUserInfo = RocketChat.authz.hasPermission(userId, 'edit-other-user-info'); - const canEditOtherUserPassword = RocketChat.authz.hasPermission(userId, 'edit-other-user-password'); + const canEditOtherUserInfo = hasPermission(userId, 'edit-other-user-info'); + const canEditOtherUserPassword = hasPermission(userId, 'edit-other-user-password'); - if (!RocketChat.settings.get('Accounts_AllowUserProfileChange') && !canEditOtherUserInfo && !canEditOtherUserPassword) { + if (!settings.get('Accounts_AllowUserProfileChange') && !canEditOtherUserInfo && !canEditOtherUserPassword) { throw new Meteor.Error('error-action-not-allowed', 'Edit user profile is not allowed', { method: 'insertOrUpdateUser', action: 'Update_user', }); } - if (userData.username && !RocketChat.settings.get('Accounts_AllowUsernameChange') && (!canEditOtherUserInfo || editingMyself)) { + if (userData.username && !settings.get('Accounts_AllowUsernameChange') && (!canEditOtherUserInfo || editingMyself)) { throw new Meteor.Error('error-action-not-allowed', 'Edit username is not allowed', { method: 'insertOrUpdateUser', action: 'Update_user', }); } - if (userData.name && !RocketChat.settings.get('Accounts_AllowRealNameChange') && (!canEditOtherUserInfo || editingMyself)) { + if (userData.name && !settings.get('Accounts_AllowRealNameChange') && (!canEditOtherUserInfo || editingMyself)) { throw new Meteor.Error('error-action-not-allowed', 'Edit user real name is not allowed', { method: 'insertOrUpdateUser', action: 'Update_user', }); } - if (userData.email && !RocketChat.settings.get('Accounts_AllowEmailChange') && (!canEditOtherUserInfo || editingMyself)) { + if (userData.email && !settings.get('Accounts_AllowEmailChange') && (!canEditOtherUserInfo || editingMyself)) { throw new Meteor.Error('error-action-not-allowed', 'Edit user email is not allowed', { method: 'insertOrUpdateUser', action: 'Update_user', }); } - if (userData.password && !RocketChat.settings.get('Accounts_AllowPasswordChange') && (!canEditOtherUserPassword || editingMyself)) { + if (userData.password && !settings.get('Accounts_AllowPasswordChange') && (!canEditOtherUserPassword || editingMyself)) { throw new Meteor.Error('error-action-not-allowed', 'Edit user password is not allowed', { method: 'insertOrUpdateUser', action: 'Update_user', @@ -176,11 +181,11 @@ RocketChat.saveUser = function(userId, userData) { Meteor.users.update({ _id }, updateUser); if (userData.sendWelcomeEmail) { - const subject = RocketChat.settings.get('Accounts_UserAddedEmail_Subject'); + const subject = settings.get('Accounts_UserAddedEmail_Subject'); const email = { to: userData.email, - from: RocketChat.settings.get('From_Email'), + from: settings.get('From_Email'), subject, html, data: { @@ -202,7 +207,7 @@ RocketChat.saveUser = function(userId, userData) { userData._id = _id; - if (RocketChat.settings.get('Accounts_SetDefaultAvatar') === true && userData.email) { + if (settings.get('Accounts_SetDefaultAvatar') === true && userData.email) { const gravatarUrl = Gravatar.imageUrl(userData.email, { default: '404', size: 200, secure: true }); try { @@ -231,7 +236,7 @@ RocketChat.saveUser = function(userId, userData) { RocketChat.setEmail(userData._id, userData.email, shouldSendVerificationEmailToUser); } - if (userData.password && userData.password.trim() && RocketChat.authz.hasPermission(userId, 'edit-other-user-password') && RocketChat.passwordPolicy.validate(userData.password)) { + if (userData.password && userData.password.trim() && hasPermission(userId, 'edit-other-user-password') && passwordPolicy.validate(userData.password)) { Accounts.setPassword(userData._id, userData.password.trim()); } diff --git a/packages/rocketchat-lib/server/functions/sendMessage.js b/packages/rocketchat-lib/server/functions/sendMessage.js index 4a5218e7ad65..952b27895100 100644 --- a/packages/rocketchat-lib/server/functions/sendMessage.js +++ b/packages/rocketchat-lib/server/functions/sendMessage.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Messages } from 'meteor/rocketchat:models'; const objectMaybeIncluding = (types) => Match.Where((value) => { Object.keys(types).forEach((field) => { @@ -113,7 +116,7 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) { message.ts = new Date(); } - if (RocketChat.settings.get('Message_Read_Receipt_Enabled')) { + if (settings.get('Message_Read_Receipt_Enabled')) { message.unread = true; } @@ -148,7 +151,7 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) { delete message.tokens; } - message = RocketChat.callbacks.run('beforeSaveMessage', message); + message = callbacks.run('beforeSaveMessage', message); if (message) { // Avoid saving sandstormSessionId to the database let sandstormSessionId = null; @@ -160,13 +163,13 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) { if (message._id && upsert) { const { _id } = message; delete message._id; - RocketChat.models.Messages.upsert({ + Messages.upsert({ _id, 'u._id': message.u._id, }, message); message._id = _id; } else { - message._id = RocketChat.models.Messages.insert(message); + message._id = Messages.insert(message); } if (Apps && Apps.isLoaded()) { @@ -181,7 +184,7 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) { Meteor.defer(() => { // Execute all callbacks message.sandstormSessionId = sandstormSessionId; - return RocketChat.callbacks.run('afterSaveMessage', message, room, user._id); + return callbacks.run('afterSaveMessage', message, room, user._id); }); return message; } diff --git a/packages/rocketchat-lib/server/functions/setEmail.js b/packages/rocketchat-lib/server/functions/setEmail.js index e947d5bfa514..ad05ef2fe3d7 100644 --- a/packages/rocketchat-lib/server/functions/setEmail.js +++ b/packages/rocketchat-lib/server/functions/setEmail.js @@ -1,4 +1,6 @@ import { Meteor } from 'meteor/meteor'; +import { Users } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import s from 'underscore.string'; RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = true) { @@ -13,7 +15,7 @@ RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = tru RocketChat.validateEmailDomain(email); - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); // User already has desired username, return if (user.emails && user.emails[0] && user.emails[0].address === email) { @@ -26,7 +28,7 @@ RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = tru } // Set new email - RocketChat.models.Users.setEmail(user._id, email); + Users.setEmail(user._id, email); user.email = email; if (shouldSendVerificationEmail === true) { Meteor.call('sendConfirmationEmail', user.email); @@ -35,5 +37,5 @@ RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = tru }; RocketChat.setEmail = RocketChat.RateLimiter.limitFunction(RocketChat._setEmail, 1, 60000, { - 0() { return !Meteor.userId() || !RocketChat.authz.hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others emails, so don't limit those + 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others emails, so don't limit those }); diff --git a/packages/rocketchat-lib/server/functions/setRealName.js b/packages/rocketchat-lib/server/functions/setRealName.js index 6bf2f183ef75..0cfac9bf3f87 100644 --- a/packages/rocketchat-lib/server/functions/setRealName.js +++ b/packages/rocketchat-lib/server/functions/setRealName.js @@ -1,4 +1,8 @@ import { Meteor } from 'meteor/meteor'; +import { Users, Subscriptions } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import s from 'underscore.string'; RocketChat._setRealName = function(userId, name) { @@ -7,7 +11,7 @@ RocketChat._setRealName = function(userId, name) { return false; } - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); // User already has desired name, return if (user.name === name) { @@ -15,13 +19,13 @@ RocketChat._setRealName = function(userId, name) { } // Set new name - RocketChat.models.Users.setName(user._id, name); + Users.setName(user._id, name); user.name = name; - RocketChat.models.Subscriptions.updateDirectFNameByName(user.username, name); + Subscriptions.updateDirectFNameByName(user.username, name); - if (RocketChat.settings.get('UI_Use_Real_Name') === true) { - RocketChat.Notifications.notifyLogged('Users:NameChanged', { + if (settings.get('UI_Use_Real_Name') === true) { + Notifications.notifyLogged('Users:NameChanged', { _id: user._id, name: user.name, username: user.username, @@ -32,5 +36,5 @@ RocketChat._setRealName = function(userId, name) { }; RocketChat.setRealName = RocketChat.RateLimiter.limitFunction(RocketChat._setRealName, 1, 60000, { - 0() { return !Meteor.userId() || !RocketChat.authz.hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others names, so don't limit those + 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others names, so don't limit those }); diff --git a/packages/rocketchat-lib/server/functions/setUserAvatar.js b/packages/rocketchat-lib/server/functions/setUserAvatar.js index df3b2e888cdb..4335123d0983 100644 --- a/packages/rocketchat-lib/server/functions/setUserAvatar.js +++ b/packages/rocketchat-lib/server/functions/setUserAvatar.js @@ -2,13 +2,15 @@ import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; import { RocketChatFile } from 'meteor/rocketchat:file'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { Users } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; RocketChat.setUserAvatar = function(user, dataURI, contentType, service) { let encoding; let image; if (service === 'initials') { - return RocketChat.models.Users.setAvatarOrigin(user._id, service); + return Users.setAvatarOrigin(user._id, service); } else if (service === 'url') { let result = null; @@ -56,8 +58,8 @@ RocketChat.setUserAvatar = function(user, dataURI, contentType, service) { fileStore.insert(file, buffer, () => { Meteor.setTimeout(function() { - RocketChat.models.Users.setAvatarOrigin(user._id, service); - RocketChat.Notifications.notifyLogged('updateAvatar', { username: user.username }); + Users.setAvatarOrigin(user._id, service); + Notifications.notifyLogged('updateAvatar', { username: user.username }); }, 500); }); }; diff --git a/packages/rocketchat-lib/server/functions/setUsername.js b/packages/rocketchat-lib/server/functions/setUsername.js index a0d45b3f03d6..6003a7abaa45 100644 --- a/packages/rocketchat-lib/server/functions/setUsername.js +++ b/packages/rocketchat-lib/server/functions/setUsername.js @@ -1,6 +1,9 @@ import s from 'underscore.string'; import { Accounts } from 'meteor/accounts-base'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users, Messages, Subscriptions, Rooms } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; RocketChat._setUsername = function(userId, u) { const username = s.trim(u); @@ -9,14 +12,14 @@ RocketChat._setUsername = function(userId, u) { } let nameValidation; try { - nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + nameValidation = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); } catch (error) { nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$'); } if (!nameValidation.test(username)) { return false; } - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); // User already has desired username, return if (user.username === username) { return user; @@ -30,16 +33,16 @@ RocketChat._setUsername = function(userId, u) { } // If first time setting username, send Enrollment Email try { - if (!previousUsername && user.emails && user.emails.length > 0 && RocketChat.settings.get('Accounts_Enrollment_Email')) { + if (!previousUsername && user.emails && user.emails.length > 0 && settings.get('Accounts_Enrollment_Email')) { Accounts.sendEnrollmentEmail(user._id); } } catch (e) { console.error(e); } // Set new username* - RocketChat.models.Users.setUsername(user._id, username); + Users.setUsername(user._id, username); user.username = username; - if (!previousUsername && RocketChat.settings.get('Accounts_SetDefaultAvatar') === true) { + if (!previousUsername && settings.get('Accounts_SetDefaultAvatar') === true) { const avatarSuggestions = getAvatarSuggestionForUser(user); let gravatar; Object.keys(avatarSuggestions).some((service) => { @@ -58,17 +61,17 @@ RocketChat._setUsername = function(userId, u) { } // Username is available; if coming from old username, update all references if (previousUsername) { - RocketChat.models.Messages.updateAllUsernamesByUserId(user._id, username); - RocketChat.models.Messages.updateUsernameOfEditByUserId(user._id, username); - RocketChat.models.Messages.findByMention(previousUsername).forEach(function(msg) { + Messages.updateAllUsernamesByUserId(user._id, username); + Messages.updateUsernameOfEditByUserId(user._id, username); + Messages.findByMention(previousUsername).forEach(function(msg) { const updatedMsg = msg.msg.replace(new RegExp(`@${ previousUsername }`, 'ig'), `@${ username }`); - return RocketChat.models.Messages.updateUsernameAndMessageOfMentionByIdAndOldUsername(msg._id, previousUsername, username, updatedMsg); + return Messages.updateUsernameAndMessageOfMentionByIdAndOldUsername(msg._id, previousUsername, username, updatedMsg); }); - RocketChat.models.Rooms.replaceUsername(previousUsername, username); - RocketChat.models.Rooms.replaceMutedUsername(previousUsername, username); - RocketChat.models.Rooms.replaceUsernameOfUserByUserId(user._id, username); - RocketChat.models.Subscriptions.setUserUsernameByUserId(user._id, username); - RocketChat.models.Subscriptions.setNameForDirectRoomsWithOldName(previousUsername, username); + Rooms.replaceUsername(previousUsername, username); + Rooms.replaceMutedUsername(previousUsername, username); + Rooms.replaceUsernameOfUserByUserId(user._id, username); + Subscriptions.setUserUsernameByUserId(user._id, username); + Subscriptions.setNameForDirectRoomsWithOldName(previousUsername, username); RocketChat.models.LivechatDepartmentAgents.replaceUsernameOfAgentByUserId(user._id, username); const fileStore = FileUpload.getStore('Avatars'); @@ -82,6 +85,6 @@ RocketChat._setUsername = function(userId, u) { RocketChat.setUsername = RocketChat.RateLimiter.limitFunction(RocketChat._setUsername, 1, 60000, { [0](userId) { - return !userId || !RocketChat.authz.hasPermission(userId, 'edit-other-user-info'); + return !userId || !hasPermission(userId, 'edit-other-user-info'); }, }); diff --git a/packages/rocketchat-lib/server/functions/unarchiveRoom.js b/packages/rocketchat-lib/server/functions/unarchiveRoom.js index 3884e06c4041..9cce78e07e1d 100644 --- a/packages/rocketchat-lib/server/functions/unarchiveRoom.js +++ b/packages/rocketchat-lib/server/functions/unarchiveRoom.js @@ -1,4 +1,6 @@ +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; + RocketChat.unarchiveRoom = function(rid) { - RocketChat.models.Rooms.unarchiveById(rid); - RocketChat.models.Subscriptions.unarchiveByRoomId(rid); + Rooms.unarchiveById(rid); + Subscriptions.unarchiveByRoomId(rid); }; diff --git a/packages/rocketchat-lib/server/functions/updateMessage.js b/packages/rocketchat-lib/server/functions/updateMessage.js index 950454594c95..82158b41dc12 100644 --- a/packages/rocketchat-lib/server/functions/updateMessage.js +++ b/packages/rocketchat-lib/server/functions/updateMessage.js @@ -1,8 +1,11 @@ import { Meteor } from 'meteor/meteor'; +import { Messages, Rooms } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.updateMessage = function(message, user, originalMessage) { if (!originalMessage) { - originalMessage = RocketChat.models.Messages.findOneById(message._id); + originalMessage = Messages.findOneById(message._id); } // For the Rocket.Chat Apps :) @@ -24,8 +27,8 @@ RocketChat.updateMessage = function(message, user, originalMessage) { } // If we keep history of edits, insert a new message to store history information - if (RocketChat.settings.get('Message_KeepHistory')) { - RocketChat.models.Messages.cloneAndSaveAsHistoryById(message._id); + if (settings.get('Message_KeepHistory')) { + Messages.cloneAndSaveAsHistoryById(message._id); } message.editedAt = new Date(); @@ -37,14 +40,14 @@ RocketChat.updateMessage = function(message, user, originalMessage) { const urls = message.msg.match(/([A-Za-z]{3,9}):\/\/([-;:&=\+\$,\w]+@{1})?([-A-Za-z0-9\.]+)+:?(\d+)?((\/[-\+=!:~%\/\.@\,\w]*)?\??([-\+=&!:;%@\/\.\,\w]+)?(?:#([^\s\)]+))?)?/g) || []; message.urls = urls.map((url) => ({ url })); - message = RocketChat.callbacks.run('beforeSaveMessage', message); + message = callbacks.run('beforeSaveMessage', message); const tempid = message._id; delete message._id; - RocketChat.models.Messages.update({ _id: tempid }, { $set: message }); + Messages.update({ _id: tempid }, { $set: message }); - const room = RocketChat.models.Rooms.findOneById(message.rid); + const room = Rooms.findOneById(message.rid); if (Apps && Apps.isLoaded()) { // This returns a promise, but it won't mutate anything about the message @@ -53,6 +56,6 @@ RocketChat.updateMessage = function(message, user, originalMessage) { } Meteor.defer(function() { - RocketChat.callbacks.run('afterSaveMessage', RocketChat.models.Messages.findOneById(tempid), room, user._id); + callbacks.run('afterSaveMessage', Messages.findOneById(tempid), room, user._id); }); }; diff --git a/packages/rocketchat-lib/server/functions/validateCustomFields.js b/packages/rocketchat-lib/server/functions/validateCustomFields.js index 26ccace4102b..f2d5bff1aba5 100644 --- a/packages/rocketchat-lib/server/functions/validateCustomFields.js +++ b/packages/rocketchat-lib/server/functions/validateCustomFields.js @@ -1,16 +1,17 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; RocketChat.validateCustomFields = function(fields) { // Special Case: // If an admin didn't set any custom fields there's nothing to validate against so consider any customFields valid - if (s.trim(RocketChat.settings.get('Accounts_CustomFields')) === '') { + if (s.trim(settings.get('Accounts_CustomFields')) === '') { return; } let customFieldsMeta; try { - customFieldsMeta = JSON.parse(RocketChat.settings.get('Accounts_CustomFields')); + customFieldsMeta = JSON.parse(settings.get('Accounts_CustomFields')); } catch (e) { throw new Meteor.Error('error-invalid-customfield-json', 'Invalid JSON for Custom Fields'); } From d49540b4589be630fab2b1974cb8ef5f093907a8 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 10:13:41 -0200 Subject: [PATCH 05/18] Import variables to remove RC namespace dependency inside rc-lib/server/lib --- packages/rocketchat-lib/server/lib/bugsnag.js | 8 ++-- .../rocketchat-lib/server/lib/configLogger.js | 7 ++-- packages/rocketchat-lib/server/lib/debug.js | 14 ++++--- .../server/lib/defaultBlockedDomainsList.js | 2 +- .../server/lib/interceptDirectReplyEmails.js | 27 +++++++------- .../server/lib/notifyUsersOnMessage.js | 37 ++++++++++--------- .../server/lib/passwordPolicy.js | 22 ++++++----- .../server/lib/processDirectEmail.js | 17 +++++---- .../server/lib/sendNotificationsOnMessage.js | 28 ++++++++------ .../server/lib/validateEmailDomain.js | 12 +++--- 10 files changed, 97 insertions(+), 77 deletions(-) diff --git a/packages/rocketchat-lib/server/lib/bugsnag.js b/packages/rocketchat-lib/server/lib/bugsnag.js index 8d123c88d512..0586eb52ff93 100644 --- a/packages/rocketchat-lib/server/lib/bugsnag.js +++ b/packages/rocketchat-lib/server/lib/bugsnag.js @@ -1,9 +1,11 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { Info } from 'meteor/rocketchat:utils'; import bugsnag from 'bugsnag'; RocketChat.bugsnag = bugsnag; -RocketChat.settings.get('Bugsnag_api_key', (key, value) => { +settings.get('Bugsnag_api_key', (key, value) => { if (value) { bugsnag.register(value); } @@ -14,8 +16,8 @@ const notify = function(message, stack) { message += ` ${ stack }`; } let options = {}; - if (RocketChat.Info) { - options = { app: { version: RocketChat.Info.version, info: RocketChat.Info } }; + if (Info) { + options = { app: { version: Info.version, info: Info } }; } const error = new Error(message); error.stack = stack; diff --git a/packages/rocketchat-lib/server/lib/configLogger.js b/packages/rocketchat-lib/server/lib/configLogger.js index e8d79ffe7b25..7a9c40ce2272 100644 --- a/packages/rocketchat-lib/server/lib/configLogger.js +++ b/packages/rocketchat-lib/server/lib/configLogger.js @@ -1,15 +1,16 @@ import { Meteor } from 'meteor/meteor'; import { LoggerManager } from 'meteor/rocketchat:logger'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.get('Log_Package', function(key, value) { +settings.get('Log_Package', function(key, value) { return LoggerManager.showPackage = value; }); -RocketChat.settings.get('Log_File', function(key, value) { +settings.get('Log_File', function(key, value) { return LoggerManager.showFileAndLine = value; }); -RocketChat.settings.get('Log_Level', function(key, value) { +settings.get('Log_Level', function(key, value) { if (value != null) { LoggerManager.logLevel = parseInt(value); Meteor.setTimeout(() => LoggerManager.enable(true), 200); diff --git a/packages/rocketchat-lib/server/lib/debug.js b/packages/rocketchat-lib/server/lib/debug.js index ca32e6a9f1ec..f821d2b2c1b4 100644 --- a/packages/rocketchat-lib/server/lib/debug.js +++ b/packages/rocketchat-lib/server/lib/debug.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; import { InstanceStatus } from 'meteor/konecty:multiple-instances-status'; +import { settings } from 'meteor/rocketchat:settings'; +import { metrics } from 'meteor/rocketchat:metrics'; import _ from 'underscore'; import { Logger } from 'meteor/rocketchat:logger'; @@ -17,13 +19,13 @@ const logger = new Logger('Meteor', { let Log_Trace_Methods; let Log_Trace_Subscriptions; -RocketChat.settings.get('Log_Trace_Methods', (key, value) => Log_Trace_Methods = value); -RocketChat.settings.get('Log_Trace_Subscriptions', (key, value) => Log_Trace_Subscriptions = value); +settings.get('Log_Trace_Methods', (key, value) => Log_Trace_Methods = value); +settings.get('Log_Trace_Subscriptions', (key, value) => Log_Trace_Subscriptions = value); let Log_Trace_Methods_Filter; let Log_Trace_Subscriptions_Filter; -RocketChat.settings.get('Log_Trace_Methods_Filter', (key, value) => Log_Trace_Methods_Filter = value ? new RegExp(value) : undefined); -RocketChat.settings.get('Log_Trace_Subscriptions_Filter', (key, value) => Log_Trace_Subscriptions_Filter = value ? new RegExp(value) : undefined); +settings.get('Log_Trace_Methods_Filter', (key, value) => Log_Trace_Methods_Filter = value ? new RegExp(value) : undefined); +settings.get('Log_Trace_Subscriptions_Filter', (key, value) => Log_Trace_Subscriptions_Filter = value ? new RegExp(value) : undefined); const traceConnection = (enable, filter, prefix, name, connection, userId) => { if (!enable) { @@ -49,7 +51,7 @@ const traceConnection = (enable, filter, prefix, name, connection, userId) => { const wrapMethods = function(name, originalHandler, methodsMap) { methodsMap[name] = function(...originalArgs) { traceConnection(Log_Trace_Methods, Log_Trace_Methods_Filter, 'method', name, this.connection, this.userId); - const end = RocketChat.metrics.meteorMethods.startTimer({ + const end = metrics.meteorMethods.startTimer({ method: name, has_connection: this.connection != null, has_user: this.userId != null, @@ -89,7 +91,7 @@ Meteor.publish = function(name, func) { return originalMeteorPublish(name, function(...args) { traceConnection(Log_Trace_Subscriptions, Log_Trace_Subscriptions_Filter, 'subscription', name, this.connection, this.userId); logger.publish(name, '-> userId:', this.userId, ', arguments: ', args); - const end = RocketChat.metrics.meteorSubscriptions.startTimer({ subscription: name }); + const end = metrics.meteorSubscriptions.startTimer({ subscription: name }); const originalReady = this.ready; this.ready = function() { diff --git a/packages/rocketchat-lib/server/lib/defaultBlockedDomainsList.js b/packages/rocketchat-lib/server/lib/defaultBlockedDomainsList.js index 23dc5b7b21d6..73334b3c9b92 100644 --- a/packages/rocketchat-lib/server/lib/defaultBlockedDomainsList.js +++ b/packages/rocketchat-lib/server/lib/defaultBlockedDomainsList.js @@ -1,4 +1,4 @@ -RocketChat.emailDomainDefaultBlackList = [ +export const emailDomainDefaultBlackList = [ '0-mail.com', '0815.ru', '0815.su', diff --git a/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js b/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js index 9b0bcb521c64..5e54bc901689 100644 --- a/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js +++ b/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; import IMAP from 'imap'; import POP3 from 'poplib'; import { simpleParser } from 'mailparser'; @@ -6,17 +7,17 @@ import { simpleParser } from 'mailparser'; export class IMAPIntercepter { constructor() { this.imap = new IMAP({ - user: RocketChat.settings.get('Direct_Reply_Username'), - password: RocketChat.settings.get('Direct_Reply_Password'), - host: RocketChat.settings.get('Direct_Reply_Host'), - port: RocketChat.settings.get('Direct_Reply_Port'), - debug: RocketChat.settings.get('Direct_Reply_Debug') ? console.log : false, - tls: !RocketChat.settings.get('Direct_Reply_IgnoreTLS'), + user: settings.get('Direct_Reply_Username'), + password: settings.get('Direct_Reply_Password'), + host: settings.get('Direct_Reply_Host'), + port: settings.get('Direct_Reply_Port'), + debug: settings.get('Direct_Reply_Debug') ? console.log : false, + tls: !settings.get('Direct_Reply_IgnoreTLS'), connTimeout: 30000, keepalive: true, }); - this.delete = RocketChat.settings.get('Direct_Reply_Delete') ? RocketChat.settings.get('Direct_Reply_Delete') : true; + this.delete = settings.get('Direct_Reply_Delete') ? settings.get('Direct_Reply_Delete') : true; // On successfully connected. this.imap.on('ready', Meteor.bindEnvironment(() => { @@ -140,16 +141,16 @@ export class IMAPIntercepter { export class POP3Intercepter { constructor() { - this.pop3 = new POP3(RocketChat.settings.get('Direct_Reply_Port'), RocketChat.settings.get('Direct_Reply_Host'), { - enabletls: !RocketChat.settings.get('Direct_Reply_IgnoreTLS'), - debug: RocketChat.settings.get('Direct_Reply_Debug') ? console.log : false, + this.pop3 = new POP3(settings.get('Direct_Reply_Port'), settings.get('Direct_Reply_Host'), { + enabletls: !settings.get('Direct_Reply_IgnoreTLS'), + debug: settings.get('Direct_Reply_Debug') ? console.log : false, }); this.totalMsgCount = 0; this.currentMsgCount = 0; this.pop3.on('connect', Meteor.bindEnvironment(() => { - this.pop3.login(RocketChat.settings.get('Direct_Reply_Username'), RocketChat.settings.get('Direct_Reply_Password')); + this.pop3.login(settings.get('Direct_Reply_Username'), settings.get('Direct_Reply_Password')); })); this.pop3.on('login', Meteor.bindEnvironment((status) => { @@ -242,13 +243,13 @@ export class POP3Helper { start() { // run every x-minutes - if (RocketChat.settings.get('Direct_Reply_Frequency')) { + if (settings.get('Direct_Reply_Frequency')) { RocketChat.POP3 = new POP3Intercepter(); this.running = Meteor.setInterval(() => { // get new emails and process RocketChat.POP3 = new POP3Intercepter(); - }, Math.max(RocketChat.settings.get('Direct_Reply_Frequency') * 60 * 1000, 2 * 60 * 1000)); + }, Math.max(settings.get('Direct_Reply_Frequency') * 60 * 1000, 2 * 60 * 1000)); } } diff --git a/packages/rocketchat-lib/server/lib/notifyUsersOnMessage.js b/packages/rocketchat-lib/server/lib/notifyUsersOnMessage.js index b1a26e11cb93..ad4a75eb9b20 100644 --- a/packages/rocketchat-lib/server/lib/notifyUsersOnMessage.js +++ b/packages/rocketchat-lib/server/lib/notifyUsersOnMessage.js @@ -1,6 +1,9 @@ import _ from 'underscore'; import s from 'underscore.string'; import moment from 'moment'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; /** * Chechs if a messages contains a user highlight @@ -24,19 +27,19 @@ function notifyUsersOnMessage(message, room) { // skips this callback if the message was edited and increments it if the edit was way in the past (aka imported) if (message.editedAt && Math.abs(moment(message.editedAt).diff()) > 60000) { // TODO: Review as I am not sure how else to get around this as the incrementing of the msgs count shouldn't be in this callback - RocketChat.models.Rooms.incMsgCountById(message.rid, 1); + Rooms.incMsgCountById(message.rid, 1); return message; } else if (message.editedAt) { // only updates last message if it was edited (skip rest of callback) - if (RocketChat.settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id)) { - RocketChat.models.Rooms.setLastMessageById(message.rid, message); + if (settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id)) { + Rooms.setLastMessageById(message.rid, message); } return message; } if (message.ts && Math.abs(moment(message.ts).diff()) > 60000) { - RocketChat.models.Rooms.incMsgCountById(message.rid, 1); + Rooms.incMsgCountById(message.rid, 1); return message; } @@ -45,7 +48,7 @@ function notifyUsersOnMessage(message, room) { let toHere = false; const mentionIds = []; const highlightsIds = []; - const highlights = RocketChat.models.Subscriptions.findByRoomWithUserHighlights(room._id, { fields: { userHighlights: 1, 'u._id': 1 } }).fetch(); + const highlights = Subscriptions.findByRoomWithUserHighlights(room._id, { fields: { userHighlights: 1, 'u._id': 1 } }).fetch(); if (message.mentions != null) { message.mentions.forEach(function(mention) { if (!toAll && mention._id === 'all') { @@ -69,47 +72,47 @@ function notifyUsersOnMessage(message, room) { }); if (room.t === 'd') { - const unreadCountDM = RocketChat.settings.get('Unread_Count_DM'); + const unreadCountDM = settings.get('Unread_Count_DM'); if (unreadCountDM === 'all_messages') { - RocketChat.models.Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id); + Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id); } else if (toAll || toHere) { - RocketChat.models.Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, 1); + Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, 1); } else if ((mentionIds && mentionIds.length > 0) || (highlightsIds && highlightsIds.length > 0)) { - RocketChat.models.Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, 1); + Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, 1); } } else { - const unreadCount = RocketChat.settings.get('Unread_Count'); + const unreadCount = settings.get('Unread_Count'); if (toAll || toHere) { let incUnread = 0; if (['all_messages', 'group_mentions_only', 'user_and_group_mentions_only'].includes(unreadCount)) { incUnread = 1; } - RocketChat.models.Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, incUnread); + Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, incUnread); } else if ((mentionIds && mentionIds.length > 0) || (highlightsIds && highlightsIds.length > 0)) { let incUnread = 0; if (['all_messages', 'user_mentions_only', 'user_and_group_mentions_only'].includes(unreadCount)) { incUnread = 1; } - RocketChat.models.Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, incUnread); + Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, incUnread); } else if (unreadCount === 'all_messages') { - RocketChat.models.Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id); + Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id); } } } // Update all the room activity tracker fields // This method take so long to execute on gient rooms cuz it will trugger the cache rebuild for the releations of that room - RocketChat.models.Rooms.incMsgCountAndSetLastMessageById(message.rid, 1, message.ts, RocketChat.settings.get('Store_Last_Message') && message); + Rooms.incMsgCountAndSetLastMessageById(message.rid, 1, message.ts, settings.get('Store_Last_Message') && message); // Update all other subscriptions to alert their owners but witout incrementing // the unread counter, as it is only for mentions and direct messages // We now set alert and open properties in two separate update commands. This proved to be more efficient on MongoDB - because it uses a more efficient index. - RocketChat.models.Subscriptions.setAlertForRoomIdExcludingUserId(message.rid, message.u._id); - RocketChat.models.Subscriptions.setOpenForRoomIdExcludingUserId(message.rid, message.u._id); + Subscriptions.setAlertForRoomIdExcludingUserId(message.rid, message.u._id); + Subscriptions.setOpenForRoomIdExcludingUserId(message.rid, message.u._id); return message; } -RocketChat.callbacks.add('afterSaveMessage', notifyUsersOnMessage, RocketChat.callbacks.priority.LOW, 'notifyUsersOnMessage'); +callbacks.add('afterSaveMessage', notifyUsersOnMessage, callbacks.priority.LOW, 'notifyUsersOnMessage'); diff --git a/packages/rocketchat-lib/server/lib/passwordPolicy.js b/packages/rocketchat-lib/server/lib/passwordPolicy.js index 7ff442bc2ecc..cf741675b3dd 100644 --- a/packages/rocketchat-lib/server/lib/passwordPolicy.js +++ b/packages/rocketchat-lib/server/lib/passwordPolicy.js @@ -1,13 +1,15 @@ +import { settings } from 'meteor/rocketchat:settings'; import PasswordPolicy from './PasswordPolicyClass'; -RocketChat.passwordPolicy = new PasswordPolicy(); +const passwordPolicy = new PasswordPolicy(); +RocketChat.passwordPolicy = passwordPolicy; -RocketChat.settings.get('Accounts_Password_Policy_Enabled', (key, value) => RocketChat.passwordPolicy.enabled = value); -RocketChat.settings.get('Accounts_Password_Policy_MinLength', (key, value) => RocketChat.passwordPolicy.minLength = value); -RocketChat.settings.get('Accounts_Password_Policy_MaxLength', (key, value) => RocketChat.passwordPolicy.maxLength = value); -RocketChat.settings.get('Accounts_Password_Policy_ForbidRepeatingCharacters', (key, value) => RocketChat.passwordPolicy.forbidRepeatingCharacters = value); -RocketChat.settings.get('Accounts_Password_Policy_ForbidRepeatingCharactersCount', (key, value) => RocketChat.passwordPolicy.forbidRepeatingCharactersCount = value); -RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneLowercase', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneLowercase = value); -RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneUppercase', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneUppercase = value); -RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneNumber', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneNumber = value); -RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneSpecialCharacter', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneSpecialCharacter = value); +settings.get('Accounts_Password_Policy_Enabled', (key, value) => passwordPolicy.enabled = value); +settings.get('Accounts_Password_Policy_MinLength', (key, value) => passwordPolicy.minLength = value); +settings.get('Accounts_Password_Policy_MaxLength', (key, value) => passwordPolicy.maxLength = value); +settings.get('Accounts_Password_Policy_ForbidRepeatingCharacters', (key, value) => passwordPolicy.forbidRepeatingCharacters = value); +settings.get('Accounts_Password_Policy_ForbidRepeatingCharactersCount', (key, value) => passwordPolicy.forbidRepeatingCharactersCount = value); +settings.get('Accounts_Password_Policy_AtLeastOneLowercase', (key, value) => passwordPolicy.mustContainAtLeastOneLowercase = value); +settings.get('Accounts_Password_Policy_AtLeastOneUppercase', (key, value) => passwordPolicy.mustContainAtLeastOneUppercase = value); +settings.get('Accounts_Password_Policy_AtLeastOneNumber', (key, value) => passwordPolicy.mustContainAtLeastOneNumber = value); +settings.get('Accounts_Password_Policy_AtLeastOneSpecialCharacter', (key, value) => passwordPolicy.mustContainAtLeastOneSpecialCharacter = value); diff --git a/packages/rocketchat-lib/server/lib/processDirectEmail.js b/packages/rocketchat-lib/server/lib/processDirectEmail.js index 94f0bfe33e8d..36b5ab27f437 100644 --- a/packages/rocketchat-lib/server/lib/processDirectEmail.js +++ b/packages/rocketchat-lib/server/lib/processDirectEmail.js @@ -1,4 +1,7 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { Rooms, Messages, Users, Subscriptions } from 'meteor/rocketchat:models'; +import { metrics } from 'meteor/rocketchat:metrics'; import { EmailReplyParser as reply } from 'emailreplyparser'; import moment from 'moment'; @@ -20,14 +23,14 @@ RocketChat.processDirectEmail = function(email) { message.ts = new Date(); } - if (message.msg && message.msg.length > RocketChat.settings.get('Message_MaxAllowedSize')) { + if (message.msg && message.msg.length > settings.get('Message_MaxAllowedSize')) { return false; } // reduce new lines in multiline message message.msg = message.msg.split('\n\n').join('\n'); - const user = RocketChat.models.Users.findOneByEmailAddress(email.headers.from, { + const user = Users.findOneByEmailAddress(email.headers.from, { fields: { username: 1, name: 1, @@ -38,7 +41,7 @@ RocketChat.processDirectEmail = function(email) { return false; } - const prevMessage = RocketChat.models.Messages.findOneById(email.headers.mid, { + const prevMessage = Messages.findOneById(email.headers.mid, { rid: 1, u: 1, }); @@ -53,7 +56,7 @@ RocketChat.processDirectEmail = function(email) { return false; } - const roomInfo = RocketChat.models.Rooms.findOneById(message.rid, { + const roomInfo = Rooms.findOneById(message.rid, { t: 1, name: 1, }); @@ -75,7 +78,7 @@ RocketChat.processDirectEmail = function(email) { // add reply message link message.msg = prevMessageLink + message.msg; - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(message.rid, user._id); + const subscription = Subscriptions.findOneByRoomIdAndUserId(message.rid, user._id); if (subscription && (subscription.blocked || subscription.blocker)) { // room is blocked return false; @@ -86,11 +89,11 @@ RocketChat.processDirectEmail = function(email) { return false; } - if (message.alias == null && RocketChat.settings.get('Message_SetNameToAliasEnabled')) { + if (message.alias == null && settings.get('Message_SetNameToAliasEnabled')) { message.alias = user.name; } - RocketChat.metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 + metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 return RocketChat.sendMessage(user, message, room); } diff --git a/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js b/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js index 5319d753a1bf..0ee85ecddc51 100644 --- a/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js +++ b/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js @@ -1,6 +1,10 @@ import { Meteor } from 'meteor/meteor'; import moment from 'moment'; - +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { roomTypes } from 'meteor/rocketchat:utils'; import { callJoinRoom, messageContainsHighlight, parseMessageTextPerUser, replaceMentionedUsernamesWithFullNames } from '../functions/notifications/'; import { sendEmail, shouldNotifyEmail } from '../functions/notifications/email'; import { sendSinglePush, shouldNotifyMobile } from '../functions/notifications/mobile'; @@ -35,7 +39,7 @@ const sendNotification = async({ const roomType = room.t; // If the user doesn't have permission to view direct messages, don't send notification of direct messages. - if (roomType === 'd' && !RocketChat.authz.hasPermission(subscription.u._id, 'view-d-room')) { + if (roomType === 'd' && !hasPermission(subscription.u._id, 'view-d-room')) { return; } @@ -186,7 +190,7 @@ async function sendAllNotifications(message, room) { return message; } - const sender = RocketChat.roomTypes.getConfig(room.t).getMsgSender(message.u._id); + const sender = roomTypes.getConfig(room.t).getMsgSender(message.u._id); if (!sender) { return message; } @@ -196,14 +200,14 @@ async function sendAllNotifications(message, room) { const hasMentionToAll = mentionIds.includes('all'); const hasMentionToHere = mentionIds.includes('here'); - let notificationMessage = RocketChat.callbacks.run('beforeSendMessageNotifications', message.msg); - if (mentionIds.length > 0 && RocketChat.settings.get('UI_Use_Real_Name')) { + let notificationMessage = callbacks.run('beforeSendMessageNotifications', message.msg); + if (mentionIds.length > 0 && settings.get('UI_Use_Real_Name')) { notificationMessage = replaceMentionedUsernamesWithFullNames(message.msg, message.mentions); } // Don't fetch all users if room exceeds max members - const maxMembersForNotification = RocketChat.settings.get('Notifications_Max_Room_Members'); - const roomMembersCount = RocketChat.models.Subscriptions.findByRoomId(room._id).count(); + const maxMembersForNotification = settings.get('Notifications_Max_Room_Members'); + const roomMembersCount = Subscriptions.findByRoomId(room._id).count(); const disableAllMessageNotifications = roomMembersCount > maxMembersForNotification && maxMembersForNotification !== 0; const query = { @@ -238,7 +242,7 @@ async function sendAllNotifications(message, room) { } const serverField = kind === 'email' ? 'emailNotificationMode' : `${ kind }Notifications`; - const serverPreference = RocketChat.settings.get(`Accounts_Default_User_Preferences_${ serverField }`); + const serverPreference = settings.get(`Accounts_Default_User_Preferences_${ serverField }`); if ((room.t === 'd' && serverPreference !== 'nothing') || (!disableAllMessageNotifications && (serverPreference === 'all' || hasMentionToAll || hasMentionToHere))) { query.$or.push({ [notificationField]: { $exists: false }, @@ -254,7 +258,7 @@ async function sendAllNotifications(message, room) { // the find bellow is crucial. all subscription records returned will receive at least one kind of notification. // the query is defined by the server's default values and Notifications_Max_Room_Members setting. - const subscriptions = await RocketChat.models.Subscriptions.model.rawCollection().aggregate([ + const subscriptions = await Subscriptions.model.rawCollection().aggregate([ { $match: query }, lookup, filter, @@ -277,7 +281,7 @@ async function sendAllNotifications(message, room) { if (room.t === 'c') { // get subscriptions from users already in room (to not send them a notification) const mentions = [...mentionIdsWithoutGroups]; - RocketChat.models.Subscriptions.findByRoomIdAndUserIds(room._id, mentionIdsWithoutGroups, { fields: { 'u._id': 1 } }).forEach((subscription) => { + Subscriptions.findByRoomIdAndUserIds(room._id, mentionIdsWithoutGroups, { fields: { 'u._id': 1 } }).forEach((subscription) => { const index = mentions.indexOf(subscription.u._id); if (index !== -1) { mentions.splice(index, 1); @@ -292,7 +296,7 @@ async function sendAllNotifications(message, room) { }) ).then((users) => { users.forEach((userId) => { - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, userId); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, userId); sendNotification({ subscription, @@ -313,6 +317,6 @@ async function sendAllNotifications(message, room) { return message; } -RocketChat.callbacks.add('afterSaveMessage', (message, room) => Promise.await(sendAllNotifications(message, room)), RocketChat.callbacks.priority.LOW, 'sendNotificationsOnMessage'); +callbacks.add('afterSaveMessage', (message, room) => Promise.await(sendAllNotifications(message, room)), callbacks.priority.LOW, 'sendNotificationsOnMessage'); export { sendNotification, sendAllNotifications }; diff --git a/packages/rocketchat-lib/server/lib/validateEmailDomain.js b/packages/rocketchat-lib/server/lib/validateEmailDomain.js index 005dab6506cb..da7d3ac2f98a 100644 --- a/packages/rocketchat-lib/server/lib/validateEmailDomain.js +++ b/packages/rocketchat-lib/server/lib/validateEmailDomain.js @@ -1,4 +1,6 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { emailDomainDefaultBlackList } from './defaultBlockedDomainsList'; import _ from 'underscore'; import dns from 'dns'; @@ -7,16 +9,16 @@ let emailDomainWhiteList = []; let useDefaultBlackList = false; let useDNSDomainCheck = false; -RocketChat.settings.get('Accounts_BlockedDomainsList', function(key, value) { +settings.get('Accounts_BlockedDomainsList', function(key, value) { emailDomainBlackList = _.map(value.split(','), (domain) => domain.trim()); }); -RocketChat.settings.get('Accounts_AllowedDomainsList', function(key, value) { +settings.get('Accounts_AllowedDomainsList', function(key, value) { emailDomainWhiteList = _.map(value.split(','), (domain) => domain.trim()); }); -RocketChat.settings.get('Accounts_UseDefaultBlockedDomainsList', function(key, value) { +settings.get('Accounts_UseDefaultBlockedDomainsList', function(key, value) { useDefaultBlackList = value; }); -RocketChat.settings.get('Accounts_UseDNSDomainCheck', function(key, value) { +settings.get('Accounts_UseDNSDomainCheck', function(key, value) { useDNSDomainCheck = value; }); @@ -30,7 +32,7 @@ RocketChat.validateEmailDomain = function(email) { // if not in whitelist if (emailDomainWhiteList.indexOf(emailDomain) === -1) { - if (emailDomainBlackList.indexOf(emailDomain) !== -1 || (useDefaultBlackList && RocketChat.emailDomainDefaultBlackList.indexOf(emailDomain) !== -1)) { + if (emailDomainBlackList.indexOf(emailDomain) !== -1 || (useDefaultBlackList && emailDomainDefaultBlackList.indexOf(emailDomain) !== -1)) { throw new Meteor.Error('error-email-domain-blacklisted', 'The email domain is blacklisted', { function: 'RocketChat.validateEmailDomain' }); } } From 4cede2ea7c2411c2c957e45ef17bf2096516744e Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 11:26:18 -0200 Subject: [PATCH 06/18] Import variables to remove RC namespace inside rc-lib/server/methods --- .../server/methods/addOAuthService.js | 36 ++++++++++--------- .../server/methods/addUsersToRoom.js | 14 ++++---- .../server/methods/archiveRoom.js | 6 ++-- .../server/methods/blockUser.js | 7 ++-- .../methods/checkRegistrationSecretURL.js | 3 +- .../methods/checkUsernameAvailability.js | 3 +- .../server/methods/cleanRoomHistory.js | 3 +- .../server/methods/createChannel.js | 3 +- .../server/methods/createPrivateGroup.js | 3 +- .../server/methods/createToken.js | 3 +- .../server/methods/deleteMessage.js | 15 ++++---- .../server/methods/deleteUserOwnAccount.js | 6 ++-- .../methods/executeSlashCommandPreview.js | 7 ++-- .../server/methods/filterATAllTag.js | 12 ++++--- .../server/methods/filterATHereTag.js | 12 ++++--- .../server/methods/filterBadWords.js | 8 +++-- .../server/methods/getChannelHistory.js | 17 +++++---- .../server/methods/getRoomJoinCode.js | 6 ++-- .../server/methods/getRoomRoles.js | 12 ++++--- .../server/methods/getServerInfo.js | 3 +- .../server/methods/getSingleMessage.js | 3 +- .../server/methods/getSlashCommandPreviews.js | 7 ++-- .../server/methods/getUserRoles.js | 5 +-- .../rocketchat-lib/server/methods/joinRoom.js | 8 +++-- .../server/methods/leaveRoom.js | 12 ++++--- .../server/methods/refreshOAuthService.js | 6 ++-- .../server/methods/removeOAuthService.js | 36 ++++++++++--------- .../server/methods/restartServer.js | 3 +- .../server/methods/robotMethods.js | 8 +++-- .../server/methods/saveSetting.js | 9 +++-- .../server/methods/sendInvitationEmail.js | 8 +++-- .../server/methods/sendMessage.js | 24 ++++++++----- .../server/methods/sendSMTPTestEmail.js | 3 +- .../server/methods/setAdminStatus.js | 3 +- .../rocketchat-lib/server/methods/setEmail.js | 3 +- .../server/methods/setRealName.js | 3 +- .../server/methods/setUsername.js | 9 +++-- .../server/methods/unarchiveRoom.js | 6 ++-- .../server/methods/unblockUser.js | 7 ++-- .../server/methods/updateMessage.js | 13 ++++--- 40 files changed, 215 insertions(+), 140 deletions(-) diff --git a/packages/rocketchat-lib/server/methods/addOAuthService.js b/packages/rocketchat-lib/server/methods/addOAuthService.js index 75e3d28d085e..275cd2835e83 100644 --- a/packages/rocketchat-lib/server/methods/addOAuthService.js +++ b/packages/rocketchat-lib/server/methods/addOAuthService.js @@ -2,6 +2,8 @@ /* eslint comma-spacing: 0 */ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import s from 'underscore.string'; Meteor.methods({ @@ -13,26 +15,26 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'addOAuthService' }); } - if (RocketChat.authz.hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { + if (hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { throw new Meteor.Error('error-action-not-allowed', 'Adding OAuth Services is not allowed', { method: 'addOAuthService', action: 'Adding_OAuth_Services' }); } name = name.toLowerCase().replace(/[^a-z0-9_]/g, ''); name = s.capitalize(name); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Enable', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-url` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'URL', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-token_path` , '/oauth/token' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Token_Path', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-token_sent_via` , 'payload' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Token_Sent_Via', persistent: true, values: [{ key: 'header', i18nLabel: 'Header' }, { key: 'payload', i18nLabel: 'Payload' }] }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-identity_token_sent_via`, 'default' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Identity_Token_Sent_Via', persistent: true, values: [{ key: 'default', i18nLabel: 'Same_As_Token_Sent_Via' }, { key: 'header', i18nLabel: 'Header' }, { key: 'payload', i18nLabel: 'Payload' }] }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-identity_path` , '/me' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Identity_Path', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-authorize_path` , '/oauth/authorize', { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Authorize_Path', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-scope` , 'openid' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Scope', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-id` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_id', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-secret` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Secret', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-login_style` , 'popup' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Login_Style', persistent: true, values: [{ key: 'redirect', i18nLabel: 'Redirect' }, { key: 'popup', i18nLabel: 'Popup' }, { key: '', i18nLabel: 'Default' }] }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-button_label_text` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-button_label_color` , '#FFFFFF' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-button_color` , '#13679A' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Color', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-username_field` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Username_Field', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-merge_users` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Merge_Users', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Enable', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-url` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'URL', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-token_path` , '/oauth/token' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Token_Path', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-token_sent_via` , 'payload' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Token_Sent_Via', persistent: true, values: [{ key: 'header', i18nLabel: 'Header' }, { key: 'payload', i18nLabel: 'Payload' }] }); + settings.add(`Accounts_OAuth_Custom-${ name }-identity_token_sent_via`, 'default' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Identity_Token_Sent_Via', persistent: true, values: [{ key: 'default', i18nLabel: 'Same_As_Token_Sent_Via' }, { key: 'header', i18nLabel: 'Header' }, { key: 'payload', i18nLabel: 'Payload' }] }); + settings.add(`Accounts_OAuth_Custom-${ name }-identity_path` , '/me' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Identity_Path', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-authorize_path` , '/oauth/authorize', { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Authorize_Path', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-scope` , 'openid' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Scope', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-id` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_id', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-secret` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Secret', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-login_style` , 'popup' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Login_Style', persistent: true, values: [{ key: 'redirect', i18nLabel: 'Redirect' }, { key: 'popup', i18nLabel: 'Popup' }, { key: '', i18nLabel: 'Default' }] }); + settings.add(`Accounts_OAuth_Custom-${ name }-button_label_text` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-button_label_color` , '#FFFFFF' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-button_color` , '#13679A' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Color', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-username_field` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Username_Field', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-merge_users` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Merge_Users', persistent: true }); } }); diff --git a/packages/rocketchat-lib/server/methods/addUsersToRoom.js b/packages/rocketchat-lib/server/methods/addUsersToRoom.js index cd75a356ecea..dd16bfea969a 100644 --- a/packages/rocketchat-lib/server/methods/addUsersToRoom.js +++ b/packages/rocketchat-lib/server/methods/addUsersToRoom.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; +import { Rooms, Subscriptions, Users } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ addUsersToRoom(data = {}) { @@ -17,9 +19,9 @@ Meteor.methods({ } // Get user and room details - const room = RocketChat.models.Rooms.findOneById(data.rid); + const room = Rooms.findOneById(data.rid); const userId = Meteor.userId(); - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(data.rid, userId, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(data.rid, userId, { fields: { _id: 1 } }); const userInRoom = subscription != null; // Can't add to direct room ever @@ -31,11 +33,11 @@ Meteor.methods({ // Can add to any room you're in, with permission, otherwise need specific room type permission let canAddUser = false; - if (userInRoom && RocketChat.authz.hasPermission(userId, 'add-user-to-joined-room', room._id)) { + if (userInRoom && hasPermission(userId, 'add-user-to-joined-room', room._id)) { canAddUser = true; - } else if (room.t === 'c' && RocketChat.authz.hasPermission(userId, 'add-user-to-any-c-room')) { + } else if (room.t === 'c' && hasPermission(userId, 'add-user-to-any-c-room')) { canAddUser = true; - } else if (room.t === 'p' && RocketChat.authz.hasPermission(userId, 'add-user-to-any-p-room')) { + } else if (room.t === 'p' && hasPermission(userId, 'add-user-to-any-p-room')) { canAddUser = true; } @@ -56,7 +58,7 @@ Meteor.methods({ // Validate each user, then add to room const user = Meteor.user(); data.users.forEach((username) => { - const newUser = RocketChat.models.Users.findOneByUsername(username); + const newUser = Users.findOneByUsername(username); if (!newUser) { throw new Meteor.Error('error-invalid-username', 'Invalid username', { method: 'addUsersToRoom', diff --git a/packages/rocketchat-lib/server/methods/archiveRoom.js b/packages/rocketchat-lib/server/methods/archiveRoom.js index 217fd59e39a1..26d03e477746 100644 --- a/packages/rocketchat-lib/server/methods/archiveRoom.js +++ b/packages/rocketchat-lib/server/methods/archiveRoom.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { Rooms } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ archiveRoom(rid) { @@ -10,13 +12,13 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'archiveRoom' }); } - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (!room) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'archiveRoom' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'archive-room', room._id)) { + if (!hasPermission(Meteor.userId(), 'archive-room', room._id)) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'archiveRoom' }); } diff --git a/packages/rocketchat-lib/server/methods/blockUser.js b/packages/rocketchat-lib/server/methods/blockUser.js index fd771a1dce68..0342cc17f874 100644 --- a/packages/rocketchat-lib/server/methods/blockUser.js +++ b/packages/rocketchat-lib/server/methods/blockUser.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { Subscriptions } from 'meteor/rocketchat:models'; Meteor.methods({ blockUser({ rid, blocked }) { @@ -11,14 +12,14 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'blockUser' }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId()); - const subscription2 = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, blocked); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId()); + const subscription2 = Subscriptions.findOneByRoomIdAndUserId(rid, blocked); if (!subscription || !subscription2) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'blockUser' }); } - RocketChat.models.Subscriptions.setBlockedByRoomId(rid, blocked, Meteor.userId()); + Subscriptions.setBlockedByRoomId(rid, blocked, Meteor.userId()); return true; }, diff --git a/packages/rocketchat-lib/server/methods/checkRegistrationSecretURL.js b/packages/rocketchat-lib/server/methods/checkRegistrationSecretURL.js index 96739aa7f87d..c77fd6f223cc 100644 --- a/packages/rocketchat-lib/server/methods/checkRegistrationSecretURL.js +++ b/packages/rocketchat-lib/server/methods/checkRegistrationSecretURL.js @@ -1,11 +1,12 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.methods({ checkRegistrationSecretURL(hash) { check(hash, String); - return hash === RocketChat.settings.get('Accounts_RegistrationForm_SecretURL'); + return hash === settings.get('Accounts_RegistrationForm_SecretURL'); }, }); diff --git a/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js b/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js index 302b02647b77..a115878d3c5d 100644 --- a/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js +++ b/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.methods({ checkUsernameAvailability(username) { @@ -11,7 +12,7 @@ Meteor.methods({ const user = Meteor.user(); - if (user.username && !RocketChat.settings.get('Accounts_AllowUsernameChange')) { + if (user.username && !settings.get('Accounts_AllowUsernameChange')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setUsername' }); } diff --git a/packages/rocketchat-lib/server/methods/cleanRoomHistory.js b/packages/rocketchat-lib/server/methods/cleanRoomHistory.js index b93cf480fa48..6e449f1a0353 100644 --- a/packages/rocketchat-lib/server/methods/cleanRoomHistory.js +++ b/packages/rocketchat-lib/server/methods/cleanRoomHistory.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ cleanRoomHistory({ roomId, latest, oldest, inclusive = true, limit, excludePinned = false, filesOnly = false, fromUsers = [] }) { @@ -18,7 +19,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'cleanRoomHistory' }); } - if (!RocketChat.authz.hasPermission(userId, 'clean-channel-history', roomId)) { + if (!hasPermission(userId, 'clean-channel-history', roomId)) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'cleanRoomHistory' }); } diff --git a/packages/rocketchat-lib/server/methods/createChannel.js b/packages/rocketchat-lib/server/methods/createChannel.js index df5b722cd407..df438753e028 100644 --- a/packages/rocketchat-lib/server/methods/createChannel.js +++ b/packages/rocketchat-lib/server/methods/createChannel.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ createChannel(name, members, readOnly = false, customFields = {}, extraData = {}) { @@ -10,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'createChannel' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'create-c')) { + if (!hasPermission(Meteor.userId(), 'create-c')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'createChannel' }); } return RocketChat.createRoom('c', name, Meteor.user() && Meteor.user().username, members, readOnly, { customFields, ...extraData }); diff --git a/packages/rocketchat-lib/server/methods/createPrivateGroup.js b/packages/rocketchat-lib/server/methods/createPrivateGroup.js index cc75b89b5ef0..2a28cfd1f5b1 100644 --- a/packages/rocketchat-lib/server/methods/createPrivateGroup.js +++ b/packages/rocketchat-lib/server/methods/createPrivateGroup.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ createPrivateGroup(name, members, readOnly = false, customFields = {}, extraData = {}) { @@ -10,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'createPrivateGroup' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'create-p')) { + if (!hasPermission(Meteor.userId(), 'create-p')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'createPrivateGroup' }); } diff --git a/packages/rocketchat-lib/server/methods/createToken.js b/packages/rocketchat-lib/server/methods/createToken.js index 249c039b4a61..9d17d463566d 100644 --- a/packages/rocketchat-lib/server/methods/createToken.js +++ b/packages/rocketchat-lib/server/methods/createToken.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ createToken(userId) { - if (Meteor.userId() !== userId && !RocketChat.authz.hasPermission(Meteor.userId(), 'user-generate-access-token')) { + if (Meteor.userId() !== userId && !hasPermission(Meteor.userId(), 'user-generate-access-token')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'createToken' }); } const token = Accounts._generateStampedLoginToken(); diff --git a/packages/rocketchat-lib/server/methods/deleteMessage.js b/packages/rocketchat-lib/server/methods/deleteMessage.js index 31e6c6b3300d..7dbed6f85c4c 100644 --- a/packages/rocketchat-lib/server/methods/deleteMessage.js +++ b/packages/rocketchat-lib/server/methods/deleteMessage.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { Messages } from 'meteor/rocketchat:models'; import moment from 'moment'; Meteor.methods({ @@ -12,7 +15,7 @@ Meteor.methods({ method: 'deleteMessage', }); } - const originalMessage = RocketChat.models.Messages.findOneById(message._id, { + const originalMessage = Messages.findOneById(message._id, { fields: { u: 1, rid: 1, @@ -26,17 +29,17 @@ Meteor.methods({ action: 'Delete_message', }); } - const forceDelete = RocketChat.authz.hasPermission(Meteor.userId(), 'force-delete-message', originalMessage.rid); - const hasPermission = RocketChat.authz.hasPermission(Meteor.userId(), 'delete-message', originalMessage.rid); - const deleteAllowed = RocketChat.settings.get('Message_AllowDeleting'); + const forceDelete = hasPermission(Meteor.userId(), 'force-delete-message', originalMessage.rid); + const _hasPermission = hasPermission(Meteor.userId(), 'delete-message', originalMessage.rid); + const deleteAllowed = settings.get('Message_AllowDeleting'); const deleteOwn = originalMessage && originalMessage.u && originalMessage.u._id === Meteor.userId(); - if (!(hasPermission || (deleteAllowed && deleteOwn)) && !(forceDelete)) { + if (!(_hasPermission || (deleteAllowed && deleteOwn)) && !(forceDelete)) { throw new Meteor.Error('error-action-not-allowed', 'Not allowed', { method: 'deleteMessage', action: 'Delete_message', }); } - const blockDeleteInMinutes = RocketChat.settings.get('Message_AllowDeleting_BlockDeleteInMinutes'); + const blockDeleteInMinutes = settings.get('Message_AllowDeleting_BlockDeleteInMinutes'); if (blockDeleteInMinutes != null && blockDeleteInMinutes !== 0 && !forceDelete) { if (originalMessage.ts == null) { return; diff --git a/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js b/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js index 3d197e11cd04..4189d0dd6f32 100644 --- a/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js +++ b/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { Accounts } from 'meteor/accounts-base'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users } from 'meteor/rocketchat:models'; import s from 'underscore.string'; Meteor.methods({ @@ -12,12 +14,12 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'deleteUserOwnAccount' }); } - if (!RocketChat.settings.get('Accounts_AllowDeleteOwnAccount')) { + if (!settings.get('Accounts_AllowDeleteOwnAccount')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'deleteUserOwnAccount' }); } const userId = Meteor.userId(); - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); if (!user) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'deleteUserOwnAccount' }); diff --git a/packages/rocketchat-lib/server/methods/executeSlashCommandPreview.js b/packages/rocketchat-lib/server/methods/executeSlashCommandPreview.js index 50460526fd37..f10b62745566 100644 --- a/packages/rocketchat-lib/server/methods/executeSlashCommandPreview.js +++ b/packages/rocketchat-lib/server/methods/executeSlashCommandPreview.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { slashCommands } from 'meteor/rocketchat:utils'; Meteor.methods({ executeSlashCommandPreview(command, preview) { @@ -8,13 +9,13 @@ Meteor.methods({ }); } - if (!command || !command.cmd || !RocketChat.slashCommands.commands[command.cmd]) { + if (!command || !command.cmd || !slashCommands.commands[command.cmd]) { throw new Meteor.Error('error-invalid-command', 'Invalid Command Provided', { method: 'executeSlashCommandPreview', }); } - const theCmd = RocketChat.slashCommands.commands[command.cmd]; + const theCmd = slashCommands.commands[command.cmd]; if (!theCmd.providesPreview) { throw new Meteor.Error('error-invalid-command', 'Command Does Not Provide Previews', { method: 'executeSlashCommandPreview', @@ -27,6 +28,6 @@ Meteor.methods({ }); } - return RocketChat.slashCommands.executePreview(command.cmd, command.params, command.msg, preview); + return slashCommands.executePreview(command.cmd, command.params, command.msg, preview); }, }); diff --git a/packages/rocketchat-lib/server/methods/filterATAllTag.js b/packages/rocketchat-lib/server/methods/filterATAllTag.js index 7b48a7449c3a..ecbd08a87ae6 100644 --- a/packages/rocketchat-lib/server/methods/filterATAllTag.js +++ b/packages/rocketchat-lib/server/methods/filterATAllTag.js @@ -1,10 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { Users } from 'meteor/rocketchat:models'; import _ from 'underscore'; import moment from 'moment'; -RocketChat.callbacks.add('beforeSaveMessage', function(message) { +callbacks.add('beforeSaveMessage', function(message) { // If the message was edited, or is older than 60 seconds (imported) // the notifications will be skipped, so we can also skip this validation if (message.editedAt || (message.ts && Math.abs(moment(message.ts).diff()) > 60000)) { @@ -16,15 +20,15 @@ RocketChat.callbacks.add('beforeSaveMessage', function(message) { _.pluck(message.mentions, '_id').some((item) => item === 'all')) { // Check if the user has permissions to use @all in both global and room scopes. - if (!RocketChat.authz.hasPermission(message.u._id, 'mention-all') && !RocketChat.authz.hasPermission(message.u._id, 'mention-all', message.rid)) { + if (!hasPermission(message.u._id, 'mention-all') && !hasPermission(message.u._id, 'mention-all', message.rid)) { // Get the language of the user for the error notification. - const { language } = RocketChat.models.Users.findOneById(message.u._id); + const { language } = Users.findOneById(message.u._id); const action = TAPi18n.__('Notify_all_in_this_room', {}, language); // Add a notification to the chat, informing the user that this // action is not allowed. - RocketChat.Notifications.notifyUser(message.u._id, 'message', { + Notifications.notifyUser(message.u._id, 'message', { _id: Random.id(), rid: message.rid, ts: new Date, diff --git a/packages/rocketchat-lib/server/methods/filterATHereTag.js b/packages/rocketchat-lib/server/methods/filterATHereTag.js index 3586789e2eca..12b11659545d 100644 --- a/packages/rocketchat-lib/server/methods/filterATHereTag.js +++ b/packages/rocketchat-lib/server/methods/filterATHereTag.js @@ -1,10 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { Users } from 'meteor/rocketchat:models'; import _ from 'underscore'; import moment from 'moment'; -RocketChat.callbacks.add('beforeSaveMessage', function(message) { +callbacks.add('beforeSaveMessage', function(message) { // If the message was edited, or is older than 60 seconds (imported) // the notifications will be skipped, so we can also skip this validation if (message.editedAt || (message.ts && Math.abs(moment(message.ts).diff()) > 60000)) { @@ -15,15 +19,15 @@ RocketChat.callbacks.add('beforeSaveMessage', function(message) { if (message.mentions != null && _.pluck(message.mentions, '_id').some((item) => item === 'here')) { // Check if the user has permissions to use @here in both global and room scopes. - if (!RocketChat.authz.hasPermission(message.u._id, 'mention-here') && !RocketChat.authz.hasPermission(message.u._id, 'mention-here', message.rid)) { + if (!hasPermission(message.u._id, 'mention-here') && !hasPermission(message.u._id, 'mention-here', message.rid)) { // Get the language of the user for the error notification. - const { language } = RocketChat.models.Users.findOneById(message.u._id); + const { language } = Users.findOneById(message.u._id); const action = TAPi18n.__('Notify_active_in_this_room', {}, language); // Add a notification to the chat, informing the user that this // action is not allowed. - RocketChat.Notifications.notifyUser(message.u._id, 'message', { + Notifications.notifyUser(message.u._id, 'message', { _id: Random.id(), rid: message.rid, ts: new Date, diff --git a/packages/rocketchat-lib/server/methods/filterBadWords.js b/packages/rocketchat-lib/server/methods/filterBadWords.js index a3fafc63c55d..2a68d5eee942 100644 --- a/packages/rocketchat-lib/server/methods/filterBadWords.js +++ b/packages/rocketchat-lib/server/methods/filterBadWords.js @@ -1,9 +1,11 @@ import Filter from 'bad-words'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.callbacks.add('beforeSaveMessage', function(message) { +callbacks.add('beforeSaveMessage', function(message) { - if (RocketChat.settings.get('Message_AllowBadWordsFilter')) { - const badWordsList = RocketChat.settings.get('Message_BadWordsFilterList'); + if (settings.get('Message_AllowBadWordsFilter')) { + const badWordsList = settings.get('Message_BadWordsFilterList'); let options; // Add words to the blacklist diff --git a/packages/rocketchat-lib/server/methods/getChannelHistory.js b/packages/rocketchat-lib/server/methods/getChannelHistory.js index 06304ec04ab4..b9ba43432f16 100644 --- a/packages/rocketchat-lib/server/methods/getChannelHistory.js +++ b/packages/rocketchat-lib/server/methods/getChannelHistory.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Subscriptions, Messages } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; Meteor.methods({ @@ -17,7 +20,7 @@ Meteor.methods({ } // Make sure they can access the room - if (room.t === 'c' && !RocketChat.authz.hasPermission(fromUserId, 'preview-c-room') && !RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, fromUserId, { fields: { _id: 1 } })) { + if (room.t === 'c' && !hasPermission(fromUserId, 'preview-c-room') && !Subscriptions.findOneByRoomIdAndUserId(rid, fromUserId, { fields: { _id: 1 } })) { return false; } @@ -38,19 +41,19 @@ Meteor.methods({ limit: count, }; - if (!RocketChat.settings.get('Message_ShowEditedStatus')) { + if (!settings.get('Message_ShowEditedStatus')) { options.fields = { editedAt: 0 }; } let records = []; if (_.isUndefined(oldest) && inclusive) { - records = RocketChat.models.Messages.findVisibleByRoomIdBeforeTimestampInclusive(rid, latest, options).fetch(); + records = Messages.findVisibleByRoomIdBeforeTimestampInclusive(rid, latest, options).fetch(); } else if (_.isUndefined(oldest) && !inclusive) { - records = RocketChat.models.Messages.findVisibleByRoomIdBeforeTimestamp(rid, latest, options).fetch(); + records = Messages.findVisibleByRoomIdBeforeTimestamp(rid, latest, options).fetch(); } else if (!_.isUndefined(oldest) && inclusive) { - records = RocketChat.models.Messages.findVisibleByRoomIdBetweenTimestampsInclusive(rid, oldest, latest, options).fetch(); + records = Messages.findVisibleByRoomIdBetweenTimestampsInclusive(rid, oldest, latest, options).fetch(); } else { - records = RocketChat.models.Messages.findVisibleByRoomIdBetweenTimestamps(rid, oldest, latest, options).fetch(); + records = Messages.findVisibleByRoomIdBetweenTimestamps(rid, oldest, latest, options).fetch(); } const messages = records.map((record) => RocketChat.composeMessageObjectWithUser(record, fromUserId)); @@ -62,7 +65,7 @@ Meteor.methods({ if (!_.isUndefined(oldest)) { const firstMsg = messages[messages.length - 1]; if (!_.isUndefined(firstMsg) && firstMsg.ts > oldest) { - const unreadMessages = RocketChat.models.Messages.findVisibleByRoomIdBetweenTimestamps(rid, oldest, firstMsg.ts, { limit: 1, sort: { ts: 1 } }); + const unreadMessages = Messages.findVisibleByRoomIdBetweenTimestamps(rid, oldest, firstMsg.ts, { limit: 1, sort: { ts: 1 } }); firstUnread = unreadMessages.fetch()[0]; unreadNotLoaded = unreadMessages.count(); } diff --git a/packages/rocketchat-lib/server/methods/getRoomJoinCode.js b/packages/rocketchat-lib/server/methods/getRoomJoinCode.js index 2b2da233bf39..4a6224b94795 100644 --- a/packages/rocketchat-lib/server/methods/getRoomJoinCode.js +++ b/packages/rocketchat-lib/server/methods/getRoomJoinCode.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Rooms } from 'meteor/rocketchat:models'; Meteor.methods({ getRoomJoinCode(rid) { @@ -9,11 +11,11 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getJoinCode' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'view-join-code')) { + if (!hasPermission(Meteor.userId(), 'view-join-code')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'getJoinCode' }); } - const [room] = RocketChat.models.Rooms.findById(rid).fetch(); + const [room] = Rooms.findById(rid).fetch(); return room && room.joinCode; }, diff --git a/packages/rocketchat-lib/server/methods/getRoomRoles.js b/packages/rocketchat-lib/server/methods/getRoomRoles.js index 3a79f1551ddb..ee18758d9b44 100644 --- a/packages/rocketchat-lib/server/methods/getRoomRoles.js +++ b/packages/rocketchat-lib/server/methods/getRoomRoles.js @@ -1,12 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; +import { Subscriptions, Users, Roles } from 'meteor/rocketchat:models'; import _ from 'underscore'; Meteor.methods({ getRoomRoles(rid) { check(rid, String); - if (!Meteor.userId() && RocketChat.settings.get('Accounts_AllowAnonymousRead') === false) { + if (!Meteor.userId() && settings.get('Accounts_AllowAnonymousRead') === false) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getRoomRoles' }); } @@ -23,16 +25,16 @@ Meteor.methods({ }, }; - const UI_Use_Real_Name = RocketChat.settings.get('UI_Use_Real_Name') === true; + const UI_Use_Real_Name = settings.get('UI_Use_Real_Name') === true; - const roles = RocketChat.models.Roles.find({ scope: 'Subscriptions', description: { $exists: 1, $ne: '' } }).fetch(); - const subscriptions = RocketChat.models.Subscriptions.findByRoomIdAndRoles(rid, _.pluck(roles, '_id'), options).fetch(); + const roles = Roles.find({ scope: 'Subscriptions', description: { $exists: 1, $ne: '' } }).fetch(); + const subscriptions = Subscriptions.findByRoomIdAndRoles(rid, _.pluck(roles, '_id'), options).fetch(); if (!UI_Use_Real_Name) { return subscriptions; } else { return subscriptions.map((subscription) => { - const user = RocketChat.models.Users.findOneById(subscription.u._id); + const user = Users.findOneById(subscription.u._id); subscription.u.name = user && user.name; return subscription; }); diff --git a/packages/rocketchat-lib/server/methods/getServerInfo.js b/packages/rocketchat-lib/server/methods/getServerInfo.js index 7c91ded54a60..d1f786eca374 100644 --- a/packages/rocketchat-lib/server/methods/getServerInfo.js +++ b/packages/rocketchat-lib/server/methods/getServerInfo.js @@ -1,7 +1,8 @@ import { Meteor } from 'meteor/meteor'; +import { Info } from 'meteor/rocketchat:utils'; Meteor.methods({ getServerInfo() { - return RocketChat.Info; + return Info; }, }); diff --git a/packages/rocketchat-lib/server/methods/getSingleMessage.js b/packages/rocketchat-lib/server/methods/getSingleMessage.js index 294cf1002ffa..756f8478cbb7 100644 --- a/packages/rocketchat-lib/server/methods/getSingleMessage.js +++ b/packages/rocketchat-lib/server/methods/getSingleMessage.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { Messages } from 'meteor/rocketchat:models'; Meteor.methods({ getSingleMessage(msgId) { @@ -9,7 +10,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getSingleMessage' }); } - const msg = RocketChat.models.Messages.findOneById(msgId); + const msg = Messages.findOneById(msgId); if (!msg || !msg.rid) { return undefined; diff --git a/packages/rocketchat-lib/server/methods/getSlashCommandPreviews.js b/packages/rocketchat-lib/server/methods/getSlashCommandPreviews.js index b3ddb974d683..28211e2182c8 100644 --- a/packages/rocketchat-lib/server/methods/getSlashCommandPreviews.js +++ b/packages/rocketchat-lib/server/methods/getSlashCommandPreviews.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { slashCommands } from 'meteor/rocketchat:utils'; Meteor.methods({ getSlashCommandPreviews(command) { @@ -8,19 +9,19 @@ Meteor.methods({ }); } - if (!command || !command.cmd || !RocketChat.slashCommands.commands[command.cmd]) { + if (!command || !command.cmd || !slashCommands.commands[command.cmd]) { throw new Meteor.Error('error-invalid-command', 'Invalid Command Provided', { method: 'executeSlashCommandPreview', }); } - const theCmd = RocketChat.slashCommands.commands[command.cmd]; + const theCmd = slashCommands.commands[command.cmd]; if (!theCmd.providesPreview) { throw new Meteor.Error('error-invalid-command', 'Command Does Not Provide Previews', { method: 'executeSlashCommandPreview', }); } - return RocketChat.slashCommands.getPreviews(command.cmd, command.params, command.msg); + return slashCommands.getPreviews(command.cmd, command.params, command.msg); }, }); diff --git a/packages/rocketchat-lib/server/methods/getUserRoles.js b/packages/rocketchat-lib/server/methods/getUserRoles.js index a0c5ad940f44..5d4c32283fa8 100644 --- a/packages/rocketchat-lib/server/methods/getUserRoles.js +++ b/packages/rocketchat-lib/server/methods/getUserRoles.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { Roles, Users } from 'meteor/rocketchat:models'; import _ from 'underscore'; Meteor.methods({ @@ -18,12 +19,12 @@ Meteor.methods({ }, }; - const roles = RocketChat.models.Roles.find({ scope: 'Users', description: { $exists: 1, $ne: '' } }).fetch(); + const roles = Roles.find({ scope: 'Users', description: { $exists: 1, $ne: '' } }).fetch(); const roleIds = _.pluck(roles, '_id'); // Security issue: we should not send all user's roles to all clients, only the 'public' roles // We must remove all roles that are not part of the query from the returned users - const users = RocketChat.models.Users.findUsersInRoles(roleIds, null, options).fetch(); + const users = Users.findUsersInRoles(roleIds, null, options).fetch(); for (const user of users) { user.roles = _.intersection(user.roles, roleIds); } diff --git a/packages/rocketchat-lib/server/methods/joinRoom.js b/packages/rocketchat-lib/server/methods/joinRoom.js index fd7a99b50400..c0f236564c34 100644 --- a/packages/rocketchat-lib/server/methods/joinRoom.js +++ b/packages/rocketchat-lib/server/methods/joinRoom.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission, canAccessRoom } from 'meteor/rocketchat:authorization'; +import { Rooms } from 'meteor/rocketchat:models'; Meteor.methods({ joinRoom(rid, code) { @@ -9,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'joinRoom' }); } - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (!room) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'joinRoom' }); @@ -24,10 +26,10 @@ Meteor.methods({ throw new Meteor.Error('error-not-allowed', 'Token required', { method: 'joinRoom' }); } } else { - if (!RocketChat.authz.canAccessRoom(room, Meteor.user())) { + if (!canAccessRoom(room, Meteor.user())) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'joinRoom' }); } - if ((room.joinCodeRequired === true) && (code !== room.joinCode) && !RocketChat.authz.hasPermission(Meteor.userId(), 'join-without-join-code')) { + if ((room.joinCodeRequired === true) && (code !== room.joinCode) && !hasPermission(Meteor.userId(), 'join-without-join-code')) { throw new Meteor.Error('error-code-invalid', 'Invalid Room Password', { method: 'joinRoom' }); } } diff --git a/packages/rocketchat-lib/server/methods/leaveRoom.js b/packages/rocketchat-lib/server/methods/leaveRoom.js index b7fe5324ada9..9ef756b99915 100644 --- a/packages/rocketchat-lib/server/methods/leaveRoom.js +++ b/packages/rocketchat-lib/server/methods/leaveRoom.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission, hasRole, getUsersInRole } from 'meteor/rocketchat:authorization'; +import { Subscriptions, Rooms } from 'meteor/rocketchat:models'; Meteor.methods({ leaveRoom(rid) { @@ -12,21 +14,21 @@ Meteor.methods({ this.unblock(); - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); const user = Meteor.user(); - if (room.t === 'd' || (room.t === 'c' && !RocketChat.authz.hasPermission(user._id, 'leave-c')) || (room.t === 'p' && !RocketChat.authz.hasPermission(user._id, 'leave-p'))) { + if (room.t === 'd' || (room.t === 'c' && !hasPermission(user._id, 'leave-c')) || (room.t === 'p' && !hasPermission(user._id, 'leave-p'))) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'leaveRoom' }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id, { fields: { _id: 1 } }); if (!subscription) { throw new Meteor.Error('error-user-not-in-room', 'You are not in this room', { method: 'leaveRoom' }); } // If user is room owner, check if there are other owners. If there isn't anyone else, warn user to set a new owner. - if (RocketChat.authz.hasRole(user._id, 'owner', room._id)) { - const numOwners = RocketChat.authz.getUsersInRole('owner', room._id).count(); + if (hasRole(user._id, 'owner', room._id)) { + const numOwners = getUsersInRole('owner', room._id).count(); if (numOwners === 1) { throw new Meteor.Error('error-you-are-last-owner', 'You are the last owner. Please set new owner before leaving the room.', { method: 'leaveRoom' }); } diff --git a/packages/rocketchat-lib/server/methods/refreshOAuthService.js b/packages/rocketchat-lib/server/methods/refreshOAuthService.js index 50efc1764b75..68984d4b4b32 100644 --- a/packages/rocketchat-lib/server/methods/refreshOAuthService.js +++ b/packages/rocketchat-lib/server/methods/refreshOAuthService.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { ServiceConfiguration } from 'meteor/service-configuration'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Settings } from 'meteor/rocketchat:models'; Meteor.methods({ refreshOAuthService() { @@ -7,12 +9,12 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'refreshOAuthService' }); } - if (RocketChat.authz.hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { + if (hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { throw new Meteor.Error('error-action-not-allowed', 'Refresh OAuth Services is not allowed', { method: 'refreshOAuthService', action: 'Refreshing_OAuth_Services' }); } ServiceConfiguration.configurations.remove({}); - RocketChat.models.Settings.update({ _id: /^Accounts_OAuth_.+/ }, { $set: { _updatedAt: new Date } }, { multi: true }); + Settings.update({ _id: /^Accounts_OAuth_.+/ }, { $set: { _updatedAt: new Date } }, { multi: true }); }, }); diff --git a/packages/rocketchat-lib/server/methods/removeOAuthService.js b/packages/rocketchat-lib/server/methods/removeOAuthService.js index 86ae0a11abe1..edcafff193ca 100644 --- a/packages/rocketchat-lib/server/methods/removeOAuthService.js +++ b/packages/rocketchat-lib/server/methods/removeOAuthService.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; Meteor.methods({ @@ -11,27 +13,27 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'removeOAuthService' }); } - if (RocketChat.authz.hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { + if (hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'removeOAuthService' }); } name = name.toLowerCase().replace(/[^a-z0-9_]/g, ''); name = s.capitalize(name); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-url`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-token_path`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-identity_path`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-authorize_path`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-scope`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-token_sent_via`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-identity_token_sent_via`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-id`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-secret`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-button_label_text`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-button_label_color`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-button_color`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-login_style`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-username_field`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-merge_users`); + settings.removeById(`Accounts_OAuth_Custom-${ name }`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-url`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-token_path`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-identity_path`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-authorize_path`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-scope`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-token_sent_via`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-identity_token_sent_via`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-id`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-secret`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-button_label_text`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-button_label_color`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-button_color`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-login_style`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-username_field`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-merge_users`); }, }); diff --git a/packages/rocketchat-lib/server/methods/restartServer.js b/packages/rocketchat-lib/server/methods/restartServer.js index dba153b4edb3..9573a9ff8f91 100644 --- a/packages/rocketchat-lib/server/methods/restartServer.js +++ b/packages/rocketchat-lib/server/methods/restartServer.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { hasRole } from 'meteor/rocketchat:authorization'; Meteor.methods({ restart_server() { @@ -6,7 +7,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'restart_server' }); } - if (RocketChat.authz.hasRole(Meteor.userId(), 'admin') !== true) { + if (hasRole(Meteor.userId(), 'admin') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'restart_server' }); } diff --git a/packages/rocketchat-lib/server/methods/robotMethods.js b/packages/rocketchat-lib/server/methods/robotMethods.js index a47fe562bd51..a17bd78159ac 100644 --- a/packages/rocketchat-lib/server/methods/robotMethods.js +++ b/packages/rocketchat-lib/server/methods/robotMethods.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import * as Models from 'meteor/rocketchat:models'; import _ from 'underscore'; Meteor.methods({ @@ -11,19 +13,19 @@ Meteor.methods({ method: 'robot.modelCall', }); } - if (!RocketChat.authz.hasRole(Meteor.userId(), 'robot')) { + if (!hasRole(Meteor.userId(), 'robot')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'robot.modelCall', }); } - const m = RocketChat.models[model]; + const m = Models[model]; if (!m || !_.isFunction(m[method])) { throw new Meteor.Error('error-invalid-method', 'Invalid method', { method: 'robot.modelCall', }); } - const cursor = RocketChat.models[model][method].apply(RocketChat.models[model], args); + const cursor = Models[model][method].apply(Models[model], args); return cursor && cursor.fetch ? cursor.fetch() : cursor; }, }); diff --git a/packages/rocketchat-lib/server/methods/saveSetting.js b/packages/rocketchat-lib/server/methods/saveSetting.js index 724e24a494bb..1bb86e9fd138 100644 --- a/packages/rocketchat-lib/server/methods/saveSetting.js +++ b/packages/rocketchat-lib/server/methods/saveSetting.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { Settings } from 'meteor/rocketchat:models'; Meteor.methods({ saveSetting(_id, value, editor) { @@ -9,7 +12,7 @@ Meteor.methods({ }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'edit-privileged-setting')) { + if (!hasPermission(Meteor.userId(), 'edit-privileged-setting')) { throw new Meteor.Error('error-action-not-allowed', 'Editing settings is not allowed', { method: 'saveSetting', }); @@ -18,7 +21,7 @@ Meteor.methods({ // Verify the _id passed in is a string. check(_id, String); - const setting = RocketChat.models.Settings.db.findOneById(_id); + const setting = Settings.db.findOneById(_id); // Verify the value is what it should be switch (setting.type) { @@ -36,7 +39,7 @@ Meteor.methods({ break; } - RocketChat.settings.updateById(_id, value, editor); + settings.updateById(_id, value, editor); return true; }, }); diff --git a/packages/rocketchat-lib/server/methods/sendInvitationEmail.js b/packages/rocketchat-lib/server/methods/sendInvitationEmail.js index 1605855a812b..b6821a0b84d3 100644 --- a/packages/rocketchat-lib/server/methods/sendInvitationEmail.js +++ b/packages/rocketchat-lib/server/methods/sendInvitationEmail.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import * as Mailer from 'meteor/rocketchat:mailer'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; let html = ''; Meteor.startup(() => { @@ -17,20 +19,20 @@ Meteor.methods({ method: 'sendInvitationEmail', }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'bulk-register-user')) { + if (!hasPermission(Meteor.userId(), 'bulk-register-user')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'sendInvitationEmail', }); } const validEmails = emails.filter(Mailer.checkAddressFormat); - const subject = RocketChat.settings.get('Invitation_Subject'); + const subject = settings.get('Invitation_Subject'); return validEmails.filter((email) => { try { return Mailer.send({ to: email, - from: RocketChat.settings.get('From_Email'), + from: settings.get('From_Email'), subject, html, data: { diff --git a/packages/rocketchat-lib/server/methods/sendMessage.js b/packages/rocketchat-lib/server/methods/sendMessage.js index 20d7dd19ffdd..0e754b534395 100644 --- a/packages/rocketchat-lib/server/methods/sendMessage.js +++ b/packages/rocketchat-lib/server/methods/sendMessage.js @@ -2,6 +2,12 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { metrics } from 'meteor/rocketchat:metrics'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { messageProperties } from 'meteor/rocketchat:ui-utils'; +import { Subscriptions, Users } from 'meteor/rocketchat:models'; import moment from 'moment'; Meteor.methods({ @@ -34,16 +40,16 @@ Meteor.methods({ } if (message.msg) { - const adjustedMessage = RocketChat.messageProperties.messageWithoutEmojiShortnames(message.msg); + const adjustedMessage = messageProperties.messageWithoutEmojiShortnames(message.msg); - if (RocketChat.messageProperties.length(adjustedMessage) > RocketChat.settings.get('Message_MaxAllowedSize')) { + if (messageProperties.length(adjustedMessage) > settings.get('Message_MaxAllowedSize')) { throw new Meteor.Error('error-message-size-exceeded', 'Message size exceeds Message_MaxAllowedSize', { method: 'sendMessage', }); } } - const user = RocketChat.models.Users.findOneById(Meteor.userId(), { + const user = Users.findOneById(Meteor.userId(), { fields: { username: 1, name: 1, @@ -55,9 +61,9 @@ Meteor.methods({ return false; } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId()); + const subscription = Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId()); if (subscription && (subscription.blocked || subscription.blocker)) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: room._id, ts: new Date, @@ -67,7 +73,7 @@ Meteor.methods({ } if ((room.muted || []).includes(user.username)) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: room._id, ts: new Date, @@ -76,7 +82,7 @@ Meteor.methods({ throw new Meteor.Error('You can\'t send messages because you have been muted'); } - if (message.alias == null && RocketChat.settings.get('Message_SetNameToAliasEnabled')) { + if (message.alias == null && settings.get('Message_SetNameToAliasEnabled')) { message.alias = user.name; } @@ -84,13 +90,13 @@ Meteor.methods({ message.sandstormSessionId = this.connection.sandstormSessionId(); } - RocketChat.metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 + metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 return RocketChat.sendMessage(user, message, room); }, }); // Limit a user, who does not have the "bot" role, to sending 5 msgs/second RocketChat.RateLimiter.limitMethod('sendMessage', 5, 1000, { userId(userId) { - return !RocketChat.authz.hasPermission(userId, 'send-many-messages'); + return !hasPermission(userId, 'send-many-messages'); }, }); diff --git a/packages/rocketchat-lib/server/methods/sendSMTPTestEmail.js b/packages/rocketchat-lib/server/methods/sendSMTPTestEmail.js index e29c73662321..4271ea921c83 100644 --- a/packages/rocketchat-lib/server/methods/sendSMTPTestEmail.js +++ b/packages/rocketchat-lib/server/methods/sendSMTPTestEmail.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; import * as Mailer from 'meteor/rocketchat:mailer'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.methods({ sendSMTPTestEmail() { @@ -18,7 +19,7 @@ Meteor.methods({ try { Mailer.send({ to: user.emails[0].address, - from: RocketChat.settings.get('From_Email'), + from: settings.get('From_Email'), subject: 'SMTP Test Email', html: '

You have successfully sent an email

', }); diff --git a/packages/rocketchat-lib/server/methods/setAdminStatus.js b/packages/rocketchat-lib/server/methods/setAdminStatus.js index 00a79d2f199e..dd72c83049cf 100644 --- a/packages/rocketchat-lib/server/methods/setAdminStatus.js +++ b/packages/rocketchat-lib/server/methods/setAdminStatus.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ setAdminStatus(userId, admin) { @@ -11,7 +12,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setAdminStatus' }); } - if (RocketChat.authz.hasPermission(Meteor.userId(), 'assign-admin-role') !== true) { + if (hasPermission(Meteor.userId(), 'assign-admin-role') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setAdminStatus' }); } diff --git a/packages/rocketchat-lib/server/methods/setEmail.js b/packages/rocketchat-lib/server/methods/setEmail.js index 7d13ad2bc81f..583526ca9129 100644 --- a/packages/rocketchat-lib/server/methods/setEmail.js +++ b/packages/rocketchat-lib/server/methods/setEmail.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.methods({ setEmail(email) { @@ -12,7 +13,7 @@ Meteor.methods({ const user = Meteor.user(); - if (!RocketChat.settings.get('Accounts_AllowEmailChange')) { + if (!settings.get('Accounts_AllowEmailChange')) { throw new Meteor.Error('error-action-not-allowed', 'Changing email is not allowed', { method: 'setEmail', action: 'Changing_email' }); } diff --git a/packages/rocketchat-lib/server/methods/setRealName.js b/packages/rocketchat-lib/server/methods/setRealName.js index bd1ddfd430ae..e7a8218ecc70 100644 --- a/packages/rocketchat-lib/server/methods/setRealName.js +++ b/packages/rocketchat-lib/server/methods/setRealName.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.methods({ setRealName(name) { @@ -10,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setRealName' }); } - if (!RocketChat.settings.get('Accounts_AllowRealNameChange')) { + if (!settings.get('Accounts_AllowRealNameChange')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setRealName' }); } diff --git a/packages/rocketchat-lib/server/methods/setUsername.js b/packages/rocketchat-lib/server/methods/setUsername.js index 4c6fb84eddc9..c964fb0ac82b 100644 --- a/packages/rocketchat-lib/server/methods/setUsername.js +++ b/packages/rocketchat-lib/server/methods/setUsername.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import _ from 'underscore'; Meteor.methods({ @@ -13,7 +16,7 @@ Meteor.methods({ const user = Meteor.user(); - if (user.username && !RocketChat.settings.get('Accounts_AllowUsernameChange')) { + if (user.username && !settings.get('Accounts_AllowUsernameChange')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setUsername' }); } @@ -23,7 +26,7 @@ Meteor.methods({ let nameValidation; try { - nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + nameValidation = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); } catch (error) { nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$'); } @@ -43,7 +46,7 @@ Meteor.methods({ if (!user.username) { Meteor.runAsUser(user._id, () => Meteor.call('joinDefaultChannels', joinDefaultChannelsSilenced)); Meteor.defer(function() { - return RocketChat.callbacks.run('afterCreateUser', RocketChat.models.Users.findOneById(user._id)); + return callbacks.run('afterCreateUser', Users.findOneById(user._id)); }); } diff --git a/packages/rocketchat-lib/server/methods/unarchiveRoom.js b/packages/rocketchat-lib/server/methods/unarchiveRoom.js index 975c3162c938..f9aafcc15f62 100644 --- a/packages/rocketchat-lib/server/methods/unarchiveRoom.js +++ b/packages/rocketchat-lib/server/methods/unarchiveRoom.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Rooms } from 'meteor/rocketchat:models'; Meteor.methods({ unarchiveRoom(rid) { @@ -10,13 +12,13 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'unarchiveRoom' }); } - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (!room) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'unarchiveRoom' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'unarchive-room', room._id)) { + if (!hasPermission(Meteor.userId(), 'unarchive-room', room._id)) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'unarchiveRoom' }); } diff --git a/packages/rocketchat-lib/server/methods/unblockUser.js b/packages/rocketchat-lib/server/methods/unblockUser.js index 21c8895e9283..481be92fe1b2 100644 --- a/packages/rocketchat-lib/server/methods/unblockUser.js +++ b/packages/rocketchat-lib/server/methods/unblockUser.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { Subscriptions } from 'meteor/rocketchat:models'; Meteor.methods({ unblockUser({ rid, blocked }) { @@ -11,14 +12,14 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'blockUser' }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId()); - const subscription2 = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, blocked); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId()); + const subscription2 = Subscriptions.findOneByRoomIdAndUserId(rid, blocked); if (!subscription || !subscription2) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'blockUser' }); } - RocketChat.models.Subscriptions.unsetBlockedByRoomId(rid, blocked, Meteor.userId()); + Subscriptions.unsetBlockedByRoomId(rid, blocked, Meteor.userId()); return true; }, diff --git a/packages/rocketchat-lib/server/methods/updateMessage.js b/packages/rocketchat-lib/server/methods/updateMessage.js index feb03bd6d547..f2a5116d880c 100644 --- a/packages/rocketchat-lib/server/methods/updateMessage.js +++ b/packages/rocketchat-lib/server/methods/updateMessage.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { Messages } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import moment from 'moment'; Meteor.methods({ @@ -11,7 +14,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'updateMessage' }); } - const originalMessage = RocketChat.models.Messages.findOneById(message._id); + const originalMessage = Messages.findOneById(message._id); if (!originalMessage || !originalMessage._id) { return; @@ -19,15 +22,15 @@ Meteor.methods({ if (originalMessage.msg === message.msg) { return; } - const hasPermission = RocketChat.authz.hasPermission(Meteor.userId(), 'edit-message', message.rid); - const editAllowed = RocketChat.settings.get('Message_AllowEditing'); + const _hasPermission = hasPermission(Meteor.userId(), 'edit-message', message.rid); + const editAllowed = settings.get('Message_AllowEditing'); const editOwn = originalMessage.u && originalMessage.u._id === Meteor.userId(); - if (!hasPermission && (!editAllowed || !editOwn)) { + if (!_hasPermission && (!editAllowed || !editOwn)) { throw new Meteor.Error('error-action-not-allowed', 'Message editing not allowed', { method: 'updateMessage', action: 'Message_editing' }); } - const blockEditInMinutes = RocketChat.settings.get('Message_AllowEditing_BlockEditInMinutes'); + const blockEditInMinutes = settings.get('Message_AllowEditing_BlockEditInMinutes'); if (Match.test(blockEditInMinutes, Number) && blockEditInMinutes !== 0) { let currentTsDiff; let msgTs; From 5ecc7b84778d30168c61d2142dc06d18ffb048d9 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 15:18:56 -0200 Subject: [PATCH 07/18] Import variables to remove dependency with RC namespace --- packages/rocketchat-lib/package.js | 2 - .../server/models/Permissions.js | 3 -- .../rocketchat-lib/server/models/Roles.js | 3 -- .../rocketchat-lib/server/models/index.js | 4 ++ .../rocketchat-lib/server/oauth/facebook.js | 1 + packages/rocketchat-lib/server/oauth/proxy.js | 5 ++- .../server/publications/settings.js | 29 +++++++------ .../rocketchat-lib/server/startup/email.js | 4 +- .../server/startup/oAuthServicesUpdate.js | 41 ++++++++++--------- .../rocketchat-lib/server/startup/robots.js | 3 +- .../rocketchat-lib/server/startup/settings.js | 23 ++++++----- .../server/startup/settingsOnLoadCdnPrefix.js | 15 +++---- .../startup/settingsOnLoadDirectReply.js | 9 ++-- .../server/startup/settingsOnLoadSMTP.js | 33 +++++++-------- .../startup/defaultRoomTypes.js | 13 +++--- 15 files changed, 99 insertions(+), 89 deletions(-) delete mode 100644 packages/rocketchat-lib/server/models/Permissions.js delete mode 100644 packages/rocketchat-lib/server/models/Roles.js diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 9604a53f4ceb..8d856d350958 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -150,8 +150,6 @@ Package.onUse(function(api) { // SERVER MODELS api.addFiles('server/models/index.js', 'server'); - api.addFiles('server/models/Permissions.js', 'server'); - api.addFiles('server/models/Roles.js', 'server'); api.addFiles('server/oauth/oauth.js', 'server'); api.addFiles('server/oauth/facebook.js', 'server'); diff --git a/packages/rocketchat-lib/server/models/Permissions.js b/packages/rocketchat-lib/server/models/Permissions.js deleted file mode 100644 index c171d3bd4a99..000000000000 --- a/packages/rocketchat-lib/server/models/Permissions.js +++ /dev/null @@ -1,3 +0,0 @@ -import { Permissions } from 'meteor/rocketchat:models'; - -RocketChat.models.Permissions = Permissions; diff --git a/packages/rocketchat-lib/server/models/Roles.js b/packages/rocketchat-lib/server/models/Roles.js deleted file mode 100644 index 88c23358a0ed..000000000000 --- a/packages/rocketchat-lib/server/models/Roles.js +++ /dev/null @@ -1,3 +0,0 @@ -import { Roles } from 'meteor/rocketchat:models'; - -RocketChat.models.Roles = Roles; diff --git a/packages/rocketchat-lib/server/models/index.js b/packages/rocketchat-lib/server/models/index.js index a7620e0667d1..ebb3c8bd4bc2 100644 --- a/packages/rocketchat-lib/server/models/index.js +++ b/packages/rocketchat-lib/server/models/index.js @@ -13,6 +13,8 @@ import { Integrations, IntegrationHistory, Base as _Base, + Permissions, + Roles, } from 'meteor/rocketchat:models'; Object.assign(RocketChat.models, { @@ -30,4 +32,6 @@ Object.assign(RocketChat.models, { CustomSounds, Integrations, IntegrationHistory, + Permissions, + Roles, }); diff --git a/packages/rocketchat-lib/server/oauth/facebook.js b/packages/rocketchat-lib/server/oauth/facebook.js index 0bb04873083d..132fdc524c67 100644 --- a/packages/rocketchat-lib/server/oauth/facebook.js +++ b/packages/rocketchat-lib/server/oauth/facebook.js @@ -2,6 +2,7 @@ import { Match, check } from 'meteor/check'; import _ from 'underscore'; import { OAuth } from 'meteor/oauth'; import { HTTP } from 'meteor/http'; + const crypto = Npm.require('crypto'); const whitelisted = [ 'id', diff --git a/packages/rocketchat-lib/server/oauth/proxy.js b/packages/rocketchat-lib/server/oauth/proxy.js index 7770f8fbc13e..31bd5061324d 100644 --- a/packages/rocketchat-lib/server/oauth/proxy.js +++ b/packages/rocketchat-lib/server/oauth/proxy.js @@ -1,10 +1,11 @@ import _ from 'underscore'; import { OAuth } from 'meteor/oauth'; +import { settings } from 'meteor/rocketchat:settings'; OAuth._redirectUri = _.wrap(OAuth._redirectUri, function(func, serviceName, ...args) { - const proxy = RocketChat.settings.get('Accounts_OAuth_Proxy_services').replace(/\s/g, '').split(','); + const proxy = settings.get('Accounts_OAuth_Proxy_services').replace(/\s/g, '').split(','); if (proxy.includes(serviceName)) { - return `${ RocketChat.settings.get('Accounts_OAuth_Proxy_host') }/oauth_redirect`; + return `${ settings.get('Accounts_OAuth_Proxy_host') }/oauth_redirect`; } else { return func(serviceName, ...args); } diff --git a/packages/rocketchat-lib/server/publications/settings.js b/packages/rocketchat-lib/server/publications/settings.js index f15667be700d..64aefc717a09 100644 --- a/packages/rocketchat-lib/server/publications/settings.js +++ b/packages/rocketchat-lib/server/publications/settings.js @@ -1,16 +1,19 @@ import { Meteor } from 'meteor/meteor'; +import { Settings } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Notifications } from 'meteor/rocketchat:notifications'; Meteor.methods({ 'public-settings/get'(updatedAt) { this.unblock(); - const records = RocketChat.models.Settings.findNotHiddenPublic().fetch(); + const records = Settings.findNotHiddenPublic().fetch(); if (updatedAt instanceof Date) { return { update: records.filter(function(record) { return record._updatedAt > updatedAt; }), - remove: RocketChat.models.Settings.trashFindDeletedAfter(updatedAt, { + remove: Settings.trashFindDeletedAfter(updatedAt, { hidden: { $ne: true, }, @@ -30,16 +33,16 @@ Meteor.methods({ return []; } this.unblock(); - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'view-privileged-setting')) { + if (!hasPermission(Meteor.userId(), 'view-privileged-setting')) { return []; } - const records = RocketChat.models.Settings.findNotHidden().fetch(); + const records = Settings.findNotHidden().fetch(); if (updatedAt instanceof Date) { return { update: records.filter(function(record) { return record._updatedAt > updatedAt; }), - remove: RocketChat.models.Settings.trashFindDeletedAfter(updatedAt, { + remove: Settings.trashFindDeletedAfter(updatedAt, { hidden: { $ne: true, }, @@ -55,14 +58,14 @@ Meteor.methods({ }, }); -RocketChat.models.Settings.on('change', ({ clientAction, id, data, diff }) => { +Settings.on('change', ({ clientAction, id, data, diff }) => { if (diff && Object.keys(diff).length === 1 && diff._updatedAt) { // avoid useless changes return; } switch (clientAction) { case 'updated': case 'inserted': - const setting = data || RocketChat.models.Settings.findOneById(id); + const setting = data || Settings.findOneById(id); const value = { _id: setting._id, value: setting.value, @@ -71,22 +74,22 @@ RocketChat.models.Settings.on('change', ({ clientAction, id, data, diff }) => { }; if (setting.public === true) { - RocketChat.Notifications.notifyAllInThisInstance('public-settings-changed', clientAction, value); + Notifications.notifyAllInThisInstance('public-settings-changed', clientAction, value); } else { - RocketChat.Notifications.notifyLoggedInThisInstance('private-settings-changed', clientAction, setting); + Notifications.notifyLoggedInThisInstance('private-settings-changed', clientAction, setting); } break; case 'removed': - RocketChat.Notifications.notifyLoggedInThisInstance('private-settings-changed', clientAction, { _id: id }); - RocketChat.Notifications.notifyAllInThisInstance('public-settings-changed', clientAction, { _id: id }); + Notifications.notifyLoggedInThisInstance('private-settings-changed', clientAction, { _id: id }); + Notifications.notifyAllInThisInstance('public-settings-changed', clientAction, { _id: id }); break; } }); -RocketChat.Notifications.streamAll.allowRead('private-settings-changed', function() { +Notifications.streamAll.allowRead('private-settings-changed', function() { if (this.userId == null) { return false; } - return RocketChat.authz.hasPermission(this.userId, 'view-privileged-setting'); + return hasPermission(this.userId, 'view-privileged-setting'); }); diff --git a/packages/rocketchat-lib/server/startup/email.js b/packages/rocketchat-lib/server/startup/email.js index 49c1252d0f98..1c63fcc4d1a6 100644 --- a/packages/rocketchat-lib/server/startup/email.js +++ b/packages/rocketchat-lib/server/startup/email.js @@ -1,4 +1,6 @@ -RocketChat.settings.addGroup('Email', function() { +import { settings } from 'meteor/rocketchat:settings'; + +settings.addGroup('Email', function() { this.section('Style', function() { this.add('email_style', `html, body, .body { font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,Ubuntu,Cantarell,'Helvetica Neue','Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol','Meiryo UI',Arial,sans-serif; } diff --git a/packages/rocketchat-lib/server/startup/oAuthServicesUpdate.js b/packages/rocketchat-lib/server/startup/oAuthServicesUpdate.js index d320b580ee3c..8496d5623511 100644 --- a/packages/rocketchat-lib/server/startup/oAuthServicesUpdate.js +++ b/packages/rocketchat-lib/server/startup/oAuthServicesUpdate.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { ServiceConfiguration } from 'meteor/service-configuration'; import { CustomOAuth } from 'meteor/rocketchat:custom-oauth'; import { Logger } from 'meteor/rocketchat:logger'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; const logger = new Logger('rocketchat:lib', { @@ -13,7 +14,7 @@ const logger = new Logger('rocketchat:lib', { }); function _OAuthServicesUpdate() { - const services = RocketChat.settings.get(/^(Accounts_OAuth_|Accounts_OAuth_Custom-)[a-z0-9_]+$/i); + const services = settings.get(/^(Accounts_OAuth_|Accounts_OAuth_Custom-)[a-z0-9_]+$/i); services.forEach((service) => { logger.oauth_updated(service.key); let serviceName = service.key.replace('Accounts_OAuth_', ''); @@ -25,26 +26,26 @@ function _OAuthServicesUpdate() { } if (service.value === true) { const data = { - clientId: RocketChat.settings.get(`${ service.key }_id`), - secret: RocketChat.settings.get(`${ service.key }_secret`), + clientId: settings.get(`${ service.key }_id`), + secret: settings.get(`${ service.key }_secret`), }; if (/Accounts_OAuth_Custom-/.test(service.key)) { data.custom = true; - data.clientId = RocketChat.settings.get(`${ service.key }-id`); - data.secret = RocketChat.settings.get(`${ service.key }-secret`); - data.serverURL = RocketChat.settings.get(`${ service.key }-url`); - data.tokenPath = RocketChat.settings.get(`${ service.key }-token_path`); - data.identityPath = RocketChat.settings.get(`${ service.key }-identity_path`); - data.authorizePath = RocketChat.settings.get(`${ service.key }-authorize_path`); - data.scope = RocketChat.settings.get(`${ service.key }-scope`); - data.buttonLabelText = RocketChat.settings.get(`${ service.key }-button_label_text`); - data.buttonLabelColor = RocketChat.settings.get(`${ service.key }-button_label_color`); - data.loginStyle = RocketChat.settings.get(`${ service.key }-login_style`); - data.buttonColor = RocketChat.settings.get(`${ service.key }-button_color`); - data.tokenSentVia = RocketChat.settings.get(`${ service.key }-token_sent_via`); - data.identityTokenSentVia = RocketChat.settings.get(`${ service.key }-identity_token_sent_via`); - data.usernameField = RocketChat.settings.get(`${ service.key }-username_field`); - data.mergeUsers = RocketChat.settings.get(`${ service.key }-merge_users`); + data.clientId = settings.get(`${ service.key }-id`); + data.secret = settings.get(`${ service.key }-secret`); + data.serverURL = settings.get(`${ service.key }-url`); + data.tokenPath = settings.get(`${ service.key }-token_path`); + data.identityPath = settings.get(`${ service.key }-identity_path`); + data.authorizePath = settings.get(`${ service.key }-authorize_path`); + data.scope = settings.get(`${ service.key }-scope`); + data.buttonLabelText = settings.get(`${ service.key }-button_label_text`); + data.buttonLabelColor = settings.get(`${ service.key }-button_label_color`); + data.loginStyle = settings.get(`${ service.key }-login_style`); + data.buttonColor = settings.get(`${ service.key }-button_color`); + data.tokenSentVia = settings.get(`${ service.key }-token_sent_via`); + data.identityTokenSentVia = settings.get(`${ service.key }-identity_token_sent_via`); + data.usernameField = settings.get(`${ service.key }-username_field`); + data.mergeUsers = settings.get(`${ service.key }-merge_users`); new CustomOAuth(serviceName.toLowerCase(), { serverURL: data.serverURL, tokenPath: data.tokenPath, @@ -88,11 +89,11 @@ function OAuthServicesRemove(_id) { }); } -RocketChat.settings.get(/^Accounts_OAuth_.+/, function() { +settings.get(/^Accounts_OAuth_.+/, function() { return OAuthServicesUpdate(); // eslint-disable-line new-cap }); -RocketChat.settings.get(/^Accounts_OAuth_Custom-[a-z0-9_]+/, function(key, value) { +settings.get(/^Accounts_OAuth_Custom-[a-z0-9_]+/, function(key, value) { if (!value) { return OAuthServicesRemove(key);// eslint-disable-line new-cap } diff --git a/packages/rocketchat-lib/server/startup/robots.js b/packages/rocketchat-lib/server/startup/robots.js index 524020ff2dce..44573705b126 100644 --- a/packages/rocketchat-lib/server/startup/robots.js +++ b/packages/rocketchat-lib/server/startup/robots.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { return WebApp.connectHandlers.use('/robots.txt', Meteor.bindEnvironment(function(req, res/* , next*/) { res.writeHead(200); - res.end(RocketChat.settings.get('Robot_Instructions_File_Content')); + res.end(settings.get('Robot_Instructions_File_Content')); })); }); diff --git a/packages/rocketchat-lib/server/startup/settings.js b/packages/rocketchat-lib/server/startup/settings.js index 6204b2c91593..27e72232f85a 100644 --- a/packages/rocketchat-lib/server/startup/settings.js +++ b/packages/rocketchat-lib/server/startup/settings.js @@ -1,8 +1,9 @@ import { Random } from 'meteor/random'; +import { settings } from 'meteor/rocketchat:settings'; import './email'; // Insert server unique id if it doesn't exist -RocketChat.settings.add('uniqueID', process.env.DEPLOYMENT_ID || Random.id(), { +settings.add('uniqueID', process.env.DEPLOYMENT_ID || Random.id(), { public: true, hidden: true, }); @@ -10,7 +11,7 @@ RocketChat.settings.add('uniqueID', process.env.DEPLOYMENT_ID || Random.id(), { // When you define a setting and want to add a description, you don't need to automatically define the i18nDescription // if you add a node to the i18n.json with the same setting name but with `_Description` it will automatically work. -RocketChat.settings.addGroup('Accounts', function() { +settings.addGroup('Accounts', function() { this.add('Accounts_AllowAnonymousRead', false, { type: 'boolean', public: true, @@ -535,7 +536,7 @@ RocketChat.settings.addGroup('Accounts', function() { }); }); -RocketChat.settings.addGroup('OAuth', function() { +settings.addGroup('OAuth', function() { this.section('Facebook', function() { const enableQuery = { _id: 'Accounts_OAuth_Facebook', @@ -692,7 +693,7 @@ RocketChat.settings.addGroup('OAuth', function() { }); }); -RocketChat.settings.addGroup('General', function() { +settings.addGroup('General', function() { this.add('Show_Setup_Wizard', 'pending', { type: 'select', public: true, @@ -898,7 +899,7 @@ RocketChat.settings.addGroup('General', function() { }); }); -RocketChat.settings.addGroup('Message', function() { +settings.addGroup('Message', function() { this.section('Message_Attachments', function() { this.add('Message_Attachments_GroupAttach', false, { type: 'boolean', @@ -1076,7 +1077,7 @@ RocketChat.settings.addGroup('Message', function() { }); }); -RocketChat.settings.addGroup('Meta', function() { +settings.addGroup('Meta', function() { this.add('Meta_language', '', { type: 'string', }); @@ -1099,7 +1100,7 @@ RocketChat.settings.addGroup('Meta', function() { }); }); -RocketChat.settings.addGroup('Push', function() { +settings.addGroup('Push', function() { this.add('Push_enable', true, { type: 'boolean', public: true, @@ -1200,7 +1201,7 @@ RocketChat.settings.addGroup('Push', function() { }); }); -RocketChat.settings.addGroup('Layout', function() { +settings.addGroup('Layout', function() { this.section('Content', function() { this.add('Layout_Home_Title', 'Home', { type: 'string', @@ -1289,7 +1290,7 @@ RocketChat.settings.addGroup('Layout', function() { }); }); -RocketChat.settings.addGroup('Logs', function() { +settings.addGroup('Logs', function() { this.add('Log_Level', '0', { type: 'select', values: [ @@ -1355,7 +1356,7 @@ RocketChat.settings.addGroup('Logs', function() { }); }); -RocketChat.settings.addGroup('Setup_Wizard', function() { +settings.addGroup('Setup_Wizard', function() { this.section('Organization_Info', function() { this.add('Organization_Type', '', { type: 'select', @@ -2666,4 +2667,4 @@ RocketChat.settings.addGroup('Setup_Wizard', function() { }); }); -RocketChat.settings.init(); +settings.init(); diff --git a/packages/rocketchat-lib/server/startup/settingsOnLoadCdnPrefix.js b/packages/rocketchat-lib/server/startup/settingsOnLoadCdnPrefix.js index bf8c2bbc9a52..94cc87095f6f 100644 --- a/packages/rocketchat-lib/server/startup/settingsOnLoadCdnPrefix.js +++ b/packages/rocketchat-lib/server/startup/settingsOnLoadCdnPrefix.js @@ -1,28 +1,29 @@ import { Meteor } from 'meteor/meteor'; import { WebAppInternals } from 'meteor/webapp'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; function testWebAppInternals(fn) { typeof WebAppInternals !== 'undefined' && fn(WebAppInternals); } -RocketChat.settings.onload('CDN_PREFIX', function(key, value) { - const useForAll = RocketChat.settings.get('CDN_PREFIX_ALL'); +settings.onload('CDN_PREFIX', function(key, value) { + const useForAll = settings.get('CDN_PREFIX_ALL'); if (_.isString(value) && value.trim() && useForAll) { return testWebAppInternals((WebAppInternals) => WebAppInternals.setBundledJsCssPrefix(value)); } }); -RocketChat.settings.onload('CDN_JSCSS_PREFIX', function(key, value) { - const useForAll = RocketChat.settings.get('CDN_PREFIX_ALL'); +settings.onload('CDN_JSCSS_PREFIX', function(key, value) { + const useForAll = settings.get('CDN_PREFIX_ALL'); if (_.isString(value) && value.trim() && !useForAll) { return testWebAppInternals((WebAppInternals) => WebAppInternals.setBundledJsCssPrefix(value)); } }); Meteor.startup(function() { - const cdnValue = RocketChat.settings.get('CDN_PREFIX'); - const useForAll = RocketChat.settings.get('CDN_PREFIX_ALL'); - const cdnJsCss = RocketChat.settings.get('CDN_JSCSS_PREFIX'); + const cdnValue = settings.get('CDN_PREFIX'); + const useForAll = settings.get('CDN_PREFIX_ALL'); + const cdnJsCss = settings.get('CDN_JSCSS_PREFIX'); if (_.isString(cdnValue) && cdnValue.trim()) { if (useForAll) { return testWebAppInternals((WebAppInternals) => WebAppInternals.setBundledJsCssPrefix(cdnValue)); diff --git a/packages/rocketchat-lib/server/startup/settingsOnLoadDirectReply.js b/packages/rocketchat-lib/server/startup/settingsOnLoadDirectReply.js index b0a532295b21..8886d01c331e 100644 --- a/packages/rocketchat-lib/server/startup/settingsOnLoadDirectReply.js +++ b/packages/rocketchat-lib/server/startup/settingsOnLoadDirectReply.js @@ -1,12 +1,13 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; import { IMAPIntercepter, POP3Helper } from '../lib/interceptDirectReplyEmails.js'; const startEmailIntercepter = _.debounce(Meteor.bindEnvironment(function() { console.log('Starting Email Intercepter...'); - if (RocketChat.settings.get('Direct_Reply_Enable') && RocketChat.settings.get('Direct_Reply_Protocol') && RocketChat.settings.get('Direct_Reply_Host') && RocketChat.settings.get('Direct_Reply_Port') && RocketChat.settings.get('Direct_Reply_Username') && RocketChat.settings.get('Direct_Reply_Password')) { - if (RocketChat.settings.get('Direct_Reply_Protocol') === 'IMAP') { + if (settings.get('Direct_Reply_Enable') && settings.get('Direct_Reply_Protocol') && settings.get('Direct_Reply_Host') && settings.get('Direct_Reply_Port') && settings.get('Direct_Reply_Username') && settings.get('Direct_Reply_Password')) { + if (settings.get('Direct_Reply_Protocol') === 'IMAP') { // stop already running IMAP instance if (RocketChat.IMAP && RocketChat.IMAP.isActive()) { console.log('Disconnecting already running IMAP instance...'); @@ -30,7 +31,7 @@ const startEmailIntercepter = _.debounce(Meteor.bindEnvironment(function() { RocketChat.IMAP.start(); return true; } - } else if (RocketChat.settings.get('Direct_Reply_Protocol') === 'POP') { + } else if (settings.get('Direct_Reply_Protocol') === 'POP') { // stop already running POP instance if (RocketChat.POP3 && RocketChat.POP3Helper && RocketChat.POP3Helper.isActive()) { console.log('Disconnecting already running POP instance...'); @@ -64,4 +65,4 @@ const startEmailIntercepter = _.debounce(Meteor.bindEnvironment(function() { } }), 1000); -RocketChat.settings.onload(/^Direct_Reply_.+/, startEmailIntercepter); +settings.onload(/^Direct_Reply_.+/, startEmailIntercepter); diff --git a/packages/rocketchat-lib/server/startup/settingsOnLoadSMTP.js b/packages/rocketchat-lib/server/startup/settingsOnLoadSMTP.js index bab4eac13ba2..2abd41e01b11 100644 --- a/packages/rocketchat-lib/server/startup/settingsOnLoadSMTP.js +++ b/packages/rocketchat-lib/server/startup/settingsOnLoadSMTP.js @@ -1,25 +1,26 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; const buildMailURL = _.debounce(function() { console.log('Updating process.env.MAIL_URL'); - if (RocketChat.settings.get('SMTP_Host')) { - process.env.MAIL_URL = `${ RocketChat.settings.get('SMTP_Protocol') }://`; + if (settings.get('SMTP_Host')) { + process.env.MAIL_URL = `${ settings.get('SMTP_Protocol') }://`; - if (RocketChat.settings.get('SMTP_Username') && RocketChat.settings.get('SMTP_Password')) { - process.env.MAIL_URL += `${ encodeURIComponent(RocketChat.settings.get('SMTP_Username')) }:${ encodeURIComponent(RocketChat.settings.get('SMTP_Password')) }@`; + if (settings.get('SMTP_Username') && settings.get('SMTP_Password')) { + process.env.MAIL_URL += `${ encodeURIComponent(settings.get('SMTP_Username')) }:${ encodeURIComponent(settings.get('SMTP_Password')) }@`; } - process.env.MAIL_URL += encodeURIComponent(RocketChat.settings.get('SMTP_Host')); + process.env.MAIL_URL += encodeURIComponent(settings.get('SMTP_Host')); - if (RocketChat.settings.get('SMTP_Port')) { - process.env.MAIL_URL += `:${ parseInt(RocketChat.settings.get('SMTP_Port')) }`; + if (settings.get('SMTP_Port')) { + process.env.MAIL_URL += `:${ parseInt(settings.get('SMTP_Port')) }`; } - process.env.MAIL_URL += `?pool=${ RocketChat.settings.get('SMTP_Pool') }`; + process.env.MAIL_URL += `?pool=${ settings.get('SMTP_Pool') }`; - if (RocketChat.settings.get('SMTP_Protocol') === 'smtp' && RocketChat.settings.get('SMTP_IgnoreTLS')) { + if (settings.get('SMTP_Protocol') === 'smtp' && settings.get('SMTP_IgnoreTLS')) { process.env.MAIL_URL += '&secure=false&ignoreTLS=true'; } @@ -27,37 +28,37 @@ const buildMailURL = _.debounce(function() { } }, 500); -RocketChat.settings.onload('SMTP_Host', function(key, value) { +settings.onload('SMTP_Host', function(key, value) { if (_.isString(value)) { return buildMailURL(); } }); -RocketChat.settings.onload('SMTP_Port', function() { +settings.onload('SMTP_Port', function() { return buildMailURL(); }); -RocketChat.settings.onload('SMTP_Username', function(key, value) { +settings.onload('SMTP_Username', function(key, value) { if (_.isString(value)) { return buildMailURL(); } }); -RocketChat.settings.onload('SMTP_Password', function(key, value) { +settings.onload('SMTP_Password', function(key, value) { if (_.isString(value)) { return buildMailURL(); } }); -RocketChat.settings.onload('SMTP_Protocol', function() { +settings.onload('SMTP_Protocol', function() { return buildMailURL(); }); -RocketChat.settings.onload('SMTP_Pool', function() { +settings.onload('SMTP_Pool', function() { return buildMailURL(); }); -RocketChat.settings.onload('SMTP_IgnoreTLS', function() { +settings.onload('SMTP_IgnoreTLS', function() { return buildMailURL(); }); diff --git a/packages/rocketchat-lib/startup/defaultRoomTypes.js b/packages/rocketchat-lib/startup/defaultRoomTypes.js index 9defe836af70..047b0465dd94 100644 --- a/packages/rocketchat-lib/startup/defaultRoomTypes.js +++ b/packages/rocketchat-lib/startup/defaultRoomTypes.js @@ -1,3 +1,4 @@ +import { roomTypes } from 'meteor/rocketchat:utils'; import { ConversationRoomType, DirectMessageRoomType, @@ -7,9 +8,9 @@ import { UnreadRoomType, } from '../lib/roomTypes'; -RocketChat.roomTypes.add(new UnreadRoomType()); -RocketChat.roomTypes.add(new FavoriteRoomType()); -RocketChat.roomTypes.add(new ConversationRoomType()); -RocketChat.roomTypes.add(new PublicRoomType()); -RocketChat.roomTypes.add(new PrivateRoomType()); -RocketChat.roomTypes.add(new DirectMessageRoomType()); +roomTypes.add(new UnreadRoomType()); +roomTypes.add(new FavoriteRoomType()); +roomTypes.add(new ConversationRoomType()); +roomTypes.add(new PublicRoomType()); +roomTypes.add(new PrivateRoomType()); +roomTypes.add(new DirectMessageRoomType()); From f3280a69113e62577ed573266e3df59f48f6afbe Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 16:04:54 -0200 Subject: [PATCH 08/18] Remove duplicated server settings located in rc-lib --- packages/rocketchat-lib/package.js | 1 - .../server/functions/settings.js | 297 ------------------ packages/rocketchat-lib/startup/index.js | 3 +- packages/rocketchat-models/package.js | 1 - .../server/models/Messages.js | 13 +- .../rocketchat-models/server/models/Users.js | 11 +- .../server/models/_BaseDb.js | 15 +- packages/rocketchat-settings/package.js | 1 + .../server/functions/settings.js | 63 +--- 9 files changed, 50 insertions(+), 355 deletions(-) delete mode 100644 packages/rocketchat-lib/server/functions/settings.js diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 8d856d350958..80a3bf8ee166 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -123,7 +123,6 @@ Package.onUse(function(api) { api.addFiles('server/functions/saveCustomFields.js', 'server'); api.addFiles('server/functions/saveCustomFieldsWithoutValidation.js', 'server'); api.addFiles('server/functions/sendMessage.js', 'server'); - api.addFiles('server/functions/settings.js', 'server'); api.addFiles('server/functions/setUserAvatar.js', 'server'); api.addFiles('server/functions/setUsername.js', 'server'); api.addFiles('server/functions/setRealName.js', 'server'); diff --git a/packages/rocketchat-lib/server/functions/settings.js b/packages/rocketchat-lib/server/functions/settings.js deleted file mode 100644 index 4ffe64fc9250..000000000000 --- a/packages/rocketchat-lib/server/functions/settings.js +++ /dev/null @@ -1,297 +0,0 @@ -import { Meteor } from 'meteor/meteor'; -import _ from 'underscore'; - -const blockedSettings = {}; - -if (process.env.SETTINGS_BLOCKED) { - process.env.SETTINGS_BLOCKED.split(',').forEach((settingId) => blockedSettings[settingId] = 1); -} - -const hiddenSettings = {}; -if (process.env.SETTINGS_HIDDEN) { - process.env.SETTINGS_HIDDEN.split(',').forEach((settingId) => hiddenSettings[settingId] = 1); -} - -RocketChat.settings._sorter = {}; - - -/* -* Add a setting -* @param {String} _id -* @param {Mixed} value -* @param {Object} setting -*/ - -RocketChat.settings.add = function(_id, value, options = {}) { - if (options == null) { - options = {}; - } - if (!_id || value == null) { - return false; - } - if (RocketChat.settings._sorter[options.group] == null) { - RocketChat.settings._sorter[options.group] = 0; - } - options.packageValue = value; - options.valueSource = 'packageValue'; - options.hidden = options.hidden || false; - options.blocked = options.blocked || false; - if (options.sorter == null) { - options.sorter = RocketChat.settings._sorter[options.group]++; - } - if (options.enableQuery != null) { - options.enableQuery = JSON.stringify(options.enableQuery); - } - if (options.i18nDefaultQuery != null) { - options.i18nDefaultQuery = JSON.stringify(options.i18nDefaultQuery); - } - if (typeof process !== 'undefined' && process.env && process.env[_id]) { - value = process.env[_id]; - if (value.toLowerCase() === 'true') { - value = true; - } else if (value.toLowerCase() === 'false') { - value = false; - } else if (options.type === 'int') { - value = parseInt(value); - } - options.processEnvValue = value; - options.valueSource = 'processEnvValue'; - } else if (Meteor.settings && typeof Meteor.settings[_id] !== 'undefined') { - if (Meteor.settings[_id] == null) { - return false; - } - - value = Meteor.settings[_id]; - options.meteorSettingsValue = value; - options.valueSource = 'meteorSettingsValue'; - } - if (options.i18nLabel == null) { - options.i18nLabel = _id; - } - if (options.i18nDescription == null) { - options.i18nDescription = `${ _id }_Description`; - } - if (blockedSettings[_id] != null) { - options.blocked = true; - } - if (hiddenSettings[_id] != null) { - options.hidden = true; - } - if (options.autocomplete == null) { - options.autocomplete = true; - } - if (typeof process !== 'undefined' && process.env && process.env[`OVERWRITE_SETTING_${ _id }`]) { - let value = process.env[`OVERWRITE_SETTING_${ _id }`]; - if (value.toLowerCase() === 'true') { - value = true; - } else if (value.toLowerCase() === 'false') { - value = false; - } else if (options.type === 'int') { - value = parseInt(value); - } - options.value = value; - options.processEnvValue = value; - options.valueSource = 'processEnvValue'; - } - const updateOperations = { - $set: options, - $setOnInsert: { - createdAt: new Date, - }, - }; - if (options.editor != null) { - updateOperations.$setOnInsert.editor = options.editor; - delete options.editor; - } - if (options.value == null) { - if (options.force === true) { - updateOperations.$set.value = options.packageValue; - } else { - updateOperations.$setOnInsert.value = value; - } - } - const query = _.extend({ - _id, - }, updateOperations.$set); - if (options.section == null) { - updateOperations.$unset = { - section: 1, - }; - query.section = { - $exists: false, - }; - } - const existantSetting = RocketChat.models.Settings.db.findOne(query); - if (existantSetting != null) { - if (existantSetting.editor == null && updateOperations.$setOnInsert.editor != null) { - updateOperations.$set.editor = updateOperations.$setOnInsert.editor; - delete updateOperations.$setOnInsert.editor; - } - } else { - updateOperations.$set.ts = new Date; - } - return RocketChat.models.Settings.upsert({ - _id, - }, updateOperations); -}; - - -/* -* Add a setting group -* @param {String} _id -*/ - -RocketChat.settings.addGroup = function(_id, options = {}, cb) { - if (!_id) { - return false; - } - if (_.isFunction(options)) { - cb = options; - options = {}; - } - if (options.i18nLabel == null) { - options.i18nLabel = _id; - } - if (options.i18nDescription == null) { - options.i18nDescription = `${ _id }_Description`; - } - options.ts = new Date; - options.blocked = false; - options.hidden = false; - if (blockedSettings[_id] != null) { - options.blocked = true; - } - if (hiddenSettings[_id] != null) { - options.hidden = true; - } - RocketChat.models.Settings.upsert({ - _id, - }, { - $set: options, - $setOnInsert: { - type: 'group', - createdAt: new Date, - }, - }); - if (cb != null) { - cb.call({ - add(id, value, options) { - if (options == null) { - options = {}; - } - options.group = _id; - return RocketChat.settings.add(id, value, options); - }, - section(section, cb) { - return cb.call({ - add(id, value, options) { - if (options == null) { - options = {}; - } - options.group = _id; - options.section = section; - return RocketChat.settings.add(id, value, options); - }, - }); - }, - }); - } -}; - - -/* -* Remove a setting by id -* @param {String} _id -*/ - -RocketChat.settings.removeById = function(_id) { - if (!_id) { - return false; - } - return RocketChat.models.Settings.removeById(_id); -}; - - -/* -* Update a setting by id -* @param {String} _id -*/ - -RocketChat.settings.updateById = function(_id, value, editor) { - if (!_id || value == null) { - return false; - } - if (editor != null) { - return RocketChat.models.Settings.updateValueAndEditorById(_id, value, editor); - } - return RocketChat.models.Settings.updateValueById(_id, value); -}; - - -/* -* Update options of a setting by id -* @param {String} _id -*/ - -RocketChat.settings.updateOptionsById = function(_id, options) { - if (!_id || options == null) { - return false; - } - return RocketChat.models.Settings.updateOptionsById(_id, options); -}; - - -/* -* Update a setting by id -* @param {String} _id -*/ - -RocketChat.settings.clearById = function(_id) { - if (_id == null) { - return false; - } - return RocketChat.models.Settings.updateValueById(_id, undefined); -}; - - -/* -* Update a setting by id -*/ - -RocketChat.settings.init = function() { - RocketChat.settings.initialLoad = true; - RocketChat.models.Settings.find().observe({ - added(record) { - Meteor.settings[record._id] = record.value; - if (record.env === true) { - process.env[record._id] = record.value; - } - return RocketChat.settings.load(record._id, record.value, RocketChat.settings.initialLoad); - }, - changed(record) { - Meteor.settings[record._id] = record.value; - if (record.env === true) { - process.env[record._id] = record.value; - } - return RocketChat.settings.load(record._id, record.value, RocketChat.settings.initialLoad); - }, - removed(record) { - delete Meteor.settings[record._id]; - if (record.env === true) { - delete process.env[record._id]; - } - return RocketChat.settings.load(record._id, undefined, RocketChat.settings.initialLoad); - }, - }); - RocketChat.settings.initialLoad = false; - RocketChat.settings.afterInitialLoad.forEach((fn) => fn(Meteor.settings)); -}; - -RocketChat.settings.afterInitialLoad = []; - -RocketChat.settings.onAfterInitialLoad = function(fn) { - RocketChat.settings.afterInitialLoad.push(fn); - if (RocketChat.settings.initialLoad === false) { - return fn(Meteor.settings); - } -}; diff --git a/packages/rocketchat-lib/startup/index.js b/packages/rocketchat-lib/startup/index.js index ebfc1a2c6047..90c94606f7c8 100644 --- a/packages/rocketchat-lib/startup/index.js +++ b/packages/rocketchat-lib/startup/index.js @@ -1,3 +1,4 @@ import * as Mailer from 'meteor/rocketchat:mailer'; +import { settings } from 'meteor/rocketchat:settings'; -Mailer.setSettings(RocketChat.settings); +Mailer.setSettings(settings); diff --git a/packages/rocketchat-models/package.js b/packages/rocketchat-models/package.js index f09b9482f4aa..63cd19c90037 100755 --- a/packages/rocketchat-models/package.js +++ b/packages/rocketchat-models/package.js @@ -8,7 +8,6 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:settings', 'rocketchat:callbacks', 'rocketchat:ui-cached-collection', 'konecty:multiple-instances-status', diff --git a/packages/rocketchat-models/server/models/Messages.js b/packages/rocketchat-models/server/models/Messages.js index d56c4a255ba3..de009f321fef 100644 --- a/packages/rocketchat-models/server/models/Messages.js +++ b/packages/rocketchat-models/server/models/Messages.js @@ -1,6 +1,5 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { settings } from 'meteor/rocketchat:settings'; import { Base } from './_Base'; import Rooms from './Rooms'; import Users from './Users'; @@ -24,6 +23,14 @@ export class Messages extends Base { this.tryEnsureIndex({ snippeted: 1 }, { sparse: 1 }); this.tryEnsureIndex({ location: '2dsphere' }); this.tryEnsureIndex({ slackBotId: 1, slackTs: 1 }, { sparse: 1 }); + this.loadSettings(); + } + + loadSettings() { + Meteor.startup(async() => { + const { settings } = await import('meteor/rocketchat:settings'); + this.settings = settings; + }); } countVisibleByRoomIdBetweenTimestampsInclusive(roomId, afterTimestamp, beforeTimestamp, options) { @@ -600,7 +607,7 @@ export class Messages extends Base { groupable: false, }; - if (settings.get('Message_Read_Receipt_Enabled')) { + if (this.settings.get('Message_Read_Receipt_Enabled')) { record.unread = true; } @@ -629,7 +636,7 @@ export class Messages extends Base { groupable: false, }; - if (settings.get('Message_Read_Receipt_Enabled')) { + if (this.settings.get('Message_Read_Receipt_Enabled')) { record.unread = true; } diff --git a/packages/rocketchat-models/server/models/Users.js b/packages/rocketchat-models/server/models/Users.js index 7206dd9d9f6e..f90e64fa4a93 100644 --- a/packages/rocketchat-models/server/models/Users.js +++ b/packages/rocketchat-models/server/models/Users.js @@ -1,6 +1,5 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { settings } from 'meteor/rocketchat:settings'; import { Base } from './_Base'; import Subscriptions from './Subscriptions'; import _ from 'underscore'; @@ -17,6 +16,14 @@ export class Users extends Base { this.tryEnsureIndex({ active: 1 }, { sparse: 1 }); this.tryEnsureIndex({ statusConnection: 1 }, { sparse: 1 }); this.tryEnsureIndex({ type: 1 }); + this.loadSettings(); + } + + loadSettings() { + Meteor.startup(async() => { + const { settings } = await import('meteor/rocketchat:settings'); + this.settings = settings; + }); } roleBaseQuery(userId) { @@ -200,7 +207,7 @@ export class Users extends Base { const termRegex = new RegExp(s.escapeRegExp(searchTerm), 'i'); - const orStmt = _.reduce(settings.get('Accounts_SearchFields').trim().split(','), function(acc, el) { + const orStmt = _.reduce(this.settings.get('Accounts_SearchFields').trim().split(','), function(acc, el) { acc.push({ [el.trim()]: termRegex }); return acc; }, []); diff --git a/packages/rocketchat-models/server/models/_BaseDb.js b/packages/rocketchat-models/server/models/_BaseDb.js index fea2c84cab0a..d32642bcc145 100644 --- a/packages/rocketchat-models/server/models/_BaseDb.js +++ b/packages/rocketchat-models/server/models/_BaseDb.js @@ -1,6 +1,6 @@ +import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Mongo, MongoInternals } from 'meteor/mongo'; -import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; import { EventEmitter } from 'events'; @@ -16,9 +16,6 @@ try { const isOplogAvailable = MongoInternals.defaultRemoteCollectionDriver().mongo._oplogHandle && !!MongoInternals.defaultRemoteCollectionDriver().mongo._oplogHandle.onOplogEntry; let isOplogEnabled = isOplogAvailable; -settings.get('Force_Disable_OpLog_For_Cache', (key, value) => { - isOplogEnabled = isOplogAvailable && value === false; -}); export class BaseDb extends EventEmitter { constructor(model, baseModel) { @@ -39,6 +36,7 @@ export class BaseDb extends EventEmitter { this.wrapModel(); let alreadyListeningToOplog = false; + this.listenSettings(); // When someone start listening for changes we start oplog if available this.on('newListener', (event/* , listener*/) => { if (event === 'change' && alreadyListeningToOplog === false) { @@ -57,6 +55,15 @@ export class BaseDb extends EventEmitter { this.tryEnsureIndex({ _updatedAt: 1 }); } + listenSettings() { + Meteor.startup(async() => { + const { settings } = await import('meteor/rocketchat:settings'); + settings.get('Force_Disable_OpLog_For_Cache', (key, value) => { + isOplogEnabled = isOplogAvailable && value === false; + }); + }); + } + get baseName() { return baseName; } diff --git a/packages/rocketchat-settings/package.js b/packages/rocketchat-settings/package.js index 227969519e91..577c3640ce3e 100644 --- a/packages/rocketchat-settings/package.js +++ b/packages/rocketchat-settings/package.js @@ -9,6 +9,7 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'rocketchat:ui-cached-collection', + 'rocketchat:models', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-settings/server/functions/settings.js b/packages/rocketchat-settings/server/functions/settings.js index 408e31c4450f..ba37d75c9d63 100644 --- a/packages/rocketchat-settings/server/functions/settings.js +++ b/packages/rocketchat-settings/server/functions/settings.js @@ -1,9 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { settings } from '../../lib/settings'; +import { Settings } from 'meteor/rocketchat:models'; import _ from 'underscore'; -let _Settings; - const blockedSettings = {}; if (process.env.SETTINGS_BLOCKED) { @@ -25,11 +24,7 @@ settings._sorter = {}; * @param {Object} setting */ -settings.add = async function(_id, value, options = {}) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.add = function(_id, value, options = {}) { if (options == null) { options = {}; } @@ -128,7 +123,7 @@ settings.add = async function(_id, value, options = {}) { $exists: false, }; } - const existantSetting = _Settings.db.findOne(query); + const existantSetting = Settings.db.findOne(query); if (existantSetting != null) { if (existantSetting.editor == null && updateOperations.$setOnInsert.editor != null) { updateOperations.$set.editor = updateOperations.$setOnInsert.editor; @@ -137,7 +132,7 @@ settings.add = async function(_id, value, options = {}) { } else { updateOperations.$set.ts = new Date; } - return _Settings.upsert({ + return Settings.upsert({ _id, }, updateOperations); }; @@ -148,11 +143,7 @@ settings.add = async function(_id, value, options = {}) { * @param {String} _id */ -settings.addGroup = async function(_id, options = {}, cb) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.addGroup = function(_id, options = {}, cb) { if (!_id) { return false; } @@ -175,7 +166,7 @@ settings.addGroup = async function(_id, options = {}, cb) { if (hiddenSettings[_id] != null) { options.hidden = true; } - _Settings.upsert({ + Settings.upsert({ _id, }, { $set: options, @@ -215,15 +206,11 @@ settings.addGroup = async function(_id, options = {}, cb) { * @param {String} _id */ -settings.removeById = async function(_id) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.removeById = function(_id) { if (!_id) { return false; } - return _Settings.removeById(_id); + return Settings.removeById(_id); }; @@ -232,18 +219,14 @@ settings.removeById = async function(_id) { * @param {String} _id */ -settings.updateById = async function(_id, value, editor) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.updateById = function(_id, value, editor) { if (!_id || value == null) { return false; } if (editor != null) { - return _Settings.updateValueAndEditorById(_id, value, editor); + return Settings.updateValueAndEditorById(_id, value, editor); } - return _Settings.updateValueById(_id, value); + return Settings.updateValueById(_id, value); }; @@ -252,15 +235,11 @@ settings.updateById = async function(_id, value, editor) { * @param {String} _id */ -settings.updateOptionsById = async function(_id, options) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.updateOptionsById = function(_id, options) { if (!_id || options == null) { return false; } - return _Settings.updateOptionsById(_id, options); + return Settings.updateOptionsById(_id, options); }; @@ -269,15 +248,11 @@ settings.updateOptionsById = async function(_id, options) { * @param {String} _id */ -settings.clearById = async function(_id) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.clearById = function(_id) { if (_id == null) { return false; } - return _Settings.updateValueById(_id, undefined); + return Settings.updateValueById(_id, undefined); }; @@ -285,13 +260,9 @@ settings.clearById = async function(_id) { * Update a setting by id */ -settings.init = async function() { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.init = function() { settings.initialLoad = true; - _Settings.find().observe({ + Settings.find().observe({ added(record) { Meteor.settings[record._id] = record.value; if (record.env === true) { From f457877396ae7fdf687ac72d71bffa43cc38b742 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 18:09:03 -0200 Subject: [PATCH 09/18] Export function and lib function of rc-lib but keep it inside RC namespace --- .../functions/addUserToDefaultChannels.js | 5 +++- .../server/functions/addUserToRoom.js | 4 ++- .../server/functions/archiveRoom.js | 4 ++- .../functions/checkEmailAvailability.js | 4 ++- .../functions/checkUsernameAvailability.js | 4 ++- .../server/functions/cleanRoomHistory.js | 4 ++- .../server/functions/createRoom.js | 4 ++- .../server/functions/deleteMessage.js | 4 ++- .../server/functions/deleteUser.js | 4 ++- .../server/functions/getFullUserData.js | 5 +++- .../getRoomByNameOrIdWithOptionToJoin.js | 4 ++- .../rocketchat-lib/server/functions/index.js | 25 +++++++++++++++++++ .../server/functions/isTheLastMessage.js | 4 ++- .../server/functions/loadMessageHistory.js | 4 ++- .../server/functions/removeUserFromRoom.js | 4 ++- .../server/functions/saveCustomFields.js | 4 ++- .../saveCustomFieldsWithoutValidation.js | 4 ++- .../server/functions/saveUser.js | 4 ++- .../server/functions/sendMessage.js | 4 ++- .../server/functions/setEmail.js | 6 +++-- .../server/functions/setRealName.js | 6 +++-- .../server/functions/setUserAvatar.js | 4 ++- .../server/functions/setUsername.js | 6 +++-- .../server/functions/unarchiveRoom.js | 4 ++- .../server/functions/updateMessage.js | 4 ++- .../server/functions/validateCustomFields.js | 4 ++- .../rocketchat-lib/server/lib/RateLimiter.js | 4 ++- packages/rocketchat-lib/server/lib/index.js | 8 ++++++ .../server/lib/validateEmailDomain.js | 4 ++- 29 files changed, 119 insertions(+), 30 deletions(-) create mode 100644 packages/rocketchat-lib/server/functions/index.js diff --git a/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js b/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js index df411a6d0616..e967b22e280a 100644 --- a/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js +++ b/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js @@ -2,7 +2,7 @@ import { Rooms, Subscriptions, Messages } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.addUserToDefaultChannels = function(user, silenced) { +export const addUserToDefaultChannels = function(user, silenced) { callbacks.run('beforeJoinDefaultChannels', user); const defaultRooms = Rooms.findByDefaultAndTypes(true, ['c', 'p'], { fields: { usernames: 0 } }).fetch(); defaultRooms.forEach((room) => { @@ -32,3 +32,6 @@ RocketChat.addUserToDefaultChannels = function(user, silenced) { } }); }; + +RocketChat.addUserToDefaultChannels = addUserToDefaultChannels; + diff --git a/packages/rocketchat-lib/server/functions/addUserToRoom.js b/packages/rocketchat-lib/server/functions/addUserToRoom.js index c9e22dbad3b0..d67cd6dfd555 100644 --- a/packages/rocketchat-lib/server/functions/addUserToRoom.js +++ b/packages/rocketchat-lib/server/functions/addUserToRoom.js @@ -3,7 +3,7 @@ import { Rooms, Subscriptions, Messages } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.addUserToRoom = function(rid, user, inviter, silenced) { +export const addUserToRoom = function(rid, user, inviter, silenced) { const now = new Date(); const room = Rooms.findOneById(rid); @@ -53,3 +53,5 @@ RocketChat.addUserToRoom = function(rid, user, inviter, silenced) { return true; }; + +RocketChat.addUserToRoom = addUserToRoom; diff --git a/packages/rocketchat-lib/server/functions/archiveRoom.js b/packages/rocketchat-lib/server/functions/archiveRoom.js index c906746c9c42..40a76a95f12d 100644 --- a/packages/rocketchat-lib/server/functions/archiveRoom.js +++ b/packages/rocketchat-lib/server/functions/archiveRoom.js @@ -2,9 +2,11 @@ import { Meteor } from 'meteor/meteor'; import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.archiveRoom = function(rid) { +export const archiveRoom = function(rid) { Rooms.archiveById(rid); Subscriptions.archiveByRoomId(rid); callbacks.run('afterRoomArchived', Rooms.findOneById(rid), Meteor.user()); }; + +RocketChat.archiveRoom = archiveRoom; diff --git a/packages/rocketchat-lib/server/functions/checkEmailAvailability.js b/packages/rocketchat-lib/server/functions/checkEmailAvailability.js index 3e892c5f19ac..6c5263c4f730 100644 --- a/packages/rocketchat-lib/server/functions/checkEmailAvailability.js +++ b/packages/rocketchat-lib/server/functions/checkEmailAvailability.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import s from 'underscore.string'; -RocketChat.checkEmailAvailability = function(email) { +export const checkEmailAvailability = function(email) { return !Meteor.users.findOne({ 'emails.address': { $regex : new RegExp(`^${ s.trim(s.escapeRegExp(email)) }$`, 'i') } }); }; + +RocketChat.checkEmailAvailability = checkEmailAvailability; diff --git a/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js b/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js index 6a3027b773b3..8f4509cb8be0 100644 --- a/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js +++ b/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js @@ -13,7 +13,7 @@ settings.get('Accounts_BlockedUsernameList', (key, value) => { const usernameIsBlocked = (username, usernameBlackList) => usernameBlackList.length && usernameBlackList.some((restrictedUsername) => restrictedUsername.test(s.trim(s.escapeRegExp(username)))); -RocketChat.checkUsernameAvailability = function(username) { +export const checkUsernameAvailability = function(username) { if (usernameIsBlocked(username, usernameBlackList)) { return false; @@ -25,3 +25,5 @@ RocketChat.checkUsernameAvailability = function(username) { }, }, { fields: { _id: 1 } }); }; + +RocketChat.checkUsernameAvailability = checkUsernameAvailability; diff --git a/packages/rocketchat-lib/server/functions/cleanRoomHistory.js b/packages/rocketchat-lib/server/functions/cleanRoomHistory.js index 2004db0157c0..967e7105415a 100644 --- a/packages/rocketchat-lib/server/functions/cleanRoomHistory.js +++ b/packages/rocketchat-lib/server/functions/cleanRoomHistory.js @@ -3,7 +3,7 @@ import { FileUpload } from 'meteor/rocketchat:file-upload'; import { Messages, Rooms } from 'meteor/rocketchat:models'; import { Notifications } from 'meteor/rocketchat:notifications'; -RocketChat.cleanRoomHistory = function({ rid, latest = new Date(), oldest = new Date('0001-01-01T00:00:00Z'), inclusive = true, limit = 0, excludePinned = true, filesOnly = false, fromUsers = [] }) { +export const cleanRoomHistory = function({ rid, latest = new Date(), oldest = new Date('0001-01-01T00:00:00Z'), inclusive = true, limit = 0, excludePinned = true, filesOnly = false, fromUsers = [] }) { const gt = inclusive ? '$gte' : '$gt'; const lt = inclusive ? '$lte' : '$lt'; @@ -42,3 +42,5 @@ RocketChat.cleanRoomHistory = function({ rid, latest = new Date(), oldest = new } return count; }; + +RocketChat.cleanRoomHistory = cleanRoomHistory; diff --git a/packages/rocketchat-lib/server/functions/createRoom.js b/packages/rocketchat-lib/server/functions/createRoom.js index 33293ceead7e..ca2154fd8290 100644 --- a/packages/rocketchat-lib/server/functions/createRoom.js +++ b/packages/rocketchat-lib/server/functions/createRoom.js @@ -6,7 +6,7 @@ import { getValidRoomName } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import s from 'underscore.string'; -RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData = {}) { +export const createRoom = function(type, name, owner, members, readOnly, extraData = {}) { name = s.trim(name); owner = s.trim(owner); members = [].concat(members); @@ -118,3 +118,5 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData name: room.name, }; }; + +RocketChat.createRoom = createRoom; diff --git a/packages/rocketchat-lib/server/functions/deleteMessage.js b/packages/rocketchat-lib/server/functions/deleteMessage.js index d34152a0e95b..5c0c634d8d45 100644 --- a/packages/rocketchat-lib/server/functions/deleteMessage.js +++ b/packages/rocketchat-lib/server/functions/deleteMessage.js @@ -5,7 +5,7 @@ import { Messages, Uploads, Rooms } from 'meteor/rocketchat:models'; import { Notifications } from 'meteor/rocketchat:notifications'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.deleteMessage = function(message, user) { +export const deleteMessage = function(message, user) { const keepHistory = settings.get('Message_KeepHistory'); const showDeletedStatus = settings.get('Message_ShowDeletedStatus'); const deletedMsg = Messages.findOneById(message._id); @@ -59,3 +59,5 @@ RocketChat.deleteMessage = function(message, user) { Apps.getBridges().getListenerBridge().messageEvent('IPostMessageDeleted', deletedMsg); } }; + +RocketChat.deleteMessage = deleteMessage; diff --git a/packages/rocketchat-lib/server/functions/deleteUser.js b/packages/rocketchat-lib/server/functions/deleteUser.js index 85a0445c7756..6fe92b5ac8dd 100644 --- a/packages/rocketchat-lib/server/functions/deleteUser.js +++ b/packages/rocketchat-lib/server/functions/deleteUser.js @@ -6,7 +6,7 @@ import { hasRole, getUsersInRole } from 'meteor/rocketchat:authorization'; import { settings } from 'meteor/rocketchat:settings'; import { Notifications } from 'meteor/rocketchat:notifications'; -RocketChat.deleteUser = function(userId) { +export const deleteUser = function(userId) { const user = Users.findOneById(userId, { fields: { username: 1, avatarOrigin: 1 }, }); @@ -97,3 +97,5 @@ RocketChat.deleteUser = function(userId) { Users.removeById(userId); // Remove user from users database }; + +RocketChat.deleteUser = deleteUser; diff --git a/packages/rocketchat-lib/server/functions/getFullUserData.js b/packages/rocketchat-lib/server/functions/getFullUserData.js index 78ccac34e372..502ba1555286 100644 --- a/packages/rocketchat-lib/server/functions/getFullUserData.js +++ b/packages/rocketchat-lib/server/functions/getFullUserData.js @@ -53,7 +53,7 @@ settings.get('Accounts_CustomFields', (key, value) => { } }); -RocketChat.getFullUserData = function({ userId, filter, limit: l }) { +export const getFullUserData = function({ userId, filter, limit: l }) { const username = s.trim(filter); const userToRetrieveFullUserData = Users.findOneByUsername(username); const isMyOwnInfo = userToRetrieveFullUserData && userToRetrieveFullUserData._id === userId; @@ -83,3 +83,6 @@ RocketChat.getFullUserData = function({ userId, filter, limit: l }) { const usernameReg = new RegExp(s.escapeRegExp(username), 'i'); return Users.findByUsernameNameOrEmailAddress(usernameReg, options); }; + +RocketChat.getFullUserData = getFullUserData; + diff --git a/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js b/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js index 5a0ff29f2ed5..88299f99598b 100644 --- a/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js +++ b/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js @@ -2,7 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Rooms, Users, Subscriptions } from 'meteor/rocketchat:models'; import _ from 'underscore'; -RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOptionToJoin({ currentUserId, nameOrId, type = '', tryDirectByUserIdOnly = false, joinChannel = true, errorOnEmpty = true }) { +export const getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOptionToJoin({ currentUserId, nameOrId, type = '', tryDirectByUserIdOnly = false, joinChannel = true, errorOnEmpty = true }) { let room; // If the nameOrId starts with #, then let's try to find a channel or group @@ -79,3 +79,5 @@ RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOp return room; }; + +RocketChat.getRoomByNameOrIdWithOptionToJoin = getRoomByNameOrIdWithOptionToJoin; diff --git a/packages/rocketchat-lib/server/functions/index.js b/packages/rocketchat-lib/server/functions/index.js new file mode 100644 index 000000000000..11eac02244a3 --- /dev/null +++ b/packages/rocketchat-lib/server/functions/index.js @@ -0,0 +1,25 @@ +export { addUserToDefaultChannels } from './addUserToDefaultChannels'; +export { addUserToRoom } from './addUserToRoom'; +export { archiveRoom } from './archiveRoom'; +export { checkEmailAvailability } from './checkEmailAvailability'; +export { checkUsernameAvailability } from './checkUsernameAvailability'; +export { cleanRoomHistory } from './cleanRoomHistory'; +export { createRoom } from './createRoom'; +export { deleteMessage } from './deleteMessage'; +export { deleteUser } from './deleteUser'; +export { getFullUserData } from './getFullUserData'; +export { getRoomByNameOrIdWithOptionToJoin } from './getRoomByNameOrIdWithOptionToJoin'; +export { isTheLastMessage } from './isTheLastMessage'; +export { loadMessageHistory } from './loadMessageHistory'; +export { removeUserFromRoom } from './removeUserFromRoom'; +export { saveCustomFields } from './saveCustomFields'; +export { saveCustomFieldsWithoutValidation } from './saveCustomFieldsWithoutValidation'; +export { saveUser } from './saveUser'; +export { sendMessage } from './sendMessage'; +export { setEmail } from './setEmail'; +export { setRealName } from './setRealName'; +export { setUserAvatar } from './setUserAvatar'; +export { setUsername } from './setUsername'; +export { unarchiveRoom } from './unarchiveRoom'; +export { updateMessage } from './updateMessage'; +export { validateCustomFields } from './validateCustomFields'; diff --git a/packages/rocketchat-lib/server/functions/isTheLastMessage.js b/packages/rocketchat-lib/server/functions/isTheLastMessage.js index 5fe73fb08de6..57300e5e061d 100644 --- a/packages/rocketchat-lib/server/functions/isTheLastMessage.js +++ b/packages/rocketchat-lib/server/functions/isTheLastMessage.js @@ -1,3 +1,5 @@ import { settings } from 'meteor/rocketchat:settings'; -RocketChat.isTheLastMessage = (room, message) => settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id); +export const isTheLastMessage = (room, message) => settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id); + +RocketChat.isTheLastMessage = isTheLastMessage; diff --git a/packages/rocketchat-lib/server/functions/loadMessageHistory.js b/packages/rocketchat-lib/server/functions/loadMessageHistory.js index 873a5aff01d9..421f39d5fbd6 100644 --- a/packages/rocketchat-lib/server/functions/loadMessageHistory.js +++ b/packages/rocketchat-lib/server/functions/loadMessageHistory.js @@ -21,7 +21,7 @@ settings.get(/Message_HideType_.+/, function(key, value) { }); }); -RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, limit = 20, ls }) { +export const loadMessageHistory = function loadMessageHistory({ userId, rid, end, limit = 20, ls }) { const options = { sort: { ts: -1, @@ -69,3 +69,5 @@ RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, unreadNotLoaded, }; }; + +RocketChat.loadMessageHistory = loadMessageHistory; diff --git a/packages/rocketchat-lib/server/functions/removeUserFromRoom.js b/packages/rocketchat-lib/server/functions/removeUserFromRoom.js index 2eb8ceed6737..0f100783447c 100644 --- a/packages/rocketchat-lib/server/functions/removeUserFromRoom.js +++ b/packages/rocketchat-lib/server/functions/removeUserFromRoom.js @@ -2,7 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Rooms, Messages, Subscriptions } from 'meteor/rocketchat:models'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.removeUserFromRoom = function(rid, user) { +export const removeUserFromRoom = function(rid, user) { const room = Rooms.findOneById(rid); if (room) { @@ -27,3 +27,5 @@ RocketChat.removeUserFromRoom = function(rid, user) { }); } }; + +RocketChat.removeUserFromRoom = removeUserFromRoom; diff --git a/packages/rocketchat-lib/server/functions/saveCustomFields.js b/packages/rocketchat-lib/server/functions/saveCustomFields.js index 86f9f3dab82a..292ddfbbdee8 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFields.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFields.js @@ -1,9 +1,11 @@ import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; -RocketChat.saveCustomFields = function(userId, formData) { +export const saveCustomFields = function(userId, formData) { if (s.trim(settings.get('Accounts_CustomFields')) !== '') { RocketChat.validateCustomFields(formData); return RocketChat.saveCustomFieldsWithoutValidation(userId, formData); } }; + +RocketChat.saveCustomFields = saveCustomFields; diff --git a/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js b/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js index e73019e5c14f..65a7b68a457e 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js @@ -3,7 +3,7 @@ import { settings } from 'meteor/rocketchat:settings'; import { Users, Subscriptions } from 'meteor/rocketchat:models'; import s from 'underscore.string'; -RocketChat.saveCustomFieldsWithoutValidation = function(userId, formData) { +export const saveCustomFieldsWithoutValidation = function(userId, formData) { if (s.trim(settings.get('Accounts_CustomFields')) !== '') { let customFieldsMeta; try { @@ -38,3 +38,5 @@ RocketChat.saveCustomFieldsWithoutValidation = function(userId, formData) { }); } }; + +RocketChat.saveCustomFieldsWithoutValidation = saveCustomFieldsWithoutValidation; diff --git a/packages/rocketchat-lib/server/functions/saveUser.js b/packages/rocketchat-lib/server/functions/saveUser.js index 14aa68429611..4f687b08164d 100644 --- a/packages/rocketchat-lib/server/functions/saveUser.js +++ b/packages/rocketchat-lib/server/functions/saveUser.js @@ -144,7 +144,7 @@ function validateUserEditing(userId, userData) { } } -RocketChat.saveUser = function(userId, userData) { +export const saveUser = function(userId, userData) { validateUserData(userId, userData); if (!userData._id) { @@ -267,3 +267,5 @@ RocketChat.saveUser = function(userId, userData) { return true; }; + +RocketChat.saveUser = saveUser; diff --git a/packages/rocketchat-lib/server/functions/sendMessage.js b/packages/rocketchat-lib/server/functions/sendMessage.js index 952b27895100..808613060a9a 100644 --- a/packages/rocketchat-lib/server/functions/sendMessage.js +++ b/packages/rocketchat-lib/server/functions/sendMessage.js @@ -78,7 +78,7 @@ const validateAttachment = (attachment) => { const validateBodyAttachments = (attachments) => attachments.map(validateAttachment); -RocketChat.sendMessage = function(user, message, room, upsert = false) { +export const sendMessage = function(user, message, room, upsert = false) { if (!user || !message || !room._id) { return false; } @@ -189,3 +189,5 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) { return message; } }; + +RocketChat.sendMessage = sendMessage; diff --git a/packages/rocketchat-lib/server/functions/setEmail.js b/packages/rocketchat-lib/server/functions/setEmail.js index ad05ef2fe3d7..91ff18fc41d1 100644 --- a/packages/rocketchat-lib/server/functions/setEmail.js +++ b/packages/rocketchat-lib/server/functions/setEmail.js @@ -3,7 +3,7 @@ import { Users } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import s from 'underscore.string'; -RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = true) { +const _setEmail = function(userId, email, shouldSendVerificationEmail = true) { email = s.trim(email); if (!userId) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { function: '_setEmail' }); @@ -36,6 +36,8 @@ RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = tru return user; }; -RocketChat.setEmail = RocketChat.RateLimiter.limitFunction(RocketChat._setEmail, 1, 60000, { +export const setEmail = RocketChat.RateLimiter.limitFunction(_setEmail, 1, 60000, { 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others emails, so don't limit those }); + +RocketChat.setEmail = setEmail; diff --git a/packages/rocketchat-lib/server/functions/setRealName.js b/packages/rocketchat-lib/server/functions/setRealName.js index 0cfac9bf3f87..d95afdb27501 100644 --- a/packages/rocketchat-lib/server/functions/setRealName.js +++ b/packages/rocketchat-lib/server/functions/setRealName.js @@ -5,7 +5,7 @@ import { Notifications } from 'meteor/rocketchat:notifications'; import { hasPermission } from 'meteor/rocketchat:authorization'; import s from 'underscore.string'; -RocketChat._setRealName = function(userId, name) { +const _setRealName = function(userId, name) { name = s.trim(name); if (!userId || !name) { return false; @@ -35,6 +35,8 @@ RocketChat._setRealName = function(userId, name) { return user; }; -RocketChat.setRealName = RocketChat.RateLimiter.limitFunction(RocketChat._setRealName, 1, 60000, { +export const setRealName = RocketChat.RateLimiter.limitFunction(_setRealName, 1, 60000, { 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others names, so don't limit those }); + +RocketChat.setRealName = setRealName; diff --git a/packages/rocketchat-lib/server/functions/setUserAvatar.js b/packages/rocketchat-lib/server/functions/setUserAvatar.js index 4335123d0983..e32ce7f76171 100644 --- a/packages/rocketchat-lib/server/functions/setUserAvatar.js +++ b/packages/rocketchat-lib/server/functions/setUserAvatar.js @@ -5,7 +5,7 @@ import { FileUpload } from 'meteor/rocketchat:file-upload'; import { Users } from 'meteor/rocketchat:models'; import { Notifications } from 'meteor/rocketchat:notifications'; -RocketChat.setUserAvatar = function(user, dataURI, contentType, service) { +export const setUserAvatar = function(user, dataURI, contentType, service) { let encoding; let image; @@ -63,3 +63,5 @@ RocketChat.setUserAvatar = function(user, dataURI, contentType, service) { }, 500); }); }; + +RocketChat.setUserAvatar = setUserAvatar; diff --git a/packages/rocketchat-lib/server/functions/setUsername.js b/packages/rocketchat-lib/server/functions/setUsername.js index 6003a7abaa45..2abff008a11c 100644 --- a/packages/rocketchat-lib/server/functions/setUsername.js +++ b/packages/rocketchat-lib/server/functions/setUsername.js @@ -5,7 +5,7 @@ import { settings } from 'meteor/rocketchat:settings'; import { Users, Messages, Subscriptions, Rooms } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; -RocketChat._setUsername = function(userId, u) { +const _setUsername = function(userId, u) { const username = s.trim(u); if (!userId || !username) { return false; @@ -83,8 +83,10 @@ RocketChat._setUsername = function(userId, u) { return user; }; -RocketChat.setUsername = RocketChat.RateLimiter.limitFunction(RocketChat._setUsername, 1, 60000, { +export const setUsername = RocketChat.RateLimiter.limitFunction(_setUsername, 1, 60000, { [0](userId) { return !userId || !hasPermission(userId, 'edit-other-user-info'); }, }); + +RocketChat.setUsername = setUsername; diff --git a/packages/rocketchat-lib/server/functions/unarchiveRoom.js b/packages/rocketchat-lib/server/functions/unarchiveRoom.js index 9cce78e07e1d..93728e0a1018 100644 --- a/packages/rocketchat-lib/server/functions/unarchiveRoom.js +++ b/packages/rocketchat-lib/server/functions/unarchiveRoom.js @@ -1,6 +1,8 @@ import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; -RocketChat.unarchiveRoom = function(rid) { +export const unarchiveRoom = function(rid) { Rooms.unarchiveById(rid); Subscriptions.unarchiveByRoomId(rid); }; + +RocketChat.unarchiveRoom = unarchiveRoom; diff --git a/packages/rocketchat-lib/server/functions/updateMessage.js b/packages/rocketchat-lib/server/functions/updateMessage.js index 82158b41dc12..a412cdfd5ef9 100644 --- a/packages/rocketchat-lib/server/functions/updateMessage.js +++ b/packages/rocketchat-lib/server/functions/updateMessage.js @@ -3,7 +3,7 @@ import { Messages, Rooms } from 'meteor/rocketchat:models'; import { settings } from 'meteor/rocketchat:settings'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.updateMessage = function(message, user, originalMessage) { +export const updateMessage = function(message, user, originalMessage) { if (!originalMessage) { originalMessage = Messages.findOneById(message._id); } @@ -59,3 +59,5 @@ RocketChat.updateMessage = function(message, user, originalMessage) { callbacks.run('afterSaveMessage', Messages.findOneById(tempid), room, user._id); }); }; + +RocketChat.updateMessage = updateMessage; diff --git a/packages/rocketchat-lib/server/functions/validateCustomFields.js b/packages/rocketchat-lib/server/functions/validateCustomFields.js index f2d5bff1aba5..fca8829289d8 100644 --- a/packages/rocketchat-lib/server/functions/validateCustomFields.js +++ b/packages/rocketchat-lib/server/functions/validateCustomFields.js @@ -2,7 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; -RocketChat.validateCustomFields = function(fields) { +export const validateCustomFields = function(fields) { // Special Case: // If an admin didn't set any custom fields there's nothing to validate against so consider any customFields valid if (s.trim(settings.get('Accounts_CustomFields')) === '') { @@ -41,3 +41,5 @@ RocketChat.validateCustomFields = function(fields) { } }); }; + +RocketChat.validateCustomFields = validateCustomFields; diff --git a/packages/rocketchat-lib/server/lib/RateLimiter.js b/packages/rocketchat-lib/server/lib/RateLimiter.js index dcbb7ce5a0c1..4099a430478e 100644 --- a/packages/rocketchat-lib/server/lib/RateLimiter.js +++ b/packages/rocketchat-lib/server/lib/RateLimiter.js @@ -3,7 +3,7 @@ import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; import { RateLimiter } from 'meteor/rate-limit'; import _ from 'underscore'; -RocketChat.RateLimiter = new class { +export const RateLimiterClass = new class { limitFunction(fn, numRequests, timeInterval, matchers) { if (process.env.TEST_MODE === 'true') { return fn; @@ -43,3 +43,5 @@ RocketChat.RateLimiter = new class { } }; + +RocketChat.RateLimiter = RateLimiterClass; diff --git a/packages/rocketchat-lib/server/lib/index.js b/packages/rocketchat-lib/server/lib/index.js index 5cf680b6e8b9..2c20567bc166 100644 --- a/packages/rocketchat-lib/server/lib/index.js +++ b/packages/rocketchat-lib/server/lib/index.js @@ -9,10 +9,18 @@ import { RoomSettingsEnum, RoomTypeConfig, RoomTypeRouteConfig } from '../../lib/RoomTypeConfig'; import { sendNotification } from './sendNotificationsOnMessage.js'; export { hostname } from '../../lib/startup/settingsOnLoadSiteUrl'; +import { passwordPolicy } from './passwordPolicy'; +import { validateEmailDomain } from './validateEmailDomain'; +import { RateLimiterClass as RateLimiter } from './RateLimiter'; +import { processDirectEmail } from './processDirectEmail'; export { RoomSettingsEnum, RoomTypeConfig, RoomTypeRouteConfig, sendNotification, + passwordPolicy, + validateEmailDomain, + RateLimiter, + processDirectEmail, }; diff --git a/packages/rocketchat-lib/server/lib/validateEmailDomain.js b/packages/rocketchat-lib/server/lib/validateEmailDomain.js index da7d3ac2f98a..f335c81716e9 100644 --- a/packages/rocketchat-lib/server/lib/validateEmailDomain.js +++ b/packages/rocketchat-lib/server/lib/validateEmailDomain.js @@ -22,7 +22,7 @@ settings.get('Accounts_UseDNSDomainCheck', function(key, value) { useDNSDomainCheck = value; }); -RocketChat.validateEmailDomain = function(email) { +export const validateEmailDomain = function(email) { const emailValidation = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; if (!emailValidation.test(email)) { throw new Meteor.Error('error-invalid-email', `Invalid email ${ email }`, { function: 'RocketChat.validateEmailDomain', email }); @@ -45,3 +45,5 @@ RocketChat.validateEmailDomain = function(email) { } } }; + +RocketChat.validateEmailDomain = validateEmailDomain; From 3b6ffa6e71bffd3aa65700183419ff3f28d97f51 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 18:18:24 -0200 Subject: [PATCH 10/18] Import variables from functions and lib to remove RC namespace dependency --- .../server/functions/saveCustomFields.js | 5 +++-- .../rocketchat-lib/server/functions/saveUser.js | 16 +++++++++------- .../rocketchat-lib/server/functions/setEmail.js | 8 +++++--- .../server/functions/setRealName.js | 3 ++- .../server/functions/setUsername.js | 10 ++++++---- packages/rocketchat-lib/server/lib/bugsnag.js | 4 +--- .../server/lib/interceptDirectReplyEmails.js | 5 +++-- .../rocketchat-lib/server/lib/passwordPolicy.js | 2 +- .../server/lib/processDirectEmail.js | 7 +++++-- .../server/methods/addUsersToRoom.js | 3 ++- .../rocketchat-lib/server/methods/archiveRoom.js | 3 ++- .../server/methods/checkUsernameAvailability.js | 6 ++++-- .../server/methods/cleanRoomHistory.js | 3 ++- .../server/methods/createChannel.js | 3 ++- .../server/methods/createPrivateGroup.js | 3 ++- .../server/methods/deleteMessage.js | 3 ++- .../server/methods/deleteUserOwnAccount.js | 3 ++- .../server/methods/getChannelHistory.js | 3 ++- .../server/methods/getFullUserData.js | 3 ++- .../server/methods/insertOrUpdateUser.js | 3 ++- .../server/methods/joinDefaultChannels.js | 3 ++- .../rocketchat-lib/server/methods/joinRoom.js | 3 ++- .../rocketchat-lib/server/methods/leaveRoom.js | 3 ++- .../rocketchat-lib/server/methods/sendMessage.js | 6 ++++-- .../rocketchat-lib/server/methods/setEmail.js | 6 ++++-- .../rocketchat-lib/server/methods/setRealName.js | 6 ++++-- .../rocketchat-lib/server/methods/setUsername.js | 8 +++++--- .../server/methods/unarchiveRoom.js | 3 ++- .../server/methods/updateMessage.js | 3 ++- packages/rocketchat-lib/server/oauth/facebook.js | 3 ++- packages/rocketchat-lib/server/oauth/google.js | 3 ++- packages/rocketchat-lib/server/oauth/oauth.js | 2 +- packages/rocketchat-lib/server/oauth/twitter.js | 3 ++- 33 files changed, 93 insertions(+), 55 deletions(-) diff --git a/packages/rocketchat-lib/server/functions/saveCustomFields.js b/packages/rocketchat-lib/server/functions/saveCustomFields.js index 292ddfbbdee8..87eeb8f63b9e 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFields.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFields.js @@ -1,10 +1,11 @@ import { settings } from 'meteor/rocketchat:settings'; +import { validateCustomFields, saveCustomFieldsWithoutValidation } from '.'; import s from 'underscore.string'; export const saveCustomFields = function(userId, formData) { if (s.trim(settings.get('Accounts_CustomFields')) !== '') { - RocketChat.validateCustomFields(formData); - return RocketChat.saveCustomFieldsWithoutValidation(userId, formData); + validateCustomFields(formData); + return saveCustomFieldsWithoutValidation(userId, formData); } }; diff --git a/packages/rocketchat-lib/server/functions/saveUser.js b/packages/rocketchat-lib/server/functions/saveUser.js index 4f687b08164d..b9264ac3e0a4 100644 --- a/packages/rocketchat-lib/server/functions/saveUser.js +++ b/packages/rocketchat-lib/server/functions/saveUser.js @@ -7,6 +7,8 @@ import { Gravatar } from 'meteor/jparker:gravatar'; import { getRoles, hasPermission } from 'meteor/rocketchat:authorization'; import { settings } from 'meteor/rocketchat:settings'; import PasswordPolicy from '../lib/PasswordPolicyClass'; +import { checkEmailAvailability, checkUsernameAvailability, setUserAvatar, setEmail, setRealName, setUsername } from '.'; +import { validateEmailDomain } from '../lib'; const passwordPolicy = new PasswordPolicy(); @@ -86,14 +88,14 @@ function validateUserData(userId, userData) { } if (!userData._id) { - if (!RocketChat.checkUsernameAvailability(userData.username)) { + if (!checkUsernameAvailability(userData.username)) { throw new Meteor.Error('error-field-unavailable', `${ _.escape(userData.username) } is already in use :(`, { method: 'insertOrUpdateUser', field: userData.username, }); } - if (userData.email && !RocketChat.checkEmailAvailability(userData.email)) { + if (userData.email && !checkEmailAvailability(userData.email)) { throw new Meteor.Error('error-field-unavailable', `${ _.escape(userData.email) } is already in use :(`, { method: 'insertOrUpdateUser', field: userData.email, @@ -148,7 +150,7 @@ export const saveUser = function(userId, userData) { validateUserData(userId, userData); if (!userData._id) { - RocketChat.validateEmailDomain(userData.email); + validateEmailDomain(userData.email); // insert user const createUser = { @@ -211,7 +213,7 @@ export const saveUser = function(userId, userData) { const gravatarUrl = Gravatar.imageUrl(userData.email, { default: '404', size: 200, secure: true }); try { - RocketChat.setUserAvatar(userData, gravatarUrl, '', 'url'); + setUserAvatar(userData, gravatarUrl, '', 'url'); } catch (e) { // Ignore this error for now, as it not being successful isn't bad } @@ -224,16 +226,16 @@ export const saveUser = function(userId, userData) { // update user if (userData.username) { - RocketChat.setUsername(userData._id, userData.username); + setUsername(userData._id, userData.username); } if (userData.name) { - RocketChat.setRealName(userData._id, userData.name); + setRealName(userData._id, userData.name); } if (userData.email) { const shouldSendVerificationEmailToUser = userData.verified !== true; - RocketChat.setEmail(userData._id, userData.email, shouldSendVerificationEmailToUser); + setEmail(userData._id, userData.email, shouldSendVerificationEmailToUser); } if (userData.password && userData.password.trim() && hasPermission(userId, 'edit-other-user-password') && passwordPolicy.validate(userData.password)) { diff --git a/packages/rocketchat-lib/server/functions/setEmail.js b/packages/rocketchat-lib/server/functions/setEmail.js index 91ff18fc41d1..55d1b9797162 100644 --- a/packages/rocketchat-lib/server/functions/setEmail.js +++ b/packages/rocketchat-lib/server/functions/setEmail.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Users } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { RateLimiter, validateEmailDomain } from '../lib'; +import { checkEmailAvailability } from '.'; import s from 'underscore.string'; const _setEmail = function(userId, email, shouldSendVerificationEmail = true) { @@ -13,7 +15,7 @@ const _setEmail = function(userId, email, shouldSendVerificationEmail = true) { throw new Meteor.Error('error-invalid-email', 'Invalid email', { function: '_setEmail' }); } - RocketChat.validateEmailDomain(email); + validateEmailDomain(email); const user = Users.findOneById(userId); @@ -23,7 +25,7 @@ const _setEmail = function(userId, email, shouldSendVerificationEmail = true) { } // Check email availability - if (!RocketChat.checkEmailAvailability(email)) { + if (!checkEmailAvailability(email)) { throw new Meteor.Error('error-field-unavailable', `${ email } is already in use :(`, { function: '_setEmail', field: email }); } @@ -36,7 +38,7 @@ const _setEmail = function(userId, email, shouldSendVerificationEmail = true) { return user; }; -export const setEmail = RocketChat.RateLimiter.limitFunction(_setEmail, 1, 60000, { +export const setEmail = RateLimiter.limitFunction(_setEmail, 1, 60000, { 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others emails, so don't limit those }); diff --git a/packages/rocketchat-lib/server/functions/setRealName.js b/packages/rocketchat-lib/server/functions/setRealName.js index d95afdb27501..6373aaa20609 100644 --- a/packages/rocketchat-lib/server/functions/setRealName.js +++ b/packages/rocketchat-lib/server/functions/setRealName.js @@ -3,6 +3,7 @@ import { Users, Subscriptions } from 'meteor/rocketchat:models'; import { settings } from 'meteor/rocketchat:settings'; import { Notifications } from 'meteor/rocketchat:notifications'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { RateLimiter } from '../lib'; import s from 'underscore.string'; const _setRealName = function(userId, name) { @@ -35,7 +36,7 @@ const _setRealName = function(userId, name) { return user; }; -export const setRealName = RocketChat.RateLimiter.limitFunction(_setRealName, 1, 60000, { +export const setRealName = RateLimiter.limitFunction(_setRealName, 1, 60000, { 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others names, so don't limit those }); diff --git a/packages/rocketchat-lib/server/functions/setUsername.js b/packages/rocketchat-lib/server/functions/setUsername.js index 2abff008a11c..9daa3e3ff305 100644 --- a/packages/rocketchat-lib/server/functions/setUsername.js +++ b/packages/rocketchat-lib/server/functions/setUsername.js @@ -4,6 +4,8 @@ import { FileUpload } from 'meteor/rocketchat:file-upload'; import { settings } from 'meteor/rocketchat:settings'; import { Users, Messages, Subscriptions, Rooms } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { RateLimiter } from '../lib'; +import { checkUsernameAvailability, setUserAvatar } from '.'; const _setUsername = function(userId, u) { const username = s.trim(u); @@ -27,7 +29,7 @@ const _setUsername = function(userId, u) { const previousUsername = user.username; // Check username availability or if the user already owns a different casing of the name if (!previousUsername || !(username.toLowerCase() === previousUsername.toLowerCase())) { - if (!RocketChat.checkUsernameAvailability(username)) { + if (!checkUsernameAvailability(username)) { return false; } } @@ -48,7 +50,7 @@ const _setUsername = function(userId, u) { Object.keys(avatarSuggestions).some((service) => { const avatarData = avatarSuggestions[service]; if (service !== 'gravatar') { - RocketChat.setUserAvatar(user, avatarData.blob, avatarData.contentType, service); + setUserAvatar(user, avatarData.blob, avatarData.contentType, service); gravatar = null; return true; } @@ -56,7 +58,7 @@ const _setUsername = function(userId, u) { return false; }); if (gravatar != null) { - RocketChat.setUserAvatar(user, gravatar.blob, gravatar.contentType, 'gravatar'); + setUserAvatar(user, gravatar.blob, gravatar.contentType, 'gravatar'); } } // Username is available; if coming from old username, update all references @@ -83,7 +85,7 @@ const _setUsername = function(userId, u) { return user; }; -export const setUsername = RocketChat.RateLimiter.limitFunction(_setUsername, 1, 60000, { +export const setUsername = RateLimiter.limitFunction(_setUsername, 1, 60000, { [0](userId) { return !userId || !hasPermission(userId, 'edit-other-user-info'); }, diff --git a/packages/rocketchat-lib/server/lib/bugsnag.js b/packages/rocketchat-lib/server/lib/bugsnag.js index 0586eb52ff93..58bd16ebde15 100644 --- a/packages/rocketchat-lib/server/lib/bugsnag.js +++ b/packages/rocketchat-lib/server/lib/bugsnag.js @@ -3,8 +3,6 @@ import { settings } from 'meteor/rocketchat:settings'; import { Info } from 'meteor/rocketchat:utils'; import bugsnag from 'bugsnag'; -RocketChat.bugsnag = bugsnag; - settings.get('Bugsnag_api_key', (key, value) => { if (value) { bugsnag.register(value); @@ -21,7 +19,7 @@ const notify = function(message, stack) { } const error = new Error(message); error.stack = stack; - RocketChat.bugsnag.notify(error, options); + bugsnag.notify(error, options); }; process.on('uncaughtException', Meteor.bindEnvironment((error) => { diff --git a/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js b/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js index 5e54bc901689..05aaf79aa4f6 100644 --- a/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js +++ b/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js @@ -3,6 +3,7 @@ import { settings } from 'meteor/rocketchat:settings'; import IMAP from 'imap'; import POP3 from 'poplib'; import { simpleParser } from 'mailparser'; +import { processDirectEmail } from '.'; export class IMAPIntercepter { constructor() { @@ -128,7 +129,7 @@ export class IMAPIntercepter { if (err) { console.log(`Mark deleted error: ${ err }`); } }); } - RocketChat.processDirectEmail(email); + processDirectEmail(email); })); })); f.once('error', (err) => { @@ -232,7 +233,7 @@ export class POP3Intercepter { body: mail.text, }; - RocketChat.processDirectEmail(email); + processDirectEmail(email); } } diff --git a/packages/rocketchat-lib/server/lib/passwordPolicy.js b/packages/rocketchat-lib/server/lib/passwordPolicy.js index cf741675b3dd..5f94dc7356b8 100644 --- a/packages/rocketchat-lib/server/lib/passwordPolicy.js +++ b/packages/rocketchat-lib/server/lib/passwordPolicy.js @@ -1,7 +1,7 @@ import { settings } from 'meteor/rocketchat:settings'; import PasswordPolicy from './PasswordPolicyClass'; -const passwordPolicy = new PasswordPolicy(); +export const passwordPolicy = new PasswordPolicy(); RocketChat.passwordPolicy = passwordPolicy; settings.get('Accounts_Password_Policy_Enabled', (key, value) => passwordPolicy.enabled = value); diff --git a/packages/rocketchat-lib/server/lib/processDirectEmail.js b/packages/rocketchat-lib/server/lib/processDirectEmail.js index 36b5ab27f437..5c64c67af410 100644 --- a/packages/rocketchat-lib/server/lib/processDirectEmail.js +++ b/packages/rocketchat-lib/server/lib/processDirectEmail.js @@ -3,9 +3,10 @@ import { settings } from 'meteor/rocketchat:settings'; import { Rooms, Messages, Users, Subscriptions } from 'meteor/rocketchat:models'; import { metrics } from 'meteor/rocketchat:metrics'; import { EmailReplyParser as reply } from 'emailreplyparser'; +import { sendMessage as _sendMessage } from '../functions'; import moment from 'moment'; -RocketChat.processDirectEmail = function(email) { +export const processDirectEmail = function(email) { function sendMessage(email) { const message = { ts: new Date(email.headers.date), @@ -95,7 +96,7 @@ RocketChat.processDirectEmail = function(email) { metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 - return RocketChat.sendMessage(user, message, room); + return _sendMessage(user, message, room); } // Extract/parse reply from email body @@ -120,3 +121,5 @@ RocketChat.processDirectEmail = function(email) { console.log('Invalid Email....If not. Please report it.'); } }; + +RocketChat.processDirectEmail = processDirectEmail; diff --git a/packages/rocketchat-lib/server/methods/addUsersToRoom.js b/packages/rocketchat-lib/server/methods/addUsersToRoom.js index dd16bfea969a..22c1a2000ca4 100644 --- a/packages/rocketchat-lib/server/methods/addUsersToRoom.js +++ b/packages/rocketchat-lib/server/methods/addUsersToRoom.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Rooms, Subscriptions, Users } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { addUserToRoom } from '../functions'; Meteor.methods({ addUsersToRoom(data = {}) { @@ -64,7 +65,7 @@ Meteor.methods({ method: 'addUsersToRoom', }); } - RocketChat.addUserToRoom(data.rid, newUser, user); + addUserToRoom(data.rid, newUser, user); }); return true; diff --git a/packages/rocketchat-lib/server/methods/archiveRoom.js b/packages/rocketchat-lib/server/methods/archiveRoom.js index 26d03e477746..d8b8e503764a 100644 --- a/packages/rocketchat-lib/server/methods/archiveRoom.js +++ b/packages/rocketchat-lib/server/methods/archiveRoom.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { Rooms } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { archiveRoom } from '../functions'; Meteor.methods({ archiveRoom(rid) { @@ -26,6 +27,6 @@ Meteor.methods({ throw new Meteor.Error('error-direct-message-room', 'Direct Messages can not be archived', { method: 'archiveRoom' }); } - return RocketChat.archiveRoom(rid); + return archiveRoom(rid); }, }); diff --git a/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js b/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js index a115878d3c5d..2dbf05c3f4a8 100644 --- a/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js +++ b/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { settings } from 'meteor/rocketchat:settings'; +import { checkUsernameAvailability } from '../functions'; +import { RateLimiter } from '../lib'; Meteor.methods({ checkUsernameAvailability(username) { @@ -19,10 +21,10 @@ Meteor.methods({ if (user.username === username) { return true; } - return RocketChat.checkUsernameAvailability(username); + return checkUsernameAvailability(username); }, }); -RocketChat.RateLimiter.limitMethod('checkUsernameAvailability', 1, 1000, { +RateLimiter.limitMethod('checkUsernameAvailability', 1, 1000, { userId() { return true; }, }); diff --git a/packages/rocketchat-lib/server/methods/cleanRoomHistory.js b/packages/rocketchat-lib/server/methods/cleanRoomHistory.js index 6e449f1a0353..baf50abfc0cc 100644 --- a/packages/rocketchat-lib/server/methods/cleanRoomHistory.js +++ b/packages/rocketchat-lib/server/methods/cleanRoomHistory.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { cleanRoomHistory } from '../functions'; Meteor.methods({ cleanRoomHistory({ roomId, latest, oldest, inclusive = true, limit, excludePinned = false, filesOnly = false, fromUsers = [] }) { @@ -23,6 +24,6 @@ Meteor.methods({ throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'cleanRoomHistory' }); } - return RocketChat.cleanRoomHistory({ rid: roomId, latest, oldest, inclusive, limit, excludePinned, filesOnly, fromUsers }); + return cleanRoomHistory({ rid: roomId, latest, oldest, inclusive, limit, excludePinned, filesOnly, fromUsers }); }, }); diff --git a/packages/rocketchat-lib/server/methods/createChannel.js b/packages/rocketchat-lib/server/methods/createChannel.js index df438753e028..56cff282b8de 100644 --- a/packages/rocketchat-lib/server/methods/createChannel.js +++ b/packages/rocketchat-lib/server/methods/createChannel.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { createRoom } from '../functions'; Meteor.methods({ createChannel(name, members, readOnly = false, customFields = {}, extraData = {}) { @@ -14,6 +15,6 @@ Meteor.methods({ if (!hasPermission(Meteor.userId(), 'create-c')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'createChannel' }); } - return RocketChat.createRoom('c', name, Meteor.user() && Meteor.user().username, members, readOnly, { customFields, ...extraData }); + return createRoom('c', name, Meteor.user() && Meteor.user().username, members, readOnly, { customFields, ...extraData }); }, }); diff --git a/packages/rocketchat-lib/server/methods/createPrivateGroup.js b/packages/rocketchat-lib/server/methods/createPrivateGroup.js index 2a28cfd1f5b1..63ff39c41eb0 100644 --- a/packages/rocketchat-lib/server/methods/createPrivateGroup.js +++ b/packages/rocketchat-lib/server/methods/createPrivateGroup.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { createRoom } from '../functions'; Meteor.methods({ createPrivateGroup(name, members, readOnly = false, customFields = {}, extraData = {}) { @@ -26,6 +27,6 @@ Meteor.methods({ }), })); - return RocketChat.createRoom('p', name, Meteor.user() && Meteor.user().username, members, readOnly, { customFields, ...extraData }); + return createRoom('p', name, Meteor.user() && Meteor.user().username, members, readOnly, { customFields, ...extraData }); }, }); diff --git a/packages/rocketchat-lib/server/methods/deleteMessage.js b/packages/rocketchat-lib/server/methods/deleteMessage.js index 7dbed6f85c4c..97ed8f7f17b0 100644 --- a/packages/rocketchat-lib/server/methods/deleteMessage.js +++ b/packages/rocketchat-lib/server/methods/deleteMessage.js @@ -3,6 +3,7 @@ import { Match, check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { settings } from 'meteor/rocketchat:settings'; import { Messages } from 'meteor/rocketchat:models'; +import { deleteMessage } from '../functions'; import moment from 'moment'; Meteor.methods({ @@ -55,6 +56,6 @@ Meteor.methods({ }); } } - return RocketChat.deleteMessage(originalMessage, Meteor.user()); + return deleteMessage(originalMessage, Meteor.user()); }, }); diff --git a/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js b/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js index 4189d0dd6f32..febe39cf61dc 100644 --- a/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js +++ b/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js @@ -3,6 +3,7 @@ import { check } from 'meteor/check'; import { Accounts } from 'meteor/accounts-base'; import { settings } from 'meteor/rocketchat:settings'; import { Users } from 'meteor/rocketchat:models'; +import { deleteUser } from '../functions'; import s from 'underscore.string'; Meteor.methods({ @@ -35,7 +36,7 @@ Meteor.methods({ } Meteor.defer(function() { - RocketChat.deleteUser(userId); + deleteUser(userId); }); return true; diff --git a/packages/rocketchat-lib/server/methods/getChannelHistory.js b/packages/rocketchat-lib/server/methods/getChannelHistory.js index b9ba43432f16..776d521233d0 100644 --- a/packages/rocketchat-lib/server/methods/getChannelHistory.js +++ b/packages/rocketchat-lib/server/methods/getChannelHistory.js @@ -3,6 +3,7 @@ import { check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { Subscriptions, Messages } from 'meteor/rocketchat:models'; import { settings } from 'meteor/rocketchat:settings'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; import _ from 'underscore'; Meteor.methods({ @@ -56,7 +57,7 @@ Meteor.methods({ records = Messages.findVisibleByRoomIdBetweenTimestamps(rid, oldest, latest, options).fetch(); } - const messages = records.map((record) => RocketChat.composeMessageObjectWithUser(record, fromUserId)); + const messages = records.map((record) => composeMessageObjectWithUser(record, fromUserId)); if (unreads) { let unreadNotLoaded = 0; diff --git a/packages/rocketchat-lib/server/methods/getFullUserData.js b/packages/rocketchat-lib/server/methods/getFullUserData.js index e65628ecc7f0..9661f032b108 100644 --- a/packages/rocketchat-lib/server/methods/getFullUserData.js +++ b/packages/rocketchat-lib/server/methods/getFullUserData.js @@ -1,8 +1,9 @@ import { Meteor } from 'meteor/meteor'; +import { getFullUserData } from '../functions'; Meteor.methods({ getFullUserData({ filter = '', username = '', limit = 1 }) { - const result = RocketChat.getFullUserData({ userId: Meteor.userId(), filter: filter || username, limit }); + const result = getFullUserData({ userId: Meteor.userId(), filter: filter || username, limit }); return result && result.fetch(); }, }); diff --git a/packages/rocketchat-lib/server/methods/insertOrUpdateUser.js b/packages/rocketchat-lib/server/methods/insertOrUpdateUser.js index c024e6ee242d..aba6e0bc6485 100644 --- a/packages/rocketchat-lib/server/methods/insertOrUpdateUser.js +++ b/packages/rocketchat-lib/server/methods/insertOrUpdateUser.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { saveUser } from '../functions'; Meteor.methods({ insertOrUpdateUser(userData) { @@ -10,6 +11,6 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'insertOrUpdateUser' }); } - return RocketChat.saveUser(Meteor.userId(), userData); + return saveUser(Meteor.userId(), userData); }, }); diff --git a/packages/rocketchat-lib/server/methods/joinDefaultChannels.js b/packages/rocketchat-lib/server/methods/joinDefaultChannels.js index 4e309f1d217a..2f1cdbdf24be 100644 --- a/packages/rocketchat-lib/server/methods/joinDefaultChannels.js +++ b/packages/rocketchat-lib/server/methods/joinDefaultChannels.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { addUserToDefaultChannels } from '../functions'; Meteor.methods({ joinDefaultChannels(silenced) { @@ -10,6 +11,6 @@ Meteor.methods({ } this.unblock(); - return RocketChat.addUserToDefaultChannels(Meteor.user(), silenced); + return addUserToDefaultChannels(Meteor.user(), silenced); }, }); diff --git a/packages/rocketchat-lib/server/methods/joinRoom.js b/packages/rocketchat-lib/server/methods/joinRoom.js index c0f236564c34..56e1fcbb46d5 100644 --- a/packages/rocketchat-lib/server/methods/joinRoom.js +++ b/packages/rocketchat-lib/server/methods/joinRoom.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { hasPermission, canAccessRoom } from 'meteor/rocketchat:authorization'; import { Rooms } from 'meteor/rocketchat:models'; +import { addUserToRoom } from '../functions'; Meteor.methods({ joinRoom(rid, code) { @@ -34,6 +35,6 @@ Meteor.methods({ } } - return RocketChat.addUserToRoom(rid, user); + return addUserToRoom(rid, user); }, }); diff --git a/packages/rocketchat-lib/server/methods/leaveRoom.js b/packages/rocketchat-lib/server/methods/leaveRoom.js index 9ef756b99915..7b8f5728c4e1 100644 --- a/packages/rocketchat-lib/server/methods/leaveRoom.js +++ b/packages/rocketchat-lib/server/methods/leaveRoom.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { hasPermission, hasRole, getUsersInRole } from 'meteor/rocketchat:authorization'; import { Subscriptions, Rooms } from 'meteor/rocketchat:models'; +import { removeUserFromRoom } from '../functions'; Meteor.methods({ leaveRoom(rid) { @@ -34,6 +35,6 @@ Meteor.methods({ } } - return RocketChat.removeUserFromRoom(rid, user); + return removeUserFromRoom(rid, user); }, }); diff --git a/packages/rocketchat-lib/server/methods/sendMessage.js b/packages/rocketchat-lib/server/methods/sendMessage.js index 0e754b534395..268f42bd119f 100644 --- a/packages/rocketchat-lib/server/methods/sendMessage.js +++ b/packages/rocketchat-lib/server/methods/sendMessage.js @@ -8,6 +8,8 @@ import { settings } from 'meteor/rocketchat:settings'; import { Notifications } from 'meteor/rocketchat:notifications'; import { messageProperties } from 'meteor/rocketchat:ui-utils'; import { Subscriptions, Users } from 'meteor/rocketchat:models'; +import { sendMessage } from '../functions'; +import { RateLimiter } from '../lib'; import moment from 'moment'; Meteor.methods({ @@ -91,11 +93,11 @@ Meteor.methods({ } metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 - return RocketChat.sendMessage(user, message, room); + return sendMessage(user, message, room); }, }); // Limit a user, who does not have the "bot" role, to sending 5 msgs/second -RocketChat.RateLimiter.limitMethod('sendMessage', 5, 1000, { +RateLimiter.limitMethod('sendMessage', 5, 1000, { userId(userId) { return !hasPermission(userId, 'send-many-messages'); }, diff --git a/packages/rocketchat-lib/server/methods/setEmail.js b/packages/rocketchat-lib/server/methods/setEmail.js index 583526ca9129..38ea7387fae2 100644 --- a/packages/rocketchat-lib/server/methods/setEmail.js +++ b/packages/rocketchat-lib/server/methods/setEmail.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { settings } from 'meteor/rocketchat:settings'; +import { setEmail } from '../functions'; +import { RateLimiter } from '../lib'; Meteor.methods({ setEmail(email) { @@ -21,7 +23,7 @@ Meteor.methods({ return email; } - if (!RocketChat.setEmail(user._id, email)) { + if (!setEmail(user._id, email)) { throw new Meteor.Error('error-could-not-change-email', 'Could not change email', { method: 'setEmail' }); } @@ -29,6 +31,6 @@ Meteor.methods({ }, }); -RocketChat.RateLimiter.limitMethod('setEmail', 1, 1000, { +RateLimiter.limitMethod('setEmail', 1, 1000, { userId(/* userId*/) { return true; }, }); diff --git a/packages/rocketchat-lib/server/methods/setRealName.js b/packages/rocketchat-lib/server/methods/setRealName.js index e7a8218ecc70..3b300ad723d9 100644 --- a/packages/rocketchat-lib/server/methods/setRealName.js +++ b/packages/rocketchat-lib/server/methods/setRealName.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { settings } from 'meteor/rocketchat:settings'; +import { setRealName } from '../functions'; +import { RateLimiter } from '../lib'; Meteor.methods({ setRealName(name) { @@ -15,7 +17,7 @@ Meteor.methods({ throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setRealName' }); } - if (!RocketChat.setRealName(Meteor.userId(), name)) { + if (!setRealName(Meteor.userId(), name)) { throw new Meteor.Error('error-could-not-change-name', 'Could not change name', { method: 'setRealName' }); } @@ -23,6 +25,6 @@ Meteor.methods({ }, }); -RocketChat.RateLimiter.limitMethod('setRealName', 1, 1000, { +RateLimiter.limitMethod('setRealName', 1, 1000, { userId: () => true, }); diff --git a/packages/rocketchat-lib/server/methods/setUsername.js b/packages/rocketchat-lib/server/methods/setUsername.js index c964fb0ac82b..c498bb99e2fb 100644 --- a/packages/rocketchat-lib/server/methods/setUsername.js +++ b/packages/rocketchat-lib/server/methods/setUsername.js @@ -3,6 +3,8 @@ import { check } from 'meteor/check'; import { settings } from 'meteor/rocketchat:settings'; import { Users } from 'meteor/rocketchat:models'; import { callbacks } from 'meteor/rocketchat:callbacks'; +import { setUsername, checkUsernameAvailability } from '../functions'; +import { RateLimiter } from '../lib'; import _ from 'underscore'; Meteor.methods({ @@ -35,11 +37,11 @@ Meteor.methods({ throw new Meteor.Error('username-invalid', `${ _.escape(username) } is not a valid username, use only letters, numbers, dots, hyphens and underscores`); } - if (!RocketChat.checkUsernameAvailability(username)) { + if (!checkUsernameAvailability(username)) { throw new Meteor.Error('error-field-unavailable', `${ _.escape(username) } is already in use :(`, { method: 'setUsername', field: username }); } - if (!RocketChat.setUsername(user._id, username)) { + if (!setUsername(user._id, username)) { throw new Meteor.Error('error-could-not-change-username', 'Could not change username', { method: 'setUsername' }); } @@ -54,6 +56,6 @@ Meteor.methods({ }, }); -RocketChat.RateLimiter.limitMethod('setUsername', 1, 1000, { +RateLimiter.limitMethod('setUsername', 1, 1000, { userId() { return true; }, }); diff --git a/packages/rocketchat-lib/server/methods/unarchiveRoom.js b/packages/rocketchat-lib/server/methods/unarchiveRoom.js index f9aafcc15f62..eda64b58e370 100644 --- a/packages/rocketchat-lib/server/methods/unarchiveRoom.js +++ b/packages/rocketchat-lib/server/methods/unarchiveRoom.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { Rooms } from 'meteor/rocketchat:models'; +import { unarchiveRoom } from '../functions'; Meteor.methods({ unarchiveRoom(rid) { @@ -22,6 +23,6 @@ Meteor.methods({ throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'unarchiveRoom' }); } - return RocketChat.unarchiveRoom(rid); + return unarchiveRoom(rid); }, }); diff --git a/packages/rocketchat-lib/server/methods/updateMessage.js b/packages/rocketchat-lib/server/methods/updateMessage.js index f2a5116d880c..5cee9e83aa29 100644 --- a/packages/rocketchat-lib/server/methods/updateMessage.js +++ b/packages/rocketchat-lib/server/methods/updateMessage.js @@ -4,6 +4,7 @@ import { Messages } from 'meteor/rocketchat:models'; import { settings } from 'meteor/rocketchat:settings'; import { hasPermission } from 'meteor/rocketchat:authorization'; import moment from 'moment'; +import { updateMessage } from '../functions'; Meteor.methods({ updateMessage(message) { @@ -55,6 +56,6 @@ Meteor.methods({ message.u = originalMessage.u; - return RocketChat.updateMessage(message, Meteor.user(), originalMessage); + return updateMessage(message, Meteor.user(), originalMessage); }, }); diff --git a/packages/rocketchat-lib/server/oauth/facebook.js b/packages/rocketchat-lib/server/oauth/facebook.js index 132fdc524c67..b35d116d8b38 100644 --- a/packages/rocketchat-lib/server/oauth/facebook.js +++ b/packages/rocketchat-lib/server/oauth/facebook.js @@ -2,6 +2,7 @@ import { Match, check } from 'meteor/check'; import _ from 'underscore'; import { OAuth } from 'meteor/oauth'; import { HTTP } from 'meteor/http'; +import { registerAccessTokenService } from './oauth'; const crypto = Npm.require('crypto'); const whitelisted = [ @@ -36,7 +37,7 @@ const getIdentity = function(accessToken, fields, secret) { } }; -RocketChat.registerAccessTokenService('facebook', function(options) { +registerAccessTokenService('facebook', function(options) { check(options, Match.ObjectIncluding({ accessToken: String, secret: String, diff --git a/packages/rocketchat-lib/server/oauth/google.js b/packages/rocketchat-lib/server/oauth/google.js index cdb50a05daed..7bccf9487761 100644 --- a/packages/rocketchat-lib/server/oauth/google.js +++ b/packages/rocketchat-lib/server/oauth/google.js @@ -2,6 +2,7 @@ import { Match, check } from 'meteor/check'; import _ from 'underscore'; import { HTTP } from 'meteor/http'; import { Google } from 'meteor/google-oauth'; +import { registerAccessTokenService } from './oauth'; function getIdentity(accessToken) { try { @@ -24,7 +25,7 @@ function getScopes(accessToken) { } -RocketChat.registerAccessTokenService('google', function(options) { +registerAccessTokenService('google', function(options) { check(options, Match.ObjectIncluding({ accessToken: String, idToken: String, diff --git a/packages/rocketchat-lib/server/oauth/oauth.js b/packages/rocketchat-lib/server/oauth/oauth.js index eef4e31739f8..c735ff0cc5b3 100644 --- a/packages/rocketchat-lib/server/oauth/oauth.js +++ b/packages/rocketchat-lib/server/oauth/oauth.js @@ -6,7 +6,7 @@ import _ from 'underscore'; const AccessTokenServices = {}; -RocketChat.registerAccessTokenService = function(serviceName, handleAccessTokenRequest) { +export const registerAccessTokenService = function(serviceName, handleAccessTokenRequest) { AccessTokenServices[serviceName] = { serviceName, handleAccessTokenRequest, diff --git a/packages/rocketchat-lib/server/oauth/twitter.js b/packages/rocketchat-lib/server/oauth/twitter.js index 38d1bd9cb30a..67ebca490495 100644 --- a/packages/rocketchat-lib/server/oauth/twitter.js +++ b/packages/rocketchat-lib/server/oauth/twitter.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { registerAccessTokenService } from './oauth'; import Twit from 'twit'; import _ from 'underscore'; @@ -29,7 +30,7 @@ const getIdentity = function(accessToken, appId, appSecret, accessTokenSecret) { } }; -RocketChat.registerAccessTokenService('twitter', function(options) { +registerAccessTokenService('twitter', function(options) { check(options, Match.ObjectIncluding({ accessToken: String, appSecret: String, From 6ab7f284d5737a3e4e0306e219d97cfda84247f6 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 18:54:21 -0200 Subject: [PATCH 11/18] Remove dependency of RC namespace in rc-sandstorm --- packages/rocketchat-lib/client/lib/sandstorm.js | 3 +++ packages/rocketchat-lib/package.js | 3 +++ packages/rocketchat-lib/server/lib/sandstorm.js | 3 +++ .../server/lib/sendNotificationsOnMessage.js | 3 ++- packages/rocketchat-sandstorm/client/index.js | 6 +++++- packages/rocketchat-sandstorm/client/powerboxListener.js | 7 +++---- packages/rocketchat-sandstorm/package.js | 1 - packages/rocketchat-sandstorm/server/events.js | 6 +++--- packages/rocketchat-sandstorm/server/index.js | 6 +++++- packages/rocketchat-sandstorm/server/lib.js | 3 +-- packages/rocketchat-sandstorm/server/powerbox.js | 8 ++++---- 11 files changed, 32 insertions(+), 17 deletions(-) create mode 100644 packages/rocketchat-lib/client/lib/sandstorm.js create mode 100644 packages/rocketchat-lib/server/lib/sandstorm.js diff --git a/packages/rocketchat-lib/client/lib/sandstorm.js b/packages/rocketchat-lib/client/lib/sandstorm.js new file mode 100644 index 000000000000..c2a9a45ee5eb --- /dev/null +++ b/packages/rocketchat-lib/client/lib/sandstorm.js @@ -0,0 +1,3 @@ +import { Sandstorm } from 'meteor/rocketchat:sandstorm'; + +RocketChat.Sandstorm = Sandstorm; diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 80a3bf8ee166..b68485aab8d7 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -43,6 +43,7 @@ Package.onUse(function(api) { api.use('rocketchat:logger'); api.use('rocketchat:mailer'); api.use('rocketchat:settings'); + api.use('rocketchat:sandstorm'); api.use('rocketchat:authorization'); api.use('mizzao:timesync'); api.use('rocketchat:custom-oauth'); @@ -146,6 +147,7 @@ Package.onUse(function(api) { api.addFiles('server/lib/validateEmailDomain.js', 'server'); api.addFiles('server/lib/passwordPolicy.js', 'server'); api.addFiles('server/lib/migrations.js', 'server'); + api.addFiles('server/lib/sandstorm.js', 'server'); // SERVER MODELS api.addFiles('server/models/index.js', 'server'); @@ -238,6 +240,7 @@ Package.onUse(function(api) { api.addFiles('client/lib/tooltip.js', 'client'); api.addFiles('client/lib/EmojiPicker.js', 'client'); api.addFiles('client/lib/ui-buttons.js', 'client'); + api.addFiles('client/lib/sandstorm.js', 'client'); // CLIENT LIB STARTUP api.addFiles('client/lib/startup/commands.js', 'client'); diff --git a/packages/rocketchat-lib/server/lib/sandstorm.js b/packages/rocketchat-lib/server/lib/sandstorm.js new file mode 100644 index 000000000000..c2a9a45ee5eb --- /dev/null +++ b/packages/rocketchat-lib/server/lib/sandstorm.js @@ -0,0 +1,3 @@ +import { Sandstorm } from 'meteor/rocketchat:sandstorm'; + +RocketChat.Sandstorm = Sandstorm; diff --git a/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js b/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js index 0ee85ecddc51..2a2736fdcda4 100644 --- a/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js +++ b/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js @@ -5,6 +5,7 @@ import { settings } from 'meteor/rocketchat:settings'; import { callbacks } from 'meteor/rocketchat:callbacks'; import { Subscriptions } from 'meteor/rocketchat:models'; import { roomTypes } from 'meteor/rocketchat:utils'; +import { Sandstorm } from 'meteor/rocketchat:sandstorm'; import { callJoinRoom, messageContainsHighlight, parseMessageTextPerUser, replaceMentionedUsernamesWithFullNames } from '../functions/notifications/'; import { sendEmail, shouldNotifyEmail } from '../functions/notifications/email'; import { sendSinglePush, shouldNotifyMobile } from '../functions/notifications/mobile'; @@ -136,7 +137,7 @@ const sendNotification = async({ } if (notificationSent) { - RocketChat.Sandstorm.notify(message, [subscription.u._id], `@${ sender.username }: ${ message.msg }`, room.t === 'p' ? 'privateMessage' : 'message'); + Sandstorm.notify(message, [subscription.u._id], `@${ sender.username }: ${ message.msg }`, room.t === 'p' ? 'privateMessage' : 'message'); } }; diff --git a/packages/rocketchat-sandstorm/client/index.js b/packages/rocketchat-sandstorm/client/index.js index 4747a9261afc..11c6e2993767 100644 --- a/packages/rocketchat-sandstorm/client/index.js +++ b/packages/rocketchat-sandstorm/client/index.js @@ -1,2 +1,6 @@ -import './powerboxListener'; +import { Sandstorm } from './powerboxListener'; import './setPath'; + +export { + Sandstorm, +}; diff --git a/packages/rocketchat-sandstorm/client/powerboxListener.js b/packages/rocketchat-sandstorm/client/powerboxListener.js index 203c392fdde7..2bdef7411b05 100644 --- a/packages/rocketchat-sandstorm/client/powerboxListener.js +++ b/packages/rocketchat-sandstorm/client/powerboxListener.js @@ -1,9 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; -RocketChat.Sandstorm = RocketChat.Sandstorm || {}; +export const Sandstorm = {}; -RocketChat.Sandstorm.request = function() {}; +Sandstorm.request = function() {}; if (Meteor.settings.public.sandstorm) { const callbackMap = {}; @@ -20,7 +19,7 @@ if (Meteor.settings.public.sandstorm) { uiView: 'EAZQAQEAABEBF1EEAQH_5-Jn6pjXtNsAAAA', }; - RocketChat.Sandstorm.request = function(interfaceName, cb) { + Sandstorm.request = function(interfaceName, cb) { const rpcId = Math.random().toString(); callbackMap[rpcId] = cb; window.parent.postMessage({ powerboxRequest: { diff --git a/packages/rocketchat-sandstorm/package.js b/packages/rocketchat-sandstorm/package.js index 78cf693797ca..20ed7713efa7 100644 --- a/packages/rocketchat-sandstorm/package.js +++ b/packages/rocketchat-sandstorm/package.js @@ -8,7 +8,6 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', 'jalik:ufs', 'kadira:flow-router', ]); diff --git a/packages/rocketchat-sandstorm/server/events.js b/packages/rocketchat-sandstorm/server/events.js index 5607afdea542..1d40e7c6add4 100644 --- a/packages/rocketchat-sandstorm/server/events.js +++ b/packages/rocketchat-sandstorm/server/events.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { getHttpBridge, waitPromise } from './lib'; +import { Sandstorm } from './lib'; import _ from 'underscore'; -RocketChat.Sandstorm.notify = function() {}; +Sandstorm.notify = function() {}; if (process.env.SANDSTORM === '1') { const ACTIVITY_TYPES = { @@ -11,7 +11,7 @@ if (process.env.SANDSTORM === '1') { privateMessage: 1, }; - RocketChat.Sandstorm.notify = function(message, userIds, caption, type) { + Sandstorm.notify = function(message, userIds, caption, type) { const sessionId = message.sandstormSessionId; if (!sessionId) { return; diff --git a/packages/rocketchat-sandstorm/server/index.js b/packages/rocketchat-sandstorm/server/index.js index a7cb461eb0b8..21d3801e191f 100644 --- a/packages/rocketchat-sandstorm/server/index.js +++ b/packages/rocketchat-sandstorm/server/index.js @@ -1,3 +1,7 @@ -import './lib'; +import { Sandstorm } from './lib'; import './events'; import './powerbox'; + +export { + Sandstorm, +}; diff --git a/packages/rocketchat-sandstorm/server/lib.js b/packages/rocketchat-sandstorm/server/lib.js index b12aac9ca88f..41c9fec79e11 100644 --- a/packages/rocketchat-sandstorm/server/lib.js +++ b/packages/rocketchat-sandstorm/server/lib.js @@ -1,8 +1,7 @@ import Future from 'fibers/future'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { UploadFS } from 'meteor/jalik:ufs'; -RocketChat.Sandstorm = {}; +export const Sandstorm = {}; export let getHttpBridge; export let waitPromise; diff --git a/packages/rocketchat-sandstorm/server/powerbox.js b/packages/rocketchat-sandstorm/server/powerbox.js index c74f37c766c4..efa9f2d9f2d3 100644 --- a/packages/rocketchat-sandstorm/server/powerbox.js +++ b/packages/rocketchat-sandstorm/server/powerbox.js @@ -1,15 +1,15 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Sandstorm } from './lib'; import { getHttpBridge, waitPromise } from './lib'; -RocketChat.Sandstorm.offerUiView = function() {}; +Sandstorm.offerUiView = function() {}; if (process.env.SANDSTORM === '1') { const Capnp = require('capnp'); const Powerbox = Capnp.importSystem('sandstorm/powerbox.capnp'); const Grain = Capnp.importSystem('sandstorm/grain.capnp'); - RocketChat.Sandstorm.offerUiView = function(token, serializedDescriptor, sessionId) { + Sandstorm.offerUiView = function(token, serializedDescriptor, sessionId) { const httpBridge = getHttpBridge(); const session = httpBridge.getSessionContext(sessionId).context; const { api } = httpBridge.getSandstormApi(sessionId); @@ -43,7 +43,7 @@ if (process.env.SANDSTORM === '1') { }; }, sandstormOffer(token, serializedDescriptor) { - RocketChat.Sandstorm.offerUiView(token, serializedDescriptor, + Sandstorm.offerUiView(token, serializedDescriptor, this.connection.sandstormSessionId()); }, }); From 568ed1f534c9e73cf8bfbdf943cf67b0865a6109 Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 23 Jan 2019 14:36:52 -0200 Subject: [PATCH 12/18] Remove dependency of RC namespace in chatpal-search --- .../chatpal-search/client/template/admin.js | 7 ++++--- .../chatpal-search/client/template/result.js | 17 +++++++++-------- packages/chatpal-search/package.js | 3 +++ .../chatpal-search/server/provider/provider.js | 4 ++-- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/packages/chatpal-search/client/template/admin.js b/packages/chatpal-search/client/template/admin.js index d104c08311d3..3b51e8825245 100644 --- a/packages/chatpal-search/client/template/admin.js +++ b/packages/chatpal-search/client/template/admin.js @@ -2,7 +2,8 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasRole } from 'meteor/rocketchat:authorization'; import toastr from 'toastr'; Template.ChatpalAdmin.onCreated(function() { @@ -13,7 +14,7 @@ Template.ChatpalAdmin.onCreated(function() { this.apiKey = new ReactiveVar(); - const lang = RocketChat.settings.get('Language'); + const lang = settings.get('Language'); this.lang = (lang === 'de' || lang === 'en') ? lang : 'en'; @@ -58,7 +59,7 @@ Template.ChatpalAdmin.helpers({ return Template.instance().apiKey.get(); }, isAdmin() { - return RocketChat.authz.hasRole(Meteor.userId(), 'admin'); + return hasRole(Meteor.userId(), 'admin'); }, tac() { return Template.instance().tac.get(); diff --git a/packages/chatpal-search/client/template/result.js b/packages/chatpal-search/client/template/result.js index 6028c81a6e6b..750fa9a83028 100644 --- a/packages/chatpal-search/client/template/result.js +++ b/packages/chatpal-search/client/template/result.js @@ -3,7 +3,8 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { roomTypes } from 'meteor/rocketchat:utils'; +import { Subscriptions } from 'meteor/rocketchat:models'; Template.ChatpalSearchResultTemplate.onCreated(function() { this.badRequest = new ReactiveVar(false); @@ -91,17 +92,17 @@ Template.ChatpalSearchSingleMessage.helpers({ if (room && room.t === 'd') { return 'at'; } - return RocketChat.roomTypes.getIcon(room && room.t); + return roomTypes.getIcon(room && room.t); }, roomLink() { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: this.rid }); - return RocketChat.roomTypes.getRouteLink(subscription.t, subscription); + const subscription = Subscriptions.findOne({ rid: this.rid }); + return roomTypes.getRouteLink(subscription.t, subscription); }, roomName() { const room = Session.get(`roomData${ this.rid }`); - return RocketChat.roomTypes.getRoomName(room.t, room); + return roomTypes.getRoomName(room.t, room); }, time() { @@ -118,11 +119,11 @@ Template.ChatpalSearchSingleRoom.helpers({ if (room && room.t === 'd') { return 'at'; } - return RocketChat.roomTypes.getIcon(room && room.t); + return roomTypes.getIcon(room && room.t); }, roomLink() { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: this._id }); - return RocketChat.roomTypes.getRouteLink(subscription.t, subscription); + const subscription = Subscriptions.findOne({ rid: this._id }); + return roomTypes.getRouteLink(subscription.t, subscription); }, }); diff --git a/packages/chatpal-search/package.js b/packages/chatpal-search/package.js index 06f5fe53821a..cdbfd317716f 100644 --- a/packages/chatpal-search/package.js +++ b/packages/chatpal-search/package.js @@ -10,6 +10,9 @@ Package.onUse(function(api) { 'ecmascript', 'templating', 'rocketchat:utils', + 'rocketchat:settings', + 'rocketchat:models', + 'rocketchat:authorization', ]); api.addAssets([ 'server/asset/chatpal-enter.svg', diff --git a/packages/chatpal-search/server/provider/provider.js b/packages/chatpal-search/server/provider/provider.js index d6175f48c318..a7c732c269ef 100644 --- a/packages/chatpal-search/server/provider/provider.js +++ b/packages/chatpal-search/server/provider/provider.js @@ -2,7 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { searchProviderService, SearchProvider } from 'meteor/rocketchat:search'; import Index from './index'; import ChatpalLogger from '../utils/logger'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions } from 'meteor/rocketchat:models'; /** * The chatpal search provider enables chatpal search. An appropriate backedn has to be specified by settings. @@ -301,7 +301,7 @@ class ChatpalProvider extends SearchProvider { * @private */ _getAcl(context) { - return RocketChat.models.Subscriptions.find({ 'u._id': context.uid }).fetch().map((room) => room.rid); + return Subscriptions.find({ 'u._id': context.uid }).fetch().map((room) => room.rid); } /** From 5d60447707688a0d97116ba837e63977b276eeec Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 15:22:28 -0200 Subject: [PATCH 13/18] Move CreadentialTokens model to rc-models --- packages/rocketchat-cas/server/index.js | 1 - packages/rocketchat-models/server/index.js | 2 ++ .../server/models/CredentialTokens.js | 8 +++++--- 3 files changed, 7 insertions(+), 4 deletions(-) rename packages/{rocketchat-cas => rocketchat-models}/server/models/CredentialTokens.js (78%) diff --git a/packages/rocketchat-cas/server/index.js b/packages/rocketchat-cas/server/index.js index 451c7d5a8aa0..0ad22d77b198 100644 --- a/packages/rocketchat-cas/server/index.js +++ b/packages/rocketchat-cas/server/index.js @@ -1,3 +1,2 @@ -import './models/CredentialTokens'; import './cas_rocketchat'; import './cas_server'; diff --git a/packages/rocketchat-models/server/index.js b/packages/rocketchat-models/server/index.js index 524abe1f5db4..54b5dfc3289c 100644 --- a/packages/rocketchat-models/server/index.js +++ b/packages/rocketchat-models/server/index.js @@ -16,6 +16,7 @@ import Roles from './models/Roles'; import CustomSounds from './models/CustomSounds'; import Integrations from './models/Integrations'; import IntegrationHistory from './models/IntegrationHistory'; +import CredentialTokens from './models/CredentialTokens'; export { Base, @@ -36,4 +37,5 @@ export { CustomSounds, Integrations, IntegrationHistory, + CredentialTokens, }; diff --git a/packages/rocketchat-cas/server/models/CredentialTokens.js b/packages/rocketchat-models/server/models/CredentialTokens.js similarity index 78% rename from packages/rocketchat-cas/server/models/CredentialTokens.js rename to packages/rocketchat-models/server/models/CredentialTokens.js index a484eb978b39..7659538e032e 100644 --- a/packages/rocketchat-cas/server/models/CredentialTokens.js +++ b/packages/rocketchat-models/server/models/CredentialTokens.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from './_Base'; -RocketChat.models.CredentialTokens = new class extends RocketChat.models._Base { +export class CredentialTokens extends Base { constructor() { super('credential_tokens'); @@ -27,4 +27,6 @@ RocketChat.models.CredentialTokens = new class extends RocketChat.models._Base { return this.findOne(query); } -}; +} + +export default new CredentialTokens(); From dd9303fd9bd71b11890534d6b40302ceeb40e960 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 15:26:04 -0200 Subject: [PATCH 14/18] Move getUsernameSuggestion function and method from server/ to rc-lib --- packages/rocketchat-lib/package.js | 5 +++- .../functions}/getUsernameSuggestion.js | 28 ++++++------------- .../rocketchat-lib/server/functions/index.js | 1 + packages/rocketchat-lib/server/index.js | 2 ++ .../server/methods/getUsernameSuggestion.js | 16 +++++++++++ 5 files changed, 31 insertions(+), 21 deletions(-) rename {server/methods => packages/rocketchat-lib/server/functions}/getUsernameSuggestion.js (69%) create mode 100644 packages/rocketchat-lib/server/index.js create mode 100644 packages/rocketchat-lib/server/methods/getUsernameSuggestion.js diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index b68485aab8d7..8639b3ad7d6d 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -22,6 +22,7 @@ Package.onUse(function(api) { api.use('mongo'); api.use('oauth'); api.use('matb33:collection-hooks'); + api.use('yasaricli:slugify'); api.use('service-configuration'); api.use('check'); api.use('rocketchat:utils'); @@ -133,6 +134,7 @@ Package.onUse(function(api) { api.addFiles('server/functions/validateCustomFields.js', 'server'); api.addFiles('server/functions/Notifications.js', 'server'); api.addFiles('server/functions/authorization.js', 'server'); + api.addFiles('server/functions/getUsernameSuggestion.js', 'server'); // SERVER LIB api.addFiles('server/lib/configLogger.js', 'server'); @@ -209,6 +211,7 @@ Package.onUse(function(api) { api.addFiles('server/methods/unarchiveRoom.js', 'server'); api.addFiles('server/methods/unblockUser.js', 'server'); api.addFiles('server/methods/updateMessage.js', 'server'); + api.addFiles('server/methods/getUsernameSuggestion.js', 'server'); // SERVER STARTUP api.addFiles('server/startup/settingsOnLoadCdnPrefix.js', 'server'); @@ -275,7 +278,7 @@ Package.onUse(function(api) { api.export('openRoom', 'client'); // exports - api.mainModule('server/lib/index.js', 'server'); + api.mainModule('server/index.js', 'server'); api.mainModule('client/lib/index.js', 'client'); api.imply('tap:i18n'); diff --git a/server/methods/getUsernameSuggestion.js b/packages/rocketchat-lib/server/functions/getUsernameSuggestion.js similarity index 69% rename from server/methods/getUsernameSuggestion.js rename to packages/rocketchat-lib/server/functions/getUsernameSuggestion.js index 076bd08e0523..30958d22743b 100644 --- a/server/methods/getUsernameSuggestion.js +++ b/packages/rocketchat-lib/server/functions/getUsernameSuggestion.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { slugify } from 'meteor/yasaricli:slugify'; +import { Users } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; function slug(text) { return slugify(text, '.').replace(/[^0-9a-z-_.]/g, ''); @@ -14,13 +16,13 @@ function usernameIsAvaliable(username) { return false; } - return !RocketChat.models.Users.findOneByUsername(username); + return !Users.findOneByUsername(username); } -const name = (username) => (RocketChat.settings.get('UTF8_Names_Slugify') ? slug(username) : username); +const name = (username) => (settings.get('UTF8_Names_Slugify') ? slug(username) : username); -function generateSuggestion(user) { +export function generateUsernameSuggestion(user) { let usernames = []; if (Meteor.settings.public.sandstorm) { @@ -67,9 +69,9 @@ function generateSuggestion(user) { } } - usernames.push(RocketChat.settings.get('Accounts_DefaultUsernamePrefixSuggestion')); + usernames.push(settings.get('Accounts_DefaultUsernamePrefixSuggestion')); - let index = RocketChat.models.Users.find({ username: new RegExp(`^${ usernames[0] }-[0-9]+`) }).count(); + let index = Users.find({ username: new RegExp(`^${ usernames[0] }-[0-9]+`) }).count(); const username = ''; while (!username) { if (usernameIsAvaliable(`${ usernames[0] }-${ index }`)) { @@ -79,18 +81,4 @@ function generateSuggestion(user) { } } -RocketChat.generateUsernameSuggestion = generateSuggestion; - -Meteor.methods({ - getUsernameSuggestion() { - if (!Meteor.userId()) { - throw new Meteor.Error('error-invalid-user', 'Invalid user', { - method: 'getUsernameSuggestion', - }); - } - - const user = Meteor.user(); - - return generateSuggestion(user); - }, -}); +RocketChat.generateUsernameSuggestion = generateUsernameSuggestion; diff --git a/packages/rocketchat-lib/server/functions/index.js b/packages/rocketchat-lib/server/functions/index.js index 11eac02244a3..de83cbb57af4 100644 --- a/packages/rocketchat-lib/server/functions/index.js +++ b/packages/rocketchat-lib/server/functions/index.js @@ -23,3 +23,4 @@ export { setUsername } from './setUsername'; export { unarchiveRoom } from './unarchiveRoom'; export { updateMessage } from './updateMessage'; export { validateCustomFields } from './validateCustomFields'; +export { generateUsernameSuggestion } from './getUsernameSuggestion'; diff --git a/packages/rocketchat-lib/server/index.js b/packages/rocketchat-lib/server/index.js new file mode 100644 index 000000000000..d43727359c92 --- /dev/null +++ b/packages/rocketchat-lib/server/index.js @@ -0,0 +1,2 @@ +export * from './lib'; +export * from './functions'; diff --git a/packages/rocketchat-lib/server/methods/getUsernameSuggestion.js b/packages/rocketchat-lib/server/methods/getUsernameSuggestion.js new file mode 100644 index 000000000000..1e736489136c --- /dev/null +++ b/packages/rocketchat-lib/server/methods/getUsernameSuggestion.js @@ -0,0 +1,16 @@ +import { Meteor } from 'meteor/meteor'; +import { generateUsernameSuggestion } from '../functions'; + +Meteor.methods({ + getUsernameSuggestion() { + if (!Meteor.userId()) { + throw new Meteor.Error('error-invalid-user', 'Invalid user', { + method: 'getUsernameSuggestion', + }); + } + + const user = Meteor.user(); + + return generateUsernameSuggestion(user); + }, +}); From 842a519c651c6b51d600b45e551f4acdc7bb2472 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 15:27:36 -0200 Subject: [PATCH 15/18] Remove dependency of RC namespace in meteor saml --- packages/meteor-accounts-saml/package.js | 2 +- .../server/saml_rocketchat.js | 62 +++++++++---------- .../server/saml_server.js | 11 ++-- 3 files changed, 38 insertions(+), 37 deletions(-) diff --git a/packages/meteor-accounts-saml/package.js b/packages/meteor-accounts-saml/package.js index 4c080b8739d2..467f0580c3bc 100644 --- a/packages/meteor-accounts-saml/package.js +++ b/packages/meteor-accounts-saml/package.js @@ -15,9 +15,9 @@ Package.on_use(function(api) { 'routepolicy', 'webapp', 'rocketchat:lib', + 'rocketchat:models', 'service-configuration', ], 'server'); - api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/meteor-accounts-saml/server/saml_rocketchat.js b/packages/meteor-accounts-saml/server/saml_rocketchat.js index 4b08f8f0e5c4..6132ba251946 100644 --- a/packages/meteor-accounts-saml/server/saml_rocketchat.js +++ b/packages/meteor-accounts-saml/server/saml_rocketchat.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { Logger } from 'meteor/rocketchat:logger'; import { ServiceConfiguration } from 'meteor/service-configuration'; +import { settings } from 'meteor/rocketchat:settings'; const logger = new Logger('steffo:meteor-accounts-saml', { methods: { @@ -12,92 +12,92 @@ const logger = new Logger('steffo:meteor-accounts-saml', { }, }); -RocketChat.settings.addGroup('SAML'); +settings.addGroup('SAML'); Meteor.methods({ addSamlService(name) { - RocketChat.settings.add(`SAML_Custom_${ name }`, false, { + settings.add(`SAML_Custom_${ name }`, false, { type: 'boolean', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Enable', }); - RocketChat.settings.add(`SAML_Custom_${ name }_provider`, 'provider-name', { + settings.add(`SAML_Custom_${ name }_provider`, 'provider-name', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Provider', }); - RocketChat.settings.add(`SAML_Custom_${ name }_entry_point`, 'https://example.com/simplesaml/saml2/idp/SSOService.php', { + settings.add(`SAML_Custom_${ name }_entry_point`, 'https://example.com/simplesaml/saml2/idp/SSOService.php', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Entry_point', }); - RocketChat.settings.add(`SAML_Custom_${ name }_idp_slo_redirect_url`, 'https://example.com/simplesaml/saml2/idp/SingleLogoutService.php', { + settings.add(`SAML_Custom_${ name }_idp_slo_redirect_url`, 'https://example.com/simplesaml/saml2/idp/SingleLogoutService.php', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_IDP_SLO_Redirect_URL', }); - RocketChat.settings.add(`SAML_Custom_${ name }_issuer`, 'https://your-rocket-chat/_saml/metadata/provider-name', { + settings.add(`SAML_Custom_${ name }_issuer`, 'https://your-rocket-chat/_saml/metadata/provider-name', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Issuer', }); - RocketChat.settings.add(`SAML_Custom_${ name }_cert`, '', { + settings.add(`SAML_Custom_${ name }_cert`, '', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Cert', multiline: true, }); - RocketChat.settings.add(`SAML_Custom_${ name }_public_cert`, '', { + settings.add(`SAML_Custom_${ name }_public_cert`, '', { type: 'string', group: 'SAML', section: name, multiline: true, i18nLabel: 'SAML_Custom_Public_Cert', }); - RocketChat.settings.add(`SAML_Custom_${ name }_private_key`, '', { + settings.add(`SAML_Custom_${ name }_private_key`, '', { type: 'string', group: 'SAML', section: name, multiline: true, i18nLabel: 'SAML_Custom_Private_Key', }); - RocketChat.settings.add(`SAML_Custom_${ name }_button_label_text`, '', { + settings.add(`SAML_Custom_${ name }_button_label_text`, '', { type: 'string', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', }); - RocketChat.settings.add(`SAML_Custom_${ name }_button_label_color`, '#FFFFFF', { + settings.add(`SAML_Custom_${ name }_button_label_color`, '#FFFFFF', { type: 'string', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', }); - RocketChat.settings.add(`SAML_Custom_${ name }_button_color`, '#13679A', { + settings.add(`SAML_Custom_${ name }_button_color`, '#13679A', { type: 'string', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Button_Color', }); - RocketChat.settings.add(`SAML_Custom_${ name }_generate_username`, false, { + settings.add(`SAML_Custom_${ name }_generate_username`, false, { type: 'boolean', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Generate_Username', }); - RocketChat.settings.add(`SAML_Custom_${ name }_debug`, false, { + settings.add(`SAML_Custom_${ name }_debug`, false, { type: 'boolean', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Debug', }); - RocketChat.settings.add(`SAML_Custom_${ name }_logout_behaviour`, 'SAML', { + settings.add(`SAML_Custom_${ name }_logout_behaviour`, 'SAML', { type: 'select', values: [ { key: 'SAML', i18nLabel: 'SAML_Custom_Logout_Behaviour_Terminate_SAML_Session' }, @@ -112,22 +112,22 @@ Meteor.methods({ const getSamlConfigs = function(service) { return { - buttonLabelText: RocketChat.settings.get(`${ service.key }_button_label_text`), - buttonLabelColor: RocketChat.settings.get(`${ service.key }_button_label_color`), - buttonColor: RocketChat.settings.get(`${ service.key }_button_color`), + buttonLabelText: settings.get(`${ service.key }_button_label_text`), + buttonLabelColor: settings.get(`${ service.key }_button_label_color`), + buttonColor: settings.get(`${ service.key }_button_color`), clientConfig: { - provider: RocketChat.settings.get(`${ service.key }_provider`), + provider: settings.get(`${ service.key }_provider`), }, - entryPoint: RocketChat.settings.get(`${ service.key }_entry_point`), - idpSLORedirectURL: RocketChat.settings.get(`${ service.key }_idp_slo_redirect_url`), - generateUsername: RocketChat.settings.get(`${ service.key }_generate_username`), - debug: RocketChat.settings.get(`${ service.key }_debug`), - issuer: RocketChat.settings.get(`${ service.key }_issuer`), - logoutBehaviour: RocketChat.settings.get(`${ service.key }_logout_behaviour`), + entryPoint: settings.get(`${ service.key }_entry_point`), + idpSLORedirectURL: settings.get(`${ service.key }_idp_slo_redirect_url`), + generateUsername: settings.get(`${ service.key }_generate_username`), + debug: settings.get(`${ service.key }_debug`), + issuer: settings.get(`${ service.key }_issuer`), + logoutBehaviour: settings.get(`${ service.key }_logout_behaviour`), secret: { - privateKey: RocketChat.settings.get(`${ service.key }_private_key`), - publicCert: RocketChat.settings.get(`${ service.key }_public_cert`), - cert: RocketChat.settings.get(`${ service.key }_cert`), + privateKey: settings.get(`${ service.key }_private_key`), + publicCert: settings.get(`${ service.key }_public_cert`), + cert: settings.get(`${ service.key }_cert`), }, }; }; @@ -168,7 +168,7 @@ const configureSamlService = function(samlConfigs) { }; const updateServices = debounce(() => { - const services = RocketChat.settings.get(/^(SAML_Custom_)[a-z]+$/i); + const services = settings.get(/^(SAML_Custom_)[a-z]+$/i); Accounts.saml.settings.providers = services.map((service) => { if (service.value === true) { const samlConfigs = getSamlConfigs(service); @@ -187,7 +187,7 @@ const updateServices = debounce(() => { }, 2000); -RocketChat.settings.get(/^SAML_.+/, updateServices); +settings.get(/^SAML_.+/, updateServices); Meteor.startup(() => Meteor.call('addSamlService', 'Default')); diff --git a/packages/meteor-accounts-saml/server/saml_server.js b/packages/meteor-accounts-saml/server/saml_server.js index 8d4ccddde087..9f88f108e044 100644 --- a/packages/meteor-accounts-saml/server/saml_server.js +++ b/packages/meteor-accounts-saml/server/saml_server.js @@ -2,8 +2,9 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { Random } from 'meteor/random'; import { WebApp } from 'meteor/webapp'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { RoutePolicy } from 'meteor/routepolicy'; +import { CredentialTokens } from 'meteor/rocketchat:models'; +import { generateUsernameSuggestion } from 'meteor/rocketchat:lib'; import bodyParser from 'body-parser'; import { SAML } from './saml_utils'; import _ from 'underscore'; @@ -126,7 +127,7 @@ Accounts.registerLoginHandler(function(loginRequest) { }; if (Accounts.saml.settings.generateUsername === true) { - const username = RocketChat.generateUsernameSuggestion(newUser); + const username = generateUsernameSuggestion(newUser); if (username) { newUser.username = username; } @@ -176,19 +177,19 @@ Accounts.registerLoginHandler(function(loginRequest) { }); Accounts.saml.hasCredential = function(credentialToken) { - return RocketChat.models.CredentialTokens.findOneById(credentialToken) != null; + return CredentialTokens.findOneById(credentialToken) != null; }; Accounts.saml.retrieveCredential = function(credentialToken) { // The credentialToken in all these functions corresponds to SAMLs inResponseTo field and is mandatory to check. - const data = RocketChat.models.CredentialTokens.findOneById(credentialToken); + const data = CredentialTokens.findOneById(credentialToken); if (data) { return data.userInfo; } }; Accounts.saml.storeCredential = function(credentialToken, loginResult) { - RocketChat.models.CredentialTokens.create(credentialToken, loginResult); + CredentialTokens.create(credentialToken, loginResult); }; const closePopup = function(res, err) { From ba81c021ceba1c88039d3b4a7e424b746a0ddbfd Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 15:48:05 -0200 Subject: [PATCH 16/18] Remove dependency of RC namespace in rc-theme --- packages/rocketchat_theme/package.js | 2 +- packages/rocketchat_theme/server/server.js | 101 +++++++++--------- packages/rocketchat_theme/server/variables.js | 15 +-- 3 files changed, 60 insertions(+), 58 deletions(-) diff --git a/packages/rocketchat_theme/package.js b/packages/rocketchat_theme/package.js index 4509cc69be44..ebad7deda55f 100644 --- a/packages/rocketchat_theme/package.js +++ b/packages/rocketchat_theme/package.js @@ -10,7 +10,7 @@ Package.onUse(function(api) { 'less', 'webapp', 'webapp-hashing', - 'rocketchat:lib', + 'rocketchat:settings', 'rocketchat:logger', 'rocketchat:assets', 'templating', diff --git a/packages/rocketchat_theme/server/server.js b/packages/rocketchat_theme/server/server.js index 977d9cfb2023..a13dc5f07480 100644 --- a/packages/rocketchat_theme/server/server.js +++ b/packages/rocketchat_theme/server/server.js @@ -1,6 +1,6 @@ import { WebApp } from 'meteor/webapp'; import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { Logger } from 'meteor/rocketchat:logger'; import { WebAppHashing } from 'meteor/webapp-hashing'; import _ from 'underscore'; @@ -16,54 +16,15 @@ const logger = new Logger('rocketchat:theme', { }, }); -WebApp.rawConnectHandlers.use(function(req, res, next) { - const path = req.url.split('?')[0]; - const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; - if (path === `${ prefix }/theme.css`) { - const css = RocketChat.theme.getCss(); - const hash = crypto.createHash('sha1').update(css).digest('hex'); - res.setHeader('Content-Type', 'text/css; charset=UTF-8'); - res.setHeader('ETag', `"${ hash }"`); - res.write(css); - return res.end(); - } else { - return next(); - } -}); - -const { calculateClientHash } = WebAppHashing; - -WebAppHashing.calculateClientHash = function(manifest, includeFilter, runtimeConfigOverride) { - const css = RocketChat.theme.getCss(); - if (css.trim() !== '') { - const hash = crypto.createHash('sha1').update(css).digest('hex'); - let themeManifestItem = _.find(manifest, function(item) { - return item.path === 'app/theme.css'; - }); - if (themeManifestItem == null) { - themeManifestItem = {}; - manifest.push(themeManifestItem); - } - themeManifestItem.path = 'app/theme.css'; - themeManifestItem.type = 'css'; - themeManifestItem.cacheable = true; - themeManifestItem.where = 'client'; - themeManifestItem.url = `/theme.css?${ hash }`; - themeManifestItem.size = css.length; - themeManifestItem.hash = hash; - } - return calculateClientHash.call(this, manifest, includeFilter, runtimeConfigOverride); -}; - -RocketChat.theme = new class { +export const theme = new class { constructor() { this.variables = {}; this.packageCallbacks = []; this.files = ['server/colors.less']; this.customCSS = ''; - RocketChat.settings.add('css', ''); - RocketChat.settings.addGroup('Layout'); - RocketChat.settings.onload('css', Meteor.bindEnvironment((key, value, initialLoad) => { + settings.add('css', ''); + settings.addGroup('Layout'); + settings.onload('css', Meteor.bindEnvironment((key, value, initialLoad) => { if (!initialLoad) { Meteor.startup(function() { process.emit('message', { @@ -74,8 +35,8 @@ RocketChat.theme = new class { })); this.compileDelayed = _.debounce(Meteor.bindEnvironment(this.compile.bind(this)), 100); Meteor.startup(() => { - RocketChat.settings.onAfterInitialLoad(() => { - RocketChat.settings.get(/^theme-./, Meteor.bindEnvironment((key, value) => { + settings.onAfterInitialLoad(() => { + settings.get(/^theme-./, Meteor.bindEnvironment((key, value) => { if (key === 'theme-custom-css' && value != null) { this.customCSS = value; } else { @@ -110,7 +71,7 @@ RocketChat.theme = new class { if (err != null) { return console.log(err); } - RocketChat.settings.updateById('css', data.css); + settings.updateById('css', data.css); return Meteor.startup(function() { return Meteor.setTimeout(function() { return process.emit('message', { @@ -131,7 +92,7 @@ RocketChat.theme = new class { section, }; - return RocketChat.settings.add(`theme-color-${ name }`, value, config); + return settings.add(`theme-color-${ name }`, value, config); } addVariable(type, name, value, section, persist = true, editor, allowedTypes, property) { @@ -149,7 +110,7 @@ RocketChat.theme = new class { allowedTypes, property, }; - return RocketChat.settings.add(`theme-${ type }-${ name }`, value, config); + return settings.add(`theme-${ type }-${ name }`, value, config); } } @@ -182,7 +143,47 @@ RocketChat.theme = new class { } getCss() { - return RocketChat.settings.get('css') || ''; + return settings.get('css') || ''; } }; + + +WebApp.rawConnectHandlers.use(function(req, res, next) { + const path = req.url.split('?')[0]; + const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; + if (path === `${ prefix }/theme.css`) { + const css = theme.getCss(); + const hash = crypto.createHash('sha1').update(css).digest('hex'); + res.setHeader('Content-Type', 'text/css; charset=UTF-8'); + res.setHeader('ETag', `"${ hash }"`); + res.write(css); + return res.end(); + } else { + return next(); + } +}); + +const { calculateClientHash } = WebAppHashing; + +WebAppHashing.calculateClientHash = function(manifest, includeFilter, runtimeConfigOverride) { + const css = theme.getCss(); + if (css.trim() !== '') { + const hash = crypto.createHash('sha1').update(css).digest('hex'); + let themeManifestItem = _.find(manifest, function(item) { + return item.path === 'app/theme.css'; + }); + if (themeManifestItem == null) { + themeManifestItem = {}; + manifest.push(themeManifestItem); + } + themeManifestItem.path = 'app/theme.css'; + themeManifestItem.type = 'css'; + themeManifestItem.cacheable = true; + themeManifestItem.where = 'client'; + themeManifestItem.url = `/theme.css?${ hash }`; + themeManifestItem.size = css.length; + themeManifestItem.hash = hash; + } + return calculateClientHash.call(this, manifest, includeFilter, runtimeConfigOverride); +}; diff --git a/packages/rocketchat_theme/server/variables.js b/packages/rocketchat_theme/server/variables.js index 8596dbbb8ea6..0206233a9e36 100644 --- a/packages/rocketchat_theme/server/variables.js +++ b/packages/rocketchat_theme/server/variables.js @@ -1,4 +1,5 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { theme } from './server'; // TODO: Define registers/getters/setters for packages to work with established // heirarchy of colors instead of making duplicate definitions // TODO: Settings pages to show simple separation of major/minor/addon colors @@ -21,9 +22,9 @@ const colors = [...Assets.getText('client/imports/general/variables.css').match( colors.forEach(([key, color]) => { if (/var/.test(color)) { const [, value] = color.match(/var\(--(.*?)\)/i); - return RocketChat.theme.addPublicColor(key, value, 'Colors', 'expression'); + return theme.addPublicColor(key, value, 'Colors', 'expression'); } - RocketChat.theme.addPublicColor(key, color, 'Colors'); + theme.addPublicColor(key, color, 'Colors'); }); const majorColors = { @@ -58,17 +59,17 @@ const minorColors = { // Bulk-add settings for color scheme Object.keys(majorColors).forEach((key) => { const value = majorColors[key]; - RocketChat.theme.addPublicColor(key, value, 'Old Colors'); + theme.addPublicColor(key, value, 'Old Colors'); }); Object.keys(minorColors).forEach((key) => { const value = minorColors[key]; - RocketChat.theme.addPublicColor(key, value, 'Old Colors (minor)', 'expression'); + theme.addPublicColor(key, value, 'Old Colors (minor)', 'expression'); }); -RocketChat.theme.addPublicFont('body-font-family', '-apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, Oxygen, Ubuntu, Cantarell, \'Helvetica Neue\', \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Meiryo UI\', Arial, sans-serif'); +theme.addPublicFont('body-font-family', '-apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, Oxygen, Ubuntu, Cantarell, \'Helvetica Neue\', \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Meiryo UI\', Arial, sans-serif'); -RocketChat.settings.add('theme-custom-css', '', { +settings.add('theme-custom-css', '', { group: 'Layout', type: 'code', code: 'text/css', From 1290be4a2ce95775cad3caef47eb96eac6afffb3 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 16:08:57 -0200 Subject: [PATCH 17/18] Move 2FA Users model to rc-models --- packages/rocketchat-2fa/server/index.js | 1 - .../rocketchat-2fa/server/models/users.js | 51 ------------------- .../rocketchat-models/server/models/Users.js | 50 ++++++++++++++++++ 3 files changed, 50 insertions(+), 52 deletions(-) delete mode 100644 packages/rocketchat-2fa/server/models/users.js diff --git a/packages/rocketchat-2fa/server/index.js b/packages/rocketchat-2fa/server/index.js index 2f088d337986..ae9766e3a2bb 100644 --- a/packages/rocketchat-2fa/server/index.js +++ b/packages/rocketchat-2fa/server/index.js @@ -1,6 +1,5 @@ import './startup/settings'; import './lib/totp'; -import './models/users'; import './methods/checkCodesRemaining'; import './methods/disable'; import './methods/enable'; diff --git a/packages/rocketchat-2fa/server/models/users.js b/packages/rocketchat-2fa/server/models/users.js deleted file mode 100644 index 80190c9cc3a1..000000000000 --- a/packages/rocketchat-2fa/server/models/users.js +++ /dev/null @@ -1,51 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Users.disable2FAAndSetTempSecretByUserId = function(userId, tempToken) { - return this.update({ - _id: userId, - }, { - $set: { - 'services.totp': { - enabled: false, - tempSecret: tempToken, - }, - }, - }); -}; - -RocketChat.models.Users.enable2FAAndSetSecretAndCodesByUserId = function(userId, secret, backupCodes) { - return this.update({ - _id: userId, - }, { - $set: { - 'services.totp.enabled': true, - 'services.totp.secret': secret, - 'services.totp.hashedBackup': backupCodes, - }, - $unset: { - 'services.totp.tempSecret': 1, - }, - }); -}; - -RocketChat.models.Users.disable2FAByUserId = function(userId) { - return this.update({ - _id: userId, - }, { - $set: { - 'services.totp': { - enabled: false, - }, - }, - }); -}; - -RocketChat.models.Users.update2FABackupCodesByUserId = function(userId, backupCodes) { - return this.update({ - _id: userId, - }, { - $set: { - 'services.totp.hashedBackup': backupCodes, - }, - }); -}; diff --git a/packages/rocketchat-models/server/models/Users.js b/packages/rocketchat-models/server/models/Users.js index f90e64fa4a93..770c4a8ad9f5 100644 --- a/packages/rocketchat-models/server/models/Users.js +++ b/packages/rocketchat-models/server/models/Users.js @@ -52,6 +52,56 @@ export class Users extends Base { }; } + disable2FAAndSetTempSecretByUserId(userId, tempToken) { + return this.update({ + _id: userId, + }, { + $set: { + 'services.totp': { + enabled: false, + tempSecret: tempToken, + }, + }, + }); + } + + enable2FAAndSetSecretAndCodesByUserId(userId, secret, backupCodes) { + return this.update({ + _id: userId, + }, { + $set: { + 'services.totp.enabled': true, + 'services.totp.secret': secret, + 'services.totp.hashedBackup': backupCodes, + }, + $unset: { + 'services.totp.tempSecret': 1, + }, + }); + } + + disable2FAByUserId(userId) { + return this.update({ + _id: userId, + }, { + $set: { + 'services.totp': { + enabled: false, + }, + }, + }); + } + + update2FABackupCodesByUserId(userId, backupCodes) { + return this.update({ + _id: userId, + }, { + $set: { + 'services.totp.hashedBackup': backupCodes, + }, + }); + } + findByIdsWithPublicE2EKey(ids, options) { const query = { _id: { From 25b121ebf662acc2e8bebe7c2cdb601eaa4cc100 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 16:09:46 -0200 Subject: [PATCH 18/18] Remove dependency of RC namespace in rc-2fa --- packages/rocketchat-2fa/client/TOTPPassword.js | 2 +- packages/rocketchat-2fa/client/accountSecurity.js | 6 +++--- packages/rocketchat-2fa/package.js | 6 ++++-- packages/rocketchat-2fa/server/index.js | 1 - packages/rocketchat-2fa/server/lib/totp.js | 9 +++++---- packages/rocketchat-2fa/server/loginHandler.js | 10 ++++++---- packages/rocketchat-2fa/server/methods/disable.js | 7 ++++--- packages/rocketchat-2fa/server/methods/enable.js | 9 +++++---- .../rocketchat-2fa/server/methods/regenerateCodes.js | 9 +++++---- .../rocketchat-2fa/server/methods/validateTempToken.js | 9 +++++---- packages/rocketchat-2fa/server/startup/settings.js | 4 ++-- 11 files changed, 40 insertions(+), 32 deletions(-) diff --git a/packages/rocketchat-2fa/client/TOTPPassword.js b/packages/rocketchat-2fa/client/TOTPPassword.js index 7bb15b1fa738..50bb8e31ccb3 100644 --- a/packages/rocketchat-2fa/client/TOTPPassword.js +++ b/packages/rocketchat-2fa/client/TOTPPassword.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { modal } from 'meteor/rocketchat:ui'; +import { modal } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; diff --git a/packages/rocketchat-2fa/client/accountSecurity.js b/packages/rocketchat-2fa/client/accountSecurity.js index b99fb2fc3e49..3a530bd7b2ab 100644 --- a/packages/rocketchat-2fa/client/accountSecurity.js +++ b/packages/rocketchat-2fa/client/accountSecurity.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; -import { modal } from 'meteor/rocketchat:ui'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { modal } from 'meteor/rocketchat:ui-utils'; +import { settings } from 'meteor/rocketchat:settings'; import { t } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; import qrcode from 'yaqrcode'; @@ -27,7 +27,7 @@ Template.accountSecurity.helpers({ return Template.instance().state.get() === 'registering'; }, isAllowed() { - return RocketChat.settings.get('Accounts_TwoFactorAuthentication_Enabled'); + return settings.get('Accounts_TwoFactorAuthentication_Enabled'); }, codesRemaining() { if (Template.instance().codesRemaining.get()) { diff --git a/packages/rocketchat-2fa/package.js b/packages/rocketchat-2fa/package.js index 71f3cf76599f..889045bb342c 100644 --- a/packages/rocketchat-2fa/package.js +++ b/packages/rocketchat-2fa/package.js @@ -11,11 +11,13 @@ Package.onUse(function(api) { 'accounts-base', 'ecmascript', 'templating', - 'rocketchat:lib', + 'rocketchat:settings', 'sha', 'random', - 'rocketchat:ui', + 'rocketchat:ui-utils', 'rocketchat:utils', + 'rocketchat:models', + 'rocketchat:callbacks', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-2fa/server/index.js b/packages/rocketchat-2fa/server/index.js index ae9766e3a2bb..e5d5ab3fc445 100644 --- a/packages/rocketchat-2fa/server/index.js +++ b/packages/rocketchat-2fa/server/index.js @@ -1,5 +1,4 @@ import './startup/settings'; -import './lib/totp'; import './methods/checkCodesRemaining'; import './methods/disable'; import './methods/enable'; diff --git a/packages/rocketchat-2fa/server/lib/totp.js b/packages/rocketchat-2fa/server/lib/totp.js index 8d794d9ec359..2a1273c74ae8 100644 --- a/packages/rocketchat-2fa/server/lib/totp.js +++ b/packages/rocketchat-2fa/server/lib/totp.js @@ -1,9 +1,10 @@ import { SHA256 } from 'meteor/sha'; import { Random } from 'meteor/random'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; import speakeasy from 'speakeasy'; -RocketChat.TOTP = { +export const TOTP = { generateSecret() { return speakeasy.generateSecret(); }, @@ -25,14 +26,14 @@ RocketChat.TOTP = { backupTokens.splice(usedCode, 1); // mark the code as used (remove it from the list) - RocketChat.models.Users.update2FABackupCodesByUserId(userId, backupTokens); + Users.update2FABackupCodesByUserId(userId, backupTokens); return true; } return false; } - const maxDelta = RocketChat.settings.get('Accounts_TwoFactorAuthentication_MaxDelta'); + const maxDelta = settings.get('Accounts_TwoFactorAuthentication_MaxDelta'); if (maxDelta) { const verifiedDelta = speakeasy.totp.verifyDelta({ secret, diff --git a/packages/rocketchat-2fa/server/loginHandler.js b/packages/rocketchat-2fa/server/loginHandler.js index 1060d218cb7a..31b9b37516c8 100644 --- a/packages/rocketchat-2fa/server/loginHandler.js +++ b/packages/rocketchat-2fa/server/loginHandler.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { TOTP } from './lib/totp'; Accounts.registerLoginHandler('totp', function(options) { if (!options.totp || !options.totp.code) { @@ -10,8 +12,8 @@ Accounts.registerLoginHandler('totp', function(options) { return Accounts._runLoginHandlers(this, options.totp.login); }); -RocketChat.callbacks.add('onValidateLogin', (login) => { - if (!RocketChat.settings.get('Accounts_TwoFactorAuthentication_Enabled')) { +callbacks.add('onValidateLogin', (login) => { + if (!settings.get('Accounts_TwoFactorAuthentication_Enabled')) { return; } @@ -22,7 +24,7 @@ RocketChat.callbacks.add('onValidateLogin', (login) => { throw new Meteor.Error('totp-required', 'TOTP Required'); } - const verified = RocketChat.TOTP.verify({ + const verified = TOTP.verify({ secret: login.user.services.totp.secret, token: totp.code, userId: login.user._id, diff --git a/packages/rocketchat-2fa/server/methods/disable.js b/packages/rocketchat-2fa/server/methods/disable.js index ac68d9ddc5eb..ebec075d936e 100644 --- a/packages/rocketchat-2fa/server/methods/disable.js +++ b/packages/rocketchat-2fa/server/methods/disable.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { TOTP } from '../lib/totp'; Meteor.methods({ '2fa:disable'(code) { @@ -9,7 +10,7 @@ Meteor.methods({ const user = Meteor.user(); - const verified = RocketChat.TOTP.verify({ + const verified = TOTP.verify({ secret: user.services.totp.secret, token: code, userId: Meteor.userId(), @@ -20,6 +21,6 @@ Meteor.methods({ return false; } - return RocketChat.models.Users.disable2FAByUserId(Meteor.userId()); + return Users.disable2FAByUserId(Meteor.userId()); }, }); diff --git a/packages/rocketchat-2fa/server/methods/enable.js b/packages/rocketchat-2fa/server/methods/enable.js index a2b984a4c1f1..4d73afc1ce84 100644 --- a/packages/rocketchat-2fa/server/methods/enable.js +++ b/packages/rocketchat-2fa/server/methods/enable.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { TOTP } from '../lib/totp'; Meteor.methods({ '2fa:enable'() { @@ -9,13 +10,13 @@ Meteor.methods({ const user = Meteor.user(); - const secret = RocketChat.TOTP.generateSecret(); + const secret = TOTP.generateSecret(); - RocketChat.models.Users.disable2FAAndSetTempSecretByUserId(Meteor.userId(), secret.base32); + Users.disable2FAAndSetTempSecretByUserId(Meteor.userId(), secret.base32); return { secret: secret.base32, - url: RocketChat.TOTP.generateOtpauthURL(secret, user.username), + url: TOTP.generateOtpauthURL(secret, user.username), }; }, }); diff --git a/packages/rocketchat-2fa/server/methods/regenerateCodes.js b/packages/rocketchat-2fa/server/methods/regenerateCodes.js index 750879b8c60b..330b70c4bd57 100644 --- a/packages/rocketchat-2fa/server/methods/regenerateCodes.js +++ b/packages/rocketchat-2fa/server/methods/regenerateCodes.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { TOTP } from '../lib/totp'; Meteor.methods({ '2fa:regenerateCodes'(userToken) { @@ -13,7 +14,7 @@ Meteor.methods({ throw new Meteor.Error('invalid-totp'); } - const verified = RocketChat.TOTP.verify({ + const verified = TOTP.verify({ secret: user.services.totp.secret, token: userToken, userId: Meteor.userId(), @@ -21,9 +22,9 @@ Meteor.methods({ }); if (verified) { - const { codes, hashedCodes } = RocketChat.TOTP.generateCodes(); + const { codes, hashedCodes } = TOTP.generateCodes(); - RocketChat.models.Users.update2FABackupCodesByUserId(Meteor.userId(), hashedCodes); + Users.update2FABackupCodesByUserId(Meteor.userId(), hashedCodes); return { codes }; } }, diff --git a/packages/rocketchat-2fa/server/methods/validateTempToken.js b/packages/rocketchat-2fa/server/methods/validateTempToken.js index a224f7b88b03..779b73bd73e7 100644 --- a/packages/rocketchat-2fa/server/methods/validateTempToken.js +++ b/packages/rocketchat-2fa/server/methods/validateTempToken.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { TOTP } from '../lib/totp'; Meteor.methods({ '2fa:validateTempToken'(userToken) { @@ -13,15 +14,15 @@ Meteor.methods({ throw new Meteor.Error('invalid-totp'); } - const verified = RocketChat.TOTP.verify({ + const verified = TOTP.verify({ secret: user.services.totp.tempSecret, token: userToken, }); if (verified) { - const { codes, hashedCodes } = RocketChat.TOTP.generateCodes(); + const { codes, hashedCodes } = TOTP.generateCodes(); - RocketChat.models.Users.enable2FAAndSetSecretAndCodesByUserId(Meteor.userId(), user.services.totp.tempSecret, hashedCodes); + Users.enable2FAAndSetSecretAndCodesByUserId(Meteor.userId(), user.services.totp.tempSecret, hashedCodes); return { codes }; } }, diff --git a/packages/rocketchat-2fa/server/startup/settings.js b/packages/rocketchat-2fa/server/startup/settings.js index 63d5c6e37b15..18e3550e0b31 100644 --- a/packages/rocketchat-2fa/server/startup/settings.js +++ b/packages/rocketchat-2fa/server/startup/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('Accounts', function() { +settings.addGroup('Accounts', function() { this.section('Two Factor Authentication', function() { this.add('Accounts_TwoFactorAuthentication_Enabled', true, { type: 'boolean',