From 6f749bcbab2d3a72782138ff260408e63bb17d4f Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 21 Jan 2019 18:58:42 -0200 Subject: [PATCH 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] 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 6/7] 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 7/7] 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());