snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
This commit is contained in:
31
apps/meteor/server/meteor-methods/users/blockUser.ts
Normal file
31
apps/meteor/server/meteor-methods/users/blockUser.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { blockUserMethod } from '../../lib/users/blockUser';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
blockUser({ rid, blocked }: { rid: string; blocked: string }): boolean;
|
||||
}
|
||||
}
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async blockUser({ rid, blocked }) {
|
||||
methodDeprecationLogger.method('blockUser', '9.0.0', '/v1/im.blockUser');
|
||||
check(rid, String);
|
||||
check(blocked, String);
|
||||
|
||||
const userId = Meteor.userId();
|
||||
|
||||
if (!userId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'blockUser' });
|
||||
}
|
||||
|
||||
await blockUserMethod(userId, { rid, blocked });
|
||||
|
||||
return true;
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { api } from '@rocket.chat/core-services';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { CustomUserStatus } from '@rocket.chat/models';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
deleteCustomUserStatus(userStatusID: string): Promise<boolean>;
|
||||
}
|
||||
}
|
||||
|
||||
export const deleteCustomUserStatus = async (userId: string, userStatusID: string): Promise<boolean> => {
|
||||
if (!(await hasPermissionAsync(userId, 'manage-user-status'))) {
|
||||
throw new Meteor.Error('not_authorized');
|
||||
}
|
||||
|
||||
const userStatus = await CustomUserStatus.findOneAndDeleteById(userStatusID);
|
||||
if (userStatus == null) {
|
||||
throw new Meteor.Error('Custom_User_Status_Error_Invalid_User_Status', 'Invalid user status', { method: 'deleteCustomUserStatus' });
|
||||
}
|
||||
|
||||
void api.broadcast('user.deleteCustomStatus', userStatus);
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async deleteCustomUserStatus(userStatusID) {
|
||||
methodDeprecationLogger.method('deleteCustomUserStatus', '9.0.0', '/v1/custom-user-status.delete');
|
||||
if (!this.userId) {
|
||||
throw new Meteor.Error('not_authorized');
|
||||
}
|
||||
|
||||
return deleteCustomUserStatus(this.userId, userStatusID);
|
||||
},
|
||||
});
|
||||
68
apps/meteor/server/meteor-methods/users/deleteUser.ts
Normal file
68
apps/meteor/server/meteor-methods/users/deleteUser.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import type { IUser } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Users } from '@rocket.chat/models';
|
||||
import { check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { deleteUser } from '../../lib/users/deleteUser';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
deleteUser(userId: IUser['_id'], confirmRelinquish?: boolean): boolean;
|
||||
}
|
||||
}
|
||||
|
||||
export const executeDeleteUser = async (fromUserId: IUser['_id'], userId: IUser['_id'], confirmRelinquish = false): Promise<boolean> => {
|
||||
const user = await Users.findOneById(userId);
|
||||
if (!user) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user to delete', {
|
||||
method: 'deleteUser',
|
||||
});
|
||||
}
|
||||
|
||||
if (user.type === 'app') {
|
||||
throw new Meteor.Error('error-cannot-delete-app-user', 'Deleting app user is not allowed', {
|
||||
method: 'deleteUser',
|
||||
});
|
||||
}
|
||||
|
||||
const adminCount = await Users.countDocuments({ roles: 'admin' });
|
||||
|
||||
const userIsAdmin = user.roles?.indexOf('admin') > -1;
|
||||
|
||||
if (adminCount === 1 && userIsAdmin) {
|
||||
throw new Meteor.Error('error-action-not-allowed', 'Leaving the app without admins is not allowed', {
|
||||
method: 'deleteUser',
|
||||
action: 'Remove_last_admin',
|
||||
});
|
||||
}
|
||||
|
||||
await deleteUser(userId, confirmRelinquish, fromUserId);
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async deleteUser(userId, confirmRelinquish = false) {
|
||||
methodDeprecationLogger.method('deleteUser', '9.0.0', '/v1/users.delete');
|
||||
check(userId, String);
|
||||
|
||||
const uid = Meteor.userId();
|
||||
if (!uid) {
|
||||
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
|
||||
method: 'deleteUser',
|
||||
});
|
||||
}
|
||||
|
||||
if ((await hasPermissionAsync(uid, 'delete-user')) !== true) {
|
||||
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
|
||||
method: 'deleteUser',
|
||||
});
|
||||
}
|
||||
|
||||
return executeDeleteUser(uid, userId, confirmRelinquish);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Apps, AppEvents } from '@rocket.chat/apps';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Users } from '@rocket.chat/models';
|
||||
import { SHA256 } from '@rocket.chat/sha256';
|
||||
import { Accounts } from 'meteor/accounts-base';
|
||||
import { check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { trim } from '../../../lib/utils/stringUtils';
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { deleteUser } from '../../lib/users/deleteUser';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
deleteUserOwnAccount(password: string, confirmRelinquish?: boolean): Promise<boolean>;
|
||||
}
|
||||
}
|
||||
|
||||
export const deleteUserOwnAccount = async (fromUserId: string, password: string, confirmRelinquish = false): Promise<boolean> => {
|
||||
if (!settings.get('Accounts_AllowDeleteOwnAccount')) {
|
||||
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
|
||||
method: 'deleteUserOwnAccount',
|
||||
});
|
||||
}
|
||||
|
||||
if (!fromUserId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'deleteUserOwnAccount',
|
||||
});
|
||||
}
|
||||
|
||||
const user = await Users.findOneById(fromUserId);
|
||||
if (!user) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'deleteUserOwnAccount',
|
||||
});
|
||||
}
|
||||
|
||||
if (user.services?.password && trim(user.services.password.bcrypt)) {
|
||||
const result = await Accounts._checkPasswordAsync(user as Meteor.User, {
|
||||
digest: password.toLowerCase(),
|
||||
algorithm: 'sha-256',
|
||||
});
|
||||
if (result.error) {
|
||||
throw new Meteor.Error('error-invalid-password', 'Invalid password', {
|
||||
method: 'deleteUserOwnAccount',
|
||||
});
|
||||
}
|
||||
} else if (!user.username || SHA256(user.username) !== password.trim()) {
|
||||
throw new Meteor.Error('error-invalid-username', 'Invalid username', {
|
||||
method: 'deleteUserOwnAccount',
|
||||
});
|
||||
}
|
||||
|
||||
await deleteUser(fromUserId, confirmRelinquish);
|
||||
|
||||
// App IPostUserDeleted event hook
|
||||
await Apps.self?.triggerEvent(AppEvents.IPostUserDeleted, { user });
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async deleteUserOwnAccount(password, confirmRelinquish) {
|
||||
methodDeprecationLogger.method('deleteUserOwnAccount', '9.0.0', '/v1/users.deleteOwnAccount');
|
||||
check(password, String);
|
||||
|
||||
const uid = Meteor.userId();
|
||||
if (!uid) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'deleteUserOwnAccount',
|
||||
});
|
||||
}
|
||||
|
||||
return deleteUserOwnAccount(uid, password, confirmRelinquish);
|
||||
},
|
||||
});
|
||||
27
apps/meteor/server/meteor-methods/users/getUserStatusText.ts
Normal file
27
apps/meteor/server/meteor-methods/users/getUserStatusText.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { getUsersHiddenFrom } from '../../lib/statusVisibility/hiddenUsers';
|
||||
import { getStatusText } from '../../lib/users/getStatusText';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
getUserStatusText(userId: string): Promise<string | undefined>;
|
||||
}
|
||||
}
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async getUserStatusText(userId) {
|
||||
methodDeprecationLogger.method('getUserStatusText', '9.0.0', '/v1/users.presence');
|
||||
const currentUserId = Meteor.userId();
|
||||
if (!currentUserId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getUserStatusText' });
|
||||
}
|
||||
|
||||
const hidden = await getUsersHiddenFrom(currentUserId);
|
||||
|
||||
return hidden?.has(userId) ? undefined : getStatusText(userId);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { generateUsernameSuggestion } from '../../lib/users/getUsernameSuggestion';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
getUsernameSuggestion(): Promise<string | undefined>;
|
||||
}
|
||||
}
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async getUsernameSuggestion() {
|
||||
methodDeprecationLogger.method('getUsernameSuggestion', '9.0.0', '/v1/users.getUsernameSuggestion');
|
||||
const user = await Meteor.userAsync();
|
||||
|
||||
if (!user) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'getUsernameSuggestion',
|
||||
});
|
||||
}
|
||||
|
||||
return generateUsernameSuggestion(user);
|
||||
},
|
||||
});
|
||||
72
apps/meteor/server/meteor-methods/users/getUsersOfRoom.ts
Normal file
72
apps/meteor/server/meteor-methods/users/getUsersOfRoom.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import type { IRoom, IUser } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Subscriptions, Rooms } from '@rocket.chat/models';
|
||||
import { check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { canAccessRoomAsync, roomAccessAttributes } from '../../lib/authorization';
|
||||
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
|
||||
import { findUsersOfRoom } from '../../lib/findUsersOfRoom';
|
||||
import { getUsersHiddenFrom, redactHiddenUsers } from '../../lib/statusVisibility/hiddenUsers';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
getUsersOfRoom(
|
||||
rid: IRoom['_id'],
|
||||
showAll?: boolean,
|
||||
options?: { limit?: number; skip?: number },
|
||||
filter?: string,
|
||||
): {
|
||||
total: number;
|
||||
records: IUser[];
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async getUsersOfRoom(rid, showAll, { limit, skip } = {}, filter) {
|
||||
if (!rid) {
|
||||
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'getUsersOfRoom' });
|
||||
}
|
||||
|
||||
check(rid, String);
|
||||
|
||||
const userId = Meteor.userId();
|
||||
if (!userId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getUsersOfRoom' });
|
||||
}
|
||||
|
||||
const room = await Rooms.findOneById(rid, { projection: { ...roomAccessAttributes, broadcast: 1 } });
|
||||
if (!room) {
|
||||
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'getUsersOfRoom' });
|
||||
}
|
||||
|
||||
if (!(await canAccessRoomAsync(room, { _id: userId }))) {
|
||||
throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'getUsersOfRoom' });
|
||||
}
|
||||
|
||||
if (room.broadcast && !(await hasPermissionAsync(userId, 'view-broadcast-member-list', rid))) {
|
||||
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'getUsersOfRoom' });
|
||||
}
|
||||
|
||||
// TODO this is currently counting deactivated users
|
||||
const total = await Subscriptions.countByRoomIdWhenUsernameExists(rid);
|
||||
|
||||
const hidden = await getUsersHiddenFrom(userId);
|
||||
|
||||
const { cursor } = await findUsersOfRoom({
|
||||
rid,
|
||||
...(!showAll && { status: 'not-offline' as const }),
|
||||
hidden,
|
||||
limit,
|
||||
skip,
|
||||
filter,
|
||||
});
|
||||
|
||||
return {
|
||||
total,
|
||||
records: redactHiddenUsers(await cursor.toArray(), hidden),
|
||||
};
|
||||
},
|
||||
});
|
||||
62
apps/meteor/server/meteor-methods/users/ignoreUser.ts
Normal file
62
apps/meteor/server/meteor-methods/users/ignoreUser.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Subscriptions } from '@rocket.chat/models';
|
||||
import { check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { notifyOnSubscriptionChangedById } from '../../lib/notifyListener';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
ignoreUser(params: { rid: string; userId: string; ignore?: boolean }): boolean;
|
||||
}
|
||||
}
|
||||
|
||||
export const ignoreUser = async (
|
||||
fromUserId: string,
|
||||
{ rid, userId: ignoredUser, ignore }: { rid: string; userId: string; ignore?: boolean },
|
||||
): Promise<boolean> => {
|
||||
const [subscription, subscriptionIgnoredUser] = await Promise.all([
|
||||
Subscriptions.findOneByRoomIdAndUserId(rid, fromUserId),
|
||||
Subscriptions.findOneByRoomIdAndUserId(rid, ignoredUser),
|
||||
]);
|
||||
|
||||
if (!subscription) {
|
||||
throw new Meteor.Error('error-invalid-subscription', 'Invalid subscription', {
|
||||
method: 'ignoreUser',
|
||||
});
|
||||
}
|
||||
|
||||
if (!subscriptionIgnoredUser) {
|
||||
throw new Meteor.Error('error-invalid-subscription', 'Invalid subscription', {
|
||||
method: 'ignoreUser',
|
||||
});
|
||||
}
|
||||
|
||||
const result = await Subscriptions.ignoreUser({ _id: subscription._id, ignoredUser, ignore });
|
||||
|
||||
if (result.modifiedCount) {
|
||||
void notifyOnSubscriptionChangedById(subscription._id);
|
||||
}
|
||||
|
||||
return !!result;
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async ignoreUser({ rid, userId: ignoredUser, ignore = true }) {
|
||||
methodDeprecationLogger.method('ignoreUser', '9.0.0', '/v1/chat.ignoreUser');
|
||||
check(ignoredUser, String);
|
||||
check(rid, String);
|
||||
check(ignore, Boolean);
|
||||
|
||||
const userId = Meteor.userId();
|
||||
if (!userId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'ignoreUser',
|
||||
});
|
||||
}
|
||||
|
||||
return ignoreUser(userId, { rid, userId: ignoredUser, ignore });
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { api } from '@rocket.chat/core-services';
|
||||
import type { ICustomUserStatus } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import type { InsertionModel } from '@rocket.chat/model-typings';
|
||||
import { CustomUserStatus } from '@rocket.chat/models';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { trim } from '../../../lib/utils/stringUtils';
|
||||
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
|
||||
type InsertOrUpdateUserStatus = {
|
||||
_id?: string;
|
||||
name: string;
|
||||
statusType: string;
|
||||
status?: string;
|
||||
emoji?: string;
|
||||
message?: string;
|
||||
order?: number;
|
||||
previousName?: string;
|
||||
previousStatusType?: string;
|
||||
};
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
insertOrUpdateUserStatus(userStatusData: InsertOrUpdateUserStatus): string | boolean;
|
||||
}
|
||||
}
|
||||
|
||||
export const insertOrUpdateUserStatus = async (userId: string, userStatusData: InsertOrUpdateUserStatus): Promise<string | boolean> => {
|
||||
if (!(await hasPermissionAsync(userId, 'manage-user-status'))) {
|
||||
throw new Meteor.Error('not_authorized');
|
||||
}
|
||||
|
||||
if (!trim(userStatusData.name)) {
|
||||
throw new Meteor.Error('error-the-field-is-required', 'The field Name is required', {
|
||||
method: 'insertOrUpdateUserStatus',
|
||||
field: 'Name',
|
||||
});
|
||||
}
|
||||
|
||||
// allow all characters except >, <, &, ", '
|
||||
// more practical than allowing specific sets of characters; also allows foreign languages
|
||||
const nameValidation = /[><&"']/;
|
||||
|
||||
if (nameValidation.test(userStatusData.name)) {
|
||||
throw new Meteor.Error('error-input-is-not-a-valid-field', `${userStatusData.name} is not a valid name`, {
|
||||
method: 'insertOrUpdateUserStatus',
|
||||
input: userStatusData.name,
|
||||
field: 'Name',
|
||||
});
|
||||
}
|
||||
|
||||
const conflictingUserStatus = userStatusData._id
|
||||
? await CustomUserStatus.findOneByNameExceptId(userStatusData.name, userStatusData._id, { projection: { _id: 1 } })
|
||||
: await CustomUserStatus.findOneByName(userStatusData.name, { projection: { _id: 1 } });
|
||||
|
||||
if (conflictingUserStatus) {
|
||||
throw new Meteor.Error('Custom_User_Status_Error_Name_Already_In_Use', 'The custom user status name is already in use', {
|
||||
method: 'insertOrUpdateUserStatus',
|
||||
});
|
||||
}
|
||||
|
||||
const validStatusTypes = ['online', 'away', 'busy', 'offline'];
|
||||
if (userStatusData.statusType && validStatusTypes.indexOf(userStatusData.statusType) < 0) {
|
||||
throw new Meteor.Error('error-input-is-not-a-valid-field', `${userStatusData.statusType} is not a valid status type`, {
|
||||
method: 'insertOrUpdateUserStatus',
|
||||
input: userStatusData.statusType,
|
||||
field: 'StatusType',
|
||||
});
|
||||
}
|
||||
|
||||
if (!userStatusData._id) {
|
||||
// insert user status
|
||||
const createUserStatus: InsertionModel<ICustomUserStatus> = {
|
||||
name: userStatusData.name,
|
||||
statusType: userStatusData.statusType,
|
||||
};
|
||||
|
||||
const _id = (await CustomUserStatus.create(createUserStatus)).insertedId;
|
||||
|
||||
void api.broadcast('user.updateCustomStatus', { ...createUserStatus, _id });
|
||||
|
||||
return _id;
|
||||
}
|
||||
|
||||
// update User status
|
||||
if (userStatusData.name !== userStatusData.previousName) {
|
||||
await CustomUserStatus.setName(userStatusData._id, userStatusData.name);
|
||||
}
|
||||
|
||||
if (userStatusData.statusType !== userStatusData.previousStatusType) {
|
||||
await CustomUserStatus.setStatusType(userStatusData._id, userStatusData.statusType);
|
||||
}
|
||||
|
||||
void api.broadcast('user.updateCustomStatus', { ...userStatusData, _id: userStatusData._id });
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async insertOrUpdateUserStatus(userStatusData) {
|
||||
methodDeprecationLogger.method('insertOrUpdateUserStatus', '9.0.0', ['/v1/custom-user-status.create', '/v1/custom-user-status.update']);
|
||||
if (!this.userId) {
|
||||
throw new Meteor.Error('not_authorized');
|
||||
}
|
||||
|
||||
return insertOrUpdateUserStatus(this.userId, userStatusData);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ICustomUserStatus } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { CustomUserStatus } from '@rocket.chat/models';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
listCustomUserStatus(): ICustomUserStatus[];
|
||||
}
|
||||
}
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async listCustomUserStatus() {
|
||||
const currentUserId = Meteor.userId();
|
||||
if (!currentUserId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'listCustomUserStatus',
|
||||
});
|
||||
}
|
||||
|
||||
return CustomUserStatus.find({}).toArray();
|
||||
},
|
||||
});
|
||||
167
apps/meteor/server/meteor-methods/users/registerUser.ts
Normal file
167
apps/meteor/server/meteor-methods/users/registerUser.ts
Normal file
@@ -0,0 +1,167 @@
|
||||
import type { IUser } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Users } from '@rocket.chat/models';
|
||||
import { Accounts } from 'meteor/accounts-base';
|
||||
import { Match, check } from 'meteor/check';
|
||||
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { trim } from '../../../lib/utils/stringUtils';
|
||||
import { RateLimiterClass as RateLimiter } from '../../lib/RateLimiter';
|
||||
import { passwordPolicy } from '../../lib/auth/passwordPolicy';
|
||||
import { validateInviteToken } from '../../lib/rooms/invites/validateInviteToken';
|
||||
import { validateEmailDomain } from '../../lib/validateEmailDomain';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
registerUser(
|
||||
formData:
|
||||
{ email: string; pass: string; username: IUser['username']; name?: string; secretURL?: string; reason?: string } | { email?: null },
|
||||
):
|
||||
| {
|
||||
token: string;
|
||||
when: Date;
|
||||
}
|
||||
| string;
|
||||
}
|
||||
}
|
||||
|
||||
export const registerUser = async (
|
||||
formData:
|
||||
{ email: string; pass: string; username: IUser['username']; name?: string; secretURL?: string; reason?: string } | { email?: null },
|
||||
): Promise<
|
||||
| {
|
||||
token: string;
|
||||
when: Date;
|
||||
}
|
||||
| string
|
||||
> => {
|
||||
const AllowAnonymousRead = settings.get<boolean>('Accounts_AllowAnonymousRead');
|
||||
const AllowAnonymousWrite = settings.get<boolean>('Accounts_AllowAnonymousWrite');
|
||||
const manuallyApproveNewUsers = settings.get<boolean>('Accounts_ManuallyApproveNewUsers');
|
||||
if (AllowAnonymousRead === true && AllowAnonymousWrite === true && !formData.email) {
|
||||
const userId = await Accounts.insertUserDoc(
|
||||
{},
|
||||
{
|
||||
globalRoles: ['anonymous'],
|
||||
active: true,
|
||||
},
|
||||
);
|
||||
|
||||
const stampedLoginToken = await Accounts._generateStampedLoginToken();
|
||||
|
||||
await Accounts._insertLoginToken(userId, stampedLoginToken);
|
||||
return stampedLoginToken;
|
||||
}
|
||||
check(
|
||||
formData,
|
||||
Match.ObjectIncluding({
|
||||
email: String,
|
||||
pass: String,
|
||||
name: String,
|
||||
secretURL: Match.Optional(String),
|
||||
reason: Match.Optional(String),
|
||||
}),
|
||||
);
|
||||
|
||||
if (settings.get('Accounts_RegistrationForm') === 'Disabled') {
|
||||
throw new Meteor.Error('error-user-registration-disabled', 'User registration is disabled', {
|
||||
method: 'registerUser',
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
settings.get('Accounts_RegistrationForm') === 'Secret URL' &&
|
||||
(!formData.secretURL || formData.secretURL !== settings.get('Accounts_RegistrationForm_SecretURL'))
|
||||
) {
|
||||
if (!formData.secretURL) {
|
||||
throw new Meteor.Error('error-user-registration-secret', 'User registration is only allowed via Secret URL', {
|
||||
method: 'registerUser',
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await validateInviteToken(formData.secretURL);
|
||||
} catch (e) {
|
||||
throw new Meteor.Error('error-user-registration-secret', 'User registration is only allowed via Secret URL', {
|
||||
method: 'registerUser',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
passwordPolicy.validate(formData.pass);
|
||||
|
||||
await validateEmailDomain(formData.email);
|
||||
|
||||
const userData = {
|
||||
email: trim(formData.email.toLowerCase()),
|
||||
password: formData.pass,
|
||||
...(formData.name?.trim() && { name: formData.name?.trim() }),
|
||||
reason: formData.reason,
|
||||
};
|
||||
|
||||
let userId;
|
||||
try {
|
||||
userId = await Accounts.createUserAsync(userData);
|
||||
} catch (e) {
|
||||
if (e instanceof Meteor.Error) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (e instanceof Error) {
|
||||
throw new Meteor.Error(e.message);
|
||||
}
|
||||
|
||||
throw new Meteor.Error(String(e));
|
||||
}
|
||||
|
||||
const reason = trim(formData.reason);
|
||||
if (manuallyApproveNewUsers && reason) {
|
||||
await Users.setReason(userId, reason);
|
||||
}
|
||||
|
||||
try {
|
||||
Accounts.sendVerificationEmail(userId, userData.email);
|
||||
} catch (error) {
|
||||
// throw new Meteor.Error 'error-email-send-failed', 'Error trying to send email: ' + error.message, { method: 'registerUser', message: error.message }
|
||||
}
|
||||
|
||||
return userId;
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async registerUser(formData) {
|
||||
return registerUser(formData);
|
||||
},
|
||||
});
|
||||
|
||||
let registerUserRuleId = RateLimiter.limitMethod(
|
||||
'registerUser',
|
||||
settings.get('Rate_Limiter_Limit_RegisterUser'),
|
||||
settings.get('API_Enable_Rate_Limiter_Limit_Time_Default'),
|
||||
{
|
||||
userId() {
|
||||
return true;
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
settings.watch('Rate_Limiter_Limit_RegisterUser', (value) => {
|
||||
// When running on testMode, there's no rate limiting added, so this function throws an error
|
||||
if (process.env.TEST_MODE === 'true' || process.env.TEST_MODE === 'api') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!registerUserRuleId) {
|
||||
throw new Error('Rate limiter rule for "registerUser" not found');
|
||||
}
|
||||
// remove old DDP rate limiter rule and create a new one with the updated setting value
|
||||
DDPRateLimiter.removeRule(registerUserRuleId);
|
||||
registerUserRuleId = RateLimiter.limitMethod('registerUser', value, settings.get('API_Enable_Rate_Limiter_Limit_Time_Default'), {
|
||||
userId() {
|
||||
return true;
|
||||
},
|
||||
});
|
||||
});
|
||||
75
apps/meteor/server/meteor-methods/users/resetAvatar.ts
Normal file
75
apps/meteor/server/meteor-methods/users/resetAvatar.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { Upload } from '@rocket.chat/core-services';
|
||||
import type { IUser } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Users } from '@rocket.chat/models';
|
||||
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
resetAvatar(userId: IUser['_id']): void;
|
||||
}
|
||||
}
|
||||
|
||||
export const resetAvatar = async (fromUserId: IUser['_id'], userId: IUser['_id']): Promise<void> => {
|
||||
const canEditOtherUserAvatar = await hasPermissionAsync(fromUserId, 'edit-other-user-avatar');
|
||||
|
||||
if (!settings.get('Accounts_AllowUserAvatarChange') && !canEditOtherUserAvatar) {
|
||||
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
|
||||
method: 'resetAvatar',
|
||||
});
|
||||
}
|
||||
|
||||
let user;
|
||||
|
||||
if (userId !== fromUserId) {
|
||||
if (!canEditOtherUserAvatar) {
|
||||
throw new Meteor.Error('error-unauthorized', 'Unauthorized', {
|
||||
method: 'resetAvatar',
|
||||
});
|
||||
}
|
||||
|
||||
user = await Users.findOneById(userId, { projection: { _id: 1, username: 1 } });
|
||||
} else {
|
||||
user = await Users.findOneById(fromUserId, { projection: { _id: 1, username: 1 } });
|
||||
}
|
||||
|
||||
if (!user?.username) {
|
||||
throw new Meteor.Error('error-invalid-desired-user', 'Invalid desired user', {
|
||||
method: 'resetAvatar',
|
||||
});
|
||||
}
|
||||
|
||||
await Upload.resetUserAvatar(user);
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async resetAvatar(userId) {
|
||||
methodDeprecationLogger.method('resetAvatar', '9.0.0', '/v1/users.resetAvatar');
|
||||
const uid = Meteor.userId();
|
||||
if (!uid) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'resetAvatar',
|
||||
});
|
||||
}
|
||||
|
||||
return resetAvatar(uid, userId);
|
||||
},
|
||||
});
|
||||
|
||||
DDPRateLimiter.addRule(
|
||||
{
|
||||
type: 'method',
|
||||
name: 'resetAvatar',
|
||||
userId() {
|
||||
return true;
|
||||
},
|
||||
},
|
||||
1,
|
||||
60000,
|
||||
);
|
||||
@@ -0,0 +1,172 @@
|
||||
import type { ISubscription } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Subscriptions } from '@rocket.chat/models';
|
||||
import { check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { notifyOnSubscriptionChangedById } from '../../lib/notifyListener';
|
||||
import { getUserNotificationPreference } from '../../lib/utils/getUserNotificationPreference';
|
||||
|
||||
const saveAudioNotificationValue = (subId: ISubscription['_id'], value: string) =>
|
||||
value === 'default' ? Subscriptions.clearAudioNotificationValueById(subId) : Subscriptions.updateAudioNotificationValueById(subId, value);
|
||||
|
||||
export type NotificationFieldType =
|
||||
| 'desktopNotifications'
|
||||
| 'mobilePushNotifications'
|
||||
| 'emailNotifications'
|
||||
| 'unreadAlert'
|
||||
| 'disableNotifications'
|
||||
| 'hideUnreadStatus'
|
||||
| 'hideMentionStatus'
|
||||
| 'muteGroupMentions'
|
||||
| 'audioNotificationValue';
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
saveNotificationSettings(roomId: string, field: NotificationFieldType, value: string): boolean;
|
||||
saveAudioNotificationValue(subId: string, value: string): boolean;
|
||||
}
|
||||
}
|
||||
|
||||
export const saveNotificationSettingsMethod = async (
|
||||
userId: string,
|
||||
roomId: string,
|
||||
field: NotificationFieldType,
|
||||
value: string,
|
||||
): Promise<boolean> => {
|
||||
const getNotificationPrefValue = async (field: string, value: unknown) => {
|
||||
if (value === 'default') {
|
||||
if (!userId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'saveNotificationSettings',
|
||||
});
|
||||
}
|
||||
|
||||
const userPref = await getUserNotificationPreference(userId, field);
|
||||
return userPref?.origin === 'server' ? null : userPref;
|
||||
}
|
||||
return { value, origin: 'subscription' };
|
||||
};
|
||||
|
||||
const notifications = {
|
||||
desktopNotifications: {
|
||||
updateMethod: async (subscription: ISubscription, value: unknown) =>
|
||||
Subscriptions.updateNotificationsPrefById(
|
||||
subscription._id,
|
||||
await getNotificationPrefValue('desktop', value),
|
||||
'desktopNotifications',
|
||||
'desktopPrefOrigin',
|
||||
),
|
||||
},
|
||||
mobilePushNotifications: {
|
||||
updateMethod: async (subscription: ISubscription, value: unknown) =>
|
||||
Subscriptions.updateNotificationsPrefById(
|
||||
subscription._id,
|
||||
await getNotificationPrefValue('mobile', value),
|
||||
'mobilePushNotifications',
|
||||
'mobilePrefOrigin',
|
||||
),
|
||||
},
|
||||
emailNotifications: {
|
||||
updateMethod: async (subscription: ISubscription, value: unknown) =>
|
||||
Subscriptions.updateNotificationsPrefById(
|
||||
subscription._id,
|
||||
await getNotificationPrefValue('email', value),
|
||||
'emailNotifications',
|
||||
'emailPrefOrigin',
|
||||
),
|
||||
},
|
||||
unreadAlert: {
|
||||
// @ts-expect-error - Check types of model. The way the method is defined makes difficult to type it, check proper types for `value`
|
||||
updateMethod: (subscription: ISubscription, value: string) => Subscriptions.updateUnreadAlertById(subscription._id, value),
|
||||
},
|
||||
disableNotifications: {
|
||||
updateMethod: (subscription: ISubscription, value: unknown) =>
|
||||
Subscriptions.updateDisableNotificationsById(subscription._id, value === '1'),
|
||||
},
|
||||
hideUnreadStatus: {
|
||||
updateMethod: (subscription: ISubscription, value: string) =>
|
||||
Subscriptions.updateHideUnreadStatusById(subscription._id, value === '1'),
|
||||
},
|
||||
hideMentionStatus: {
|
||||
updateMethod: (subscription: ISubscription, value: unknown) =>
|
||||
Subscriptions.updateHideMentionStatusById(subscription._id, value === '1'),
|
||||
},
|
||||
muteGroupMentions: {
|
||||
updateMethod: (subscription: ISubscription, value: unknown) => Subscriptions.updateMuteGroupMentions(subscription._id, value === '1'),
|
||||
},
|
||||
audioNotificationValue: {
|
||||
updateMethod: (subscription: ISubscription, value: string) => saveAudioNotificationValue(subscription._id, value),
|
||||
},
|
||||
};
|
||||
const isInvalidNotification = !Object.keys(notifications).includes(field);
|
||||
const basicValuesForNotifications = ['all', 'mentions', 'nothing', 'default'];
|
||||
const fieldsMustHaveBasicValues = ['emailNotifications', 'mobilePushNotifications', 'desktopNotifications'];
|
||||
|
||||
if (isInvalidNotification) {
|
||||
throw new Meteor.Error('error-invalid-settings', 'Invalid settings field', {
|
||||
method: 'saveNotificationSettings',
|
||||
});
|
||||
}
|
||||
|
||||
if (fieldsMustHaveBasicValues.includes(field) && !basicValuesForNotifications.includes(value)) {
|
||||
throw new Meteor.Error('error-invalid-settings', 'Invalid settings value', {
|
||||
method: 'saveNotificationSettings',
|
||||
});
|
||||
}
|
||||
|
||||
const subscription = await Subscriptions.findOneByRoomIdAndUserId(roomId, userId);
|
||||
if (!subscription) {
|
||||
throw new Meteor.Error('error-invalid-subscription', 'Invalid subscription', {
|
||||
method: 'saveNotificationSettings',
|
||||
});
|
||||
}
|
||||
|
||||
const updateResponse = await notifications[field].updateMethod(subscription, value);
|
||||
if (updateResponse.modifiedCount) {
|
||||
void notifyOnSubscriptionChangedById(subscription._id);
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async saveNotificationSettings(roomId, field, value) {
|
||||
methodDeprecationLogger.method('saveNotificationSettings', '9.0.0', '/v1/rooms.saveNotification');
|
||||
const userId = Meteor.userId();
|
||||
if (!userId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'saveNotificationSettings',
|
||||
});
|
||||
}
|
||||
check(roomId, String);
|
||||
check(field, String);
|
||||
check(value, String);
|
||||
|
||||
return saveNotificationSettingsMethod(userId, roomId, field, value);
|
||||
},
|
||||
|
||||
async saveAudioNotificationValue(rid, value) {
|
||||
const userId = Meteor.userId();
|
||||
if (!userId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'saveAudioNotificationValue',
|
||||
});
|
||||
}
|
||||
|
||||
const subscription = await Subscriptions.findOneByRoomIdAndUserId(rid, userId);
|
||||
if (!subscription) {
|
||||
throw new Meteor.Error('error-invalid-subscription', 'Invalid subscription', {
|
||||
method: 'saveAudioNotificationValue',
|
||||
});
|
||||
}
|
||||
|
||||
const saveAudioNotificationResponse = await saveAudioNotificationValue(subscription._id, value);
|
||||
if (saveAudioNotificationResponse.modifiedCount) {
|
||||
void notifyOnSubscriptionChangedById(subscription._id);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
});
|
||||
297
apps/meteor/server/meteor-methods/users/saveUserPreferences.ts
Normal file
297
apps/meteor/server/meteor-methods/users/saveUserPreferences.ts
Normal file
@@ -0,0 +1,297 @@
|
||||
import { StatusVisibility } from '@rocket.chat/core-services';
|
||||
import type { ISidebarCategory, ISubscription, ThemePreference } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Subscriptions, Users } from '@rocket.chat/models';
|
||||
import type { FontSize } from '@rocket.chat/rest-typings';
|
||||
import { Match, check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import {
|
||||
notifyOnSubscriptionChangedByAutoTranslateAndUserId,
|
||||
notifyOnSubscriptionChangedByUserId,
|
||||
notifyOnSubscriptionChangedByUserPreferences,
|
||||
notifyOnUserChange,
|
||||
} from '../../lib/notifyListener';
|
||||
import { resolveUsersByUsernames } from '../../lib/statusVisibility/resolveUsers';
|
||||
import { settings as rcSettings } from '../../settings';
|
||||
|
||||
type UserPreferences = {
|
||||
language: string;
|
||||
newRoomNotification: string;
|
||||
newMessageNotification: string;
|
||||
clockMode: number;
|
||||
useEmojis: boolean;
|
||||
convertAsciiEmoji: boolean;
|
||||
saveMobileBandwidth: boolean;
|
||||
collapseMediaByDefault: boolean;
|
||||
autoImageLoad: boolean;
|
||||
emailNotificationMode: string;
|
||||
unreadAlert: boolean;
|
||||
masterVolume: number;
|
||||
notificationsSoundVolume: number;
|
||||
voipRingerVolume: number;
|
||||
desktopNotifications: string;
|
||||
pushNotifications: string;
|
||||
enableAutoAway: boolean;
|
||||
highlights: string[];
|
||||
hideUsernames: boolean;
|
||||
hideRoles: boolean;
|
||||
displayAvatars: boolean;
|
||||
hideFlexTab: boolean;
|
||||
sendOnEnter: string;
|
||||
idleTimeLimit: number;
|
||||
sidebarShowFavorites: boolean;
|
||||
sidebarShowUnread: boolean;
|
||||
sidebarSortby: string;
|
||||
sidebarViewMode: string;
|
||||
sidebarDisplayAvatar: boolean;
|
||||
sidebarGroupByType: boolean;
|
||||
sidebarCategories: ISidebarCategory[];
|
||||
muteFocusedConversations: boolean;
|
||||
dontAskAgainList: { action: string; label: string }[];
|
||||
themeAppearence: ThemePreference;
|
||||
fontSize?: FontSize;
|
||||
receiveLoginDetectionEmail: boolean;
|
||||
notifyCalendarEvents: boolean;
|
||||
enableMobileRinging: boolean;
|
||||
mentionsWithSymbol?: boolean;
|
||||
utcOffset?: number;
|
||||
statusVisibilityDenied?: string[];
|
||||
};
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
saveUserPreferences(preferences: Partial<UserPreferences>): boolean;
|
||||
}
|
||||
}
|
||||
|
||||
async function updateNotificationPreferences(
|
||||
userId: ISubscription['u']['_id'],
|
||||
setting: keyof ISubscription,
|
||||
newValue: string,
|
||||
oldValue: string,
|
||||
preferenceType: keyof ISubscription,
|
||||
) {
|
||||
if (newValue === oldValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (newValue === 'default') {
|
||||
const clearNotificationResponse = await Subscriptions.clearNotificationUserPreferences(userId, setting, preferenceType);
|
||||
if (clearNotificationResponse.modifiedCount) {
|
||||
void notifyOnSubscriptionChangedByUserPreferences(userId, preferenceType, 'user');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const updateNotificationResponse = await Subscriptions.updateNotificationUserPreferences(userId, newValue, setting, preferenceType);
|
||||
if (updateNotificationResponse.modifiedCount) {
|
||||
void notifyOnSubscriptionChangedByUserPreferences(userId, preferenceType, 'subscription');
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_CATEGORY_NAME_LENGTH = 30;
|
||||
|
||||
export const validateSidebarCategories = (categories: ISidebarCategory[]): void => {
|
||||
for (const category of categories) {
|
||||
if (category.default) {
|
||||
continue;
|
||||
}
|
||||
const trimmed = category.name.trim();
|
||||
if (!trimmed) {
|
||||
throw new Meteor.Error('error-invalid-param', 'sidebarCategories contains a blank category name');
|
||||
}
|
||||
if (trimmed.length > MAX_CATEGORY_NAME_LENGTH) {
|
||||
throw new Meteor.Error('error-invalid-param', 'sidebarCategories category name exceeds maximum length');
|
||||
}
|
||||
}
|
||||
|
||||
const hasDuplicates = (values: string[]): boolean => new Set(values).size !== values.length;
|
||||
if (hasDuplicates(categories.map((category) => category._id))) {
|
||||
throw new Meteor.Error('error-invalid-param', 'sidebarCategories contains duplicate category _id values');
|
||||
}
|
||||
};
|
||||
|
||||
export const saveUserPreferences = async (settings: Partial<UserPreferences>, userId: string): Promise<void> => {
|
||||
const keys = {
|
||||
language: Match.Optional(String),
|
||||
newRoomNotification: Match.Optional(String),
|
||||
newMessageNotification: Match.Optional(String),
|
||||
clockMode: Match.Optional(Number),
|
||||
useEmojis: Match.Optional(Boolean),
|
||||
convertAsciiEmoji: Match.Optional(Boolean),
|
||||
saveMobileBandwidth: Match.Optional(Boolean),
|
||||
collapseMediaByDefault: Match.Optional(Boolean),
|
||||
autoImageLoad: Match.Optional(Boolean),
|
||||
emailNotificationMode: Match.Optional(String),
|
||||
unreadAlert: Match.Optional(Boolean),
|
||||
masterVolume: Match.Optional(Number),
|
||||
notificationsSoundVolume: Match.Optional(Number),
|
||||
voipRingerVolume: Match.Optional(Number),
|
||||
desktopNotifications: Match.Optional(String),
|
||||
pushNotifications: Match.Optional(String),
|
||||
enableAutoAway: Match.Optional(Boolean),
|
||||
highlights: Match.Optional([String]),
|
||||
hideUsernames: Match.Optional(Boolean),
|
||||
hideRoles: Match.Optional(Boolean),
|
||||
displayAvatars: Match.Optional(Boolean),
|
||||
hideFlexTab: Match.Optional(Boolean),
|
||||
sendOnEnter: Match.Optional(String),
|
||||
idleTimeLimit: Match.Optional(Number),
|
||||
sidebarShowFavorites: Match.Optional(Boolean),
|
||||
sidebarShowUnread: Match.Optional(Boolean),
|
||||
sidebarSortby: Match.Optional(String),
|
||||
sidebarViewMode: Match.Optional(String),
|
||||
sidebarDisplayAvatar: Match.Optional(Boolean),
|
||||
sidebarGroupByType: Match.Optional(Boolean),
|
||||
sidebarCategories: Match.Optional([
|
||||
{
|
||||
_id: String,
|
||||
name: String,
|
||||
default: Match.Optional(Boolean),
|
||||
showUnreads: Match.Optional(Boolean),
|
||||
keepUnreadsOnTop: Match.Optional(Boolean),
|
||||
},
|
||||
]),
|
||||
muteFocusedConversations: Match.Optional(Boolean),
|
||||
themeAppearence: Match.Optional(String),
|
||||
fontSize: Match.Optional(String),
|
||||
omnichannelTranscriptEmail: Match.Optional(Boolean),
|
||||
omnichannelTranscriptPDF: Match.Optional(Boolean),
|
||||
omnichannelHideConversationAfterClosing: Match.Optional(Boolean),
|
||||
notifyCalendarEvents: Match.Optional(Boolean),
|
||||
enableMobileRinging: Match.Optional(Boolean),
|
||||
mentionsWithSymbol: Match.Optional(Boolean),
|
||||
utcOffset: Match.Optional(Number),
|
||||
statusVisibilityDenied: Match.Optional([String]),
|
||||
};
|
||||
check(settings, Match.ObjectIncluding(keys));
|
||||
|
||||
if (settings.sidebarCategories) {
|
||||
validateSidebarCategories(settings.sidebarCategories);
|
||||
}
|
||||
|
||||
const user = await Users.findOneById(userId);
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
|
||||
const {
|
||||
desktopNotifications: oldDesktopNotifications,
|
||||
pushNotifications: oldMobileNotifications,
|
||||
emailNotificationMode: oldEmailNotifications,
|
||||
language: oldLanguage,
|
||||
} = user.settings?.preferences || {};
|
||||
|
||||
if (user.settings == null) {
|
||||
await Users.clearSettings(user._id);
|
||||
}
|
||||
|
||||
if (settings.language != null) {
|
||||
await Users.setLanguage(user._id, settings.language);
|
||||
}
|
||||
|
||||
// utcOffset lives at the user-document root (not under settings.preferences)
|
||||
if (settings.utcOffset != null) {
|
||||
await Users.setUtcOffset(user._id, settings.utcOffset);
|
||||
delete settings.utcOffset;
|
||||
}
|
||||
|
||||
// Keep compatibility with old values
|
||||
if (settings.emailNotificationMode === 'all') {
|
||||
settings.emailNotificationMode = 'mentions';
|
||||
} else if (settings.emailNotificationMode === 'disabled') {
|
||||
settings.emailNotificationMode = 'nothing';
|
||||
}
|
||||
|
||||
if (settings.idleTimeLimit != null && settings.idleTimeLimit < 60) {
|
||||
throw new Meteor.Error('invalid-idle-time-limit-value', 'Invalid idleTimeLimit');
|
||||
}
|
||||
|
||||
const requested = settings.statusVisibilityDenied?.filter((username) => username !== user.username);
|
||||
const denied = requested ? await resolveUsersByUsernames(requested) : undefined;
|
||||
|
||||
if (denied) {
|
||||
settings.statusVisibilityDenied = denied.usernames;
|
||||
}
|
||||
|
||||
await Users.setPreferences(user._id, denied ? { ...settings, statusVisibilityDenied: denied.ids } : settings);
|
||||
|
||||
const diff = (Object.keys(settings) as (keyof UserPreferences)[]).reduce<Record<string, any>>((data, key) => {
|
||||
data[`settings.preferences.${key}`] = settings[key];
|
||||
|
||||
return data;
|
||||
}, {});
|
||||
|
||||
void notifyOnUserChange({
|
||||
id: user._id,
|
||||
clientAction: 'updated',
|
||||
diff: {
|
||||
...diff,
|
||||
...(settings.language != null && { language: settings.language }),
|
||||
},
|
||||
});
|
||||
|
||||
if (settings.statusVisibilityDenied != null && rcSettings.get<boolean>('Accounts_StatusVisibility_Enabled')) {
|
||||
void StatusVisibility.invalidate([user._id]);
|
||||
}
|
||||
|
||||
// propagate changed notification preferences
|
||||
setImmediate(async () => {
|
||||
const { desktopNotifications, pushNotifications, emailNotificationMode, highlights, language } = settings;
|
||||
const promises = [];
|
||||
|
||||
if (desktopNotifications) {
|
||||
promises.push(
|
||||
updateNotificationPreferences(user._id, 'desktopNotifications', desktopNotifications, oldDesktopNotifications, 'desktopPrefOrigin'),
|
||||
);
|
||||
}
|
||||
|
||||
if (pushNotifications) {
|
||||
promises.push(
|
||||
updateNotificationPreferences(user._id, 'mobilePushNotifications', pushNotifications, oldMobileNotifications, 'mobilePrefOrigin'),
|
||||
);
|
||||
}
|
||||
|
||||
if (emailNotificationMode) {
|
||||
promises.push(
|
||||
updateNotificationPreferences(user._id, 'emailNotifications', emailNotificationMode, oldEmailNotifications, 'emailPrefOrigin'),
|
||||
);
|
||||
}
|
||||
|
||||
await Promise.allSettled(promises);
|
||||
|
||||
if (Array.isArray(highlights)) {
|
||||
const response = await Subscriptions.updateUserHighlights(user._id, highlights);
|
||||
if (response.modifiedCount) {
|
||||
void notifyOnSubscriptionChangedByUserId(user._id);
|
||||
}
|
||||
}
|
||||
|
||||
if (language && oldLanguage !== language && rcSettings.get('AutoTranslate_AutoEnableOnJoinRoom')) {
|
||||
const workspaceLanguage = rcSettings.get('Language');
|
||||
const targetLanguage = language === 'default' || language === workspaceLanguage ? null : language;
|
||||
|
||||
const response = await Subscriptions.setAutoTranslateByUserId(user._id, targetLanguage);
|
||||
if (response.modifiedCount) {
|
||||
void notifyOnSubscriptionChangedByAutoTranslateAndUserId(user._id);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async saveUserPreferences(settings) {
|
||||
methodDeprecationLogger.method('saveUserPreferences', '9.0.0', '/v1/users.setPreferences');
|
||||
const userId = Meteor.userId();
|
||||
if (!userId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'saveUserPreferences' });
|
||||
}
|
||||
|
||||
await saveUserPreferences(settings, userId);
|
||||
|
||||
return true;
|
||||
},
|
||||
});
|
||||
246
apps/meteor/server/meteor-methods/users/saveUserProfile.ts
Normal file
246
apps/meteor/server/meteor-methods/users/saveUserProfile.ts
Normal file
@@ -0,0 +1,246 @@
|
||||
import { Apps, AppEvents } from '@rocket.chat/apps';
|
||||
import type { UserStatus, IUser } from '@rocket.chat/core-typings';
|
||||
import { Users } from '@rocket.chat/models';
|
||||
import { Accounts } from 'meteor/accounts-base';
|
||||
import { Match, check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import type { UpdateFilter } from 'mongodb';
|
||||
|
||||
import { setEmailFunction } from './setEmail';
|
||||
import { setUserStatusMethod } from './setUserStatus';
|
||||
import { getUserInfo } from '../../api/lib/getUserInfo';
|
||||
import { type AuthenticatedContext, twoFactorRequired } from '../../lib/2fa/twoFactorRequired';
|
||||
import { passwordPolicy } from '../../lib/auth/passwordPolicy';
|
||||
import { callbacks } from '../../lib/callbacks';
|
||||
import { compareUserPassword } from '../../lib/compareUserPassword';
|
||||
import { compareUserPasswordHistory } from '../../lib/compareUserPasswordHistory';
|
||||
import { notifyOnUserChange } from '../../lib/notifyListener';
|
||||
import { saveCustomFields } from '../../lib/users/saveCustomFields';
|
||||
import { validateUserEditing } from '../../lib/users/saveUser';
|
||||
import { saveUserIdentity } from '../../lib/users/saveUserIdentity';
|
||||
import { settings as rcSettings } from '../../settings';
|
||||
|
||||
const MAX_BIO_LENGTH = 260;
|
||||
const MAX_NICKNAME_LENGTH = 120;
|
||||
|
||||
async function saveUserProfile(
|
||||
this: AuthenticatedContext,
|
||||
settings: {
|
||||
email?: string;
|
||||
username?: string;
|
||||
realname?: string;
|
||||
newPassword?: string;
|
||||
statusText?: string;
|
||||
statusType?: string;
|
||||
bio?: string;
|
||||
nickname?: string;
|
||||
},
|
||||
customFields: Record<string, unknown>,
|
||||
..._: unknown[]
|
||||
) {
|
||||
const unset: UpdateFilter<IUser> = {};
|
||||
if (!rcSettings.get<boolean>('Accounts_AllowUserProfileChange')) {
|
||||
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
|
||||
method: 'saveUserProfile',
|
||||
});
|
||||
}
|
||||
|
||||
if (!this.userId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'saveUserProfile',
|
||||
});
|
||||
}
|
||||
|
||||
await validateUserEditing(this.userId, {
|
||||
_id: this.userId,
|
||||
email: settings.email,
|
||||
username: settings.username,
|
||||
name: settings.realname,
|
||||
password: settings.newPassword,
|
||||
statusText: settings.statusText,
|
||||
});
|
||||
|
||||
const user = await Users.findOneById(this.userId);
|
||||
|
||||
if (!user) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'saveUserProfile',
|
||||
});
|
||||
}
|
||||
|
||||
if (settings.realname || settings.username) {
|
||||
if (
|
||||
!(await saveUserIdentity({
|
||||
_id: this.userId,
|
||||
name: settings.realname,
|
||||
username: settings.username,
|
||||
}))
|
||||
) {
|
||||
throw new Meteor.Error('error-could-not-save-identity', 'Could not save user identity', {
|
||||
method: 'saveUserProfile',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.statusType || settings.statusText != null) {
|
||||
await setUserStatusMethod(user, settings.statusType as UserStatus, settings.statusText);
|
||||
}
|
||||
|
||||
if (user && (settings.bio || settings.bio === '')) {
|
||||
if (typeof settings.bio !== 'string') {
|
||||
throw new Meteor.Error('error-invalid-field', 'bio', {
|
||||
method: 'saveUserProfile',
|
||||
});
|
||||
}
|
||||
if (settings.bio.length > MAX_BIO_LENGTH) {
|
||||
throw new Meteor.Error('error-bio-size-exceeded', `Bio size exceeds ${MAX_BIO_LENGTH} characters`, {
|
||||
method: 'saveUserProfile',
|
||||
});
|
||||
}
|
||||
await Users.setBio(user._id, settings.bio.trim());
|
||||
}
|
||||
|
||||
if (user && (settings.nickname || settings.nickname === '')) {
|
||||
if (typeof settings.nickname !== 'string') {
|
||||
throw new Meteor.Error('error-invalid-field', 'nickname', {
|
||||
method: 'saveUserProfile',
|
||||
});
|
||||
}
|
||||
if (settings.nickname.length > MAX_NICKNAME_LENGTH) {
|
||||
throw new Meteor.Error('error-nickname-size-exceeded', `Nickname size exceeds ${MAX_NICKNAME_LENGTH} characters`, {
|
||||
method: 'saveUserProfile',
|
||||
});
|
||||
}
|
||||
await Users.setNickname(user._id, settings.nickname.trim());
|
||||
}
|
||||
|
||||
if (user && settings.email) {
|
||||
await setEmailFunction(settings.email, user);
|
||||
}
|
||||
|
||||
const canChangePasswordForOAuth = rcSettings.get<boolean>('Accounts_AllowPasswordChangeForOAuthUsers');
|
||||
if (canChangePasswordForOAuth || user?.services?.password) {
|
||||
// Should be the last check to prevent error when trying to check password for users without password
|
||||
if (settings.newPassword && rcSettings.get<boolean>('Accounts_AllowPasswordChange') === true && user?.services?.password?.bcrypt) {
|
||||
// don't let user change to same password
|
||||
if (user && (await compareUserPassword(user, { plain: settings.newPassword }))) {
|
||||
throw new Meteor.Error('error-password-same-as-current', 'Entered password same as current password', {
|
||||
method: 'saveUserProfile',
|
||||
});
|
||||
}
|
||||
|
||||
if (user?.services?.passwordHistory && !(await compareUserPasswordHistory(user, { plain: settings.newPassword }))) {
|
||||
throw new Meteor.Error('error-password-in-history', 'Entered password has been previously used', {
|
||||
method: 'saveUserProfile',
|
||||
});
|
||||
}
|
||||
|
||||
passwordPolicy.validate(settings.newPassword);
|
||||
|
||||
await Accounts.setPasswordAsync(this.userId, settings.newPassword, {
|
||||
logout: false,
|
||||
});
|
||||
|
||||
if (user.requirePasswordChange) {
|
||||
await Users.unsetRequirePasswordChange(user._id);
|
||||
unset.requirePasswordChange = true;
|
||||
unset.requirePasswordChangeReason = true;
|
||||
}
|
||||
|
||||
await Users.addPasswordToHistory(
|
||||
this.userId,
|
||||
user.services?.password.bcrypt,
|
||||
rcSettings.get<number>('Accounts_Password_History_Amount'),
|
||||
);
|
||||
|
||||
try {
|
||||
await Users.removeNonLoginTokensExcept(this.userId, this.token);
|
||||
} catch (e) {
|
||||
Accounts._clearAllLoginTokens(this.userId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Users.setProfile(this.userId, {});
|
||||
|
||||
if (customFields && Object.keys(customFields).length) {
|
||||
await saveCustomFields(this.userId, customFields);
|
||||
}
|
||||
|
||||
// App IPostUserUpdated event hook
|
||||
const updatedUser = await Users.findOneById(this.userId);
|
||||
|
||||
// This should never happen, but since `Users.findOneById` might return null, we'll handle it just in case
|
||||
if (!updatedUser) {
|
||||
throw new Error('Unexpected error after saving user profile: user not found');
|
||||
}
|
||||
|
||||
await callbacks.run('afterSaveUser', {
|
||||
user: updatedUser,
|
||||
oldUser: user,
|
||||
});
|
||||
|
||||
void notifyOnUserChange({
|
||||
clientAction: 'updated',
|
||||
id: updatedUser._id,
|
||||
diff: await getUserInfo(updatedUser),
|
||||
...(Object.keys(unset).length > 0 && { unset }),
|
||||
});
|
||||
|
||||
await Apps.self?.triggerEvent(AppEvents.IPostUserUpdated, { user: updatedUser, previousUser: user });
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
const saveUserProfileWithTwoFactor = twoFactorRequired(saveUserProfile, {
|
||||
requireSecondFactor: true,
|
||||
});
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
saveUserProfile(
|
||||
settings: {
|
||||
email?: string;
|
||||
username?: string;
|
||||
realname?: string;
|
||||
newPassword?: string;
|
||||
statusText?: string;
|
||||
statusType?: string;
|
||||
bio?: string;
|
||||
nickname?: string;
|
||||
},
|
||||
customFields: Record<string, any>,
|
||||
...args: unknown[]
|
||||
): boolean;
|
||||
}
|
||||
}
|
||||
|
||||
export function executeSaveUserProfile(
|
||||
this: AuthenticatedContext,
|
||||
user: IUser,
|
||||
settings: {
|
||||
email?: string;
|
||||
username?: string;
|
||||
realname?: string;
|
||||
newPassword?: string;
|
||||
statusText?: string;
|
||||
statusType?: string;
|
||||
bio?: string;
|
||||
nickname?: string;
|
||||
},
|
||||
customFields: Record<string, any> = {},
|
||||
...args: unknown[]
|
||||
) {
|
||||
check(settings, Object);
|
||||
check(customFields, Match.Maybe(Object));
|
||||
|
||||
if (
|
||||
(settings.email && user.emails?.length) ||
|
||||
(settings.newPassword && Object.keys(user.services || {}).length && !user.requirePasswordChange)
|
||||
) {
|
||||
return saveUserProfileWithTwoFactor.call(this, settings, customFields, ...args);
|
||||
}
|
||||
|
||||
return saveUserProfile.call(this, settings, customFields, ...args);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Match, check } from 'meteor/check';
|
||||
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { setAvatarFromServiceWithValidation } from '../../lib/users/setUserAvatar';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
setAvatarFromService(dataURI: Buffer | Blob, contentType?: string, service?: string, targetUserId?: string): void;
|
||||
}
|
||||
}
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async setAvatarFromService(dataURI, contentType, service, targetUserId) {
|
||||
methodDeprecationLogger.method('setAvatarFromService', '9.0.0', '/v1/users.setAvatar');
|
||||
|
||||
check(dataURI, String);
|
||||
check(contentType, Match.Optional(String));
|
||||
check(service, Match.Optional(String));
|
||||
check(targetUserId, Match.Optional(String));
|
||||
|
||||
const uid = Meteor.userId();
|
||||
|
||||
if (!uid) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'setAvatarFromService',
|
||||
});
|
||||
}
|
||||
|
||||
return setAvatarFromServiceWithValidation(uid, dataURI, contentType, service, targetUserId);
|
||||
},
|
||||
});
|
||||
|
||||
DDPRateLimiter.addRule(
|
||||
{
|
||||
type: 'method',
|
||||
name: 'setAvatarFromService',
|
||||
userId() {
|
||||
return true;
|
||||
},
|
||||
},
|
||||
1,
|
||||
5000,
|
||||
);
|
||||
58
apps/meteor/server/meteor-methods/users/setEmail.ts
Normal file
58
apps/meteor/server/meteor-methods/users/setEmail.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import type { IUser } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { RateLimiterClass as RateLimiter } from '../../lib/RateLimiter';
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { setEmail } from '../../lib/users/setEmail';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
setEmail(email: string): string;
|
||||
}
|
||||
}
|
||||
|
||||
export const setEmailFunction = async (email: string, user: Meteor.User | IUser) => {
|
||||
check(email, String);
|
||||
|
||||
if (!settings.get('Accounts_AllowEmailChange')) {
|
||||
throw new Meteor.Error('error-action-not-allowed', 'Changing email is not allowed', {
|
||||
method: 'setEmail',
|
||||
action: 'Changing_email',
|
||||
});
|
||||
}
|
||||
|
||||
if (user.emails?.[0]?.address === email) {
|
||||
return email;
|
||||
}
|
||||
|
||||
if (!(await setEmail(user._id, email))) {
|
||||
throw new Meteor.Error('error-could-not-change-email', 'Could not change email', {
|
||||
method: 'setEmail',
|
||||
});
|
||||
}
|
||||
|
||||
return email;
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async setEmail(email) {
|
||||
methodDeprecationLogger.method('setEmail', '9.0.0', '/v1/users.updateOwnBasicInfo');
|
||||
const user = await Meteor.userAsync();
|
||||
|
||||
if (!user) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setEmail' });
|
||||
}
|
||||
|
||||
return setEmailFunction(email, user);
|
||||
},
|
||||
});
|
||||
|
||||
RateLimiter.limitMethod('setEmail', 1, 1000, {
|
||||
userId(/* userId*/) {
|
||||
return true;
|
||||
},
|
||||
});
|
||||
42
apps/meteor/server/meteor-methods/users/setRealName.ts
Normal file
42
apps/meteor/server/meteor-methods/users/setRealName.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { RateLimiterClass as RateLimiter } from '../../lib/RateLimiter';
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { setRealName } from '../../lib/users/setRealName';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
setRealName(name: string): string;
|
||||
}
|
||||
}
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async setRealName(name) {
|
||||
methodDeprecationLogger.method('setRealName', '9.0.0', '/v1/users.updateOwnBasicInfo');
|
||||
check(name, String);
|
||||
const userId = Meteor.userId();
|
||||
if (!userId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setRealName' });
|
||||
}
|
||||
|
||||
if (!settings.get('Accounts_AllowRealNameChange')) {
|
||||
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setRealName' });
|
||||
}
|
||||
|
||||
if (!(await setRealName(userId, name))) {
|
||||
throw new Meteor.Error('error-could-not-change-name', 'Could not change name', {
|
||||
method: 'setRealName',
|
||||
});
|
||||
}
|
||||
|
||||
return name;
|
||||
},
|
||||
});
|
||||
|
||||
RateLimiter.limitMethod('setRealName', 1, 1000, {
|
||||
userId: () => true,
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
|
||||
import { setUserActiveStatus } from '../../lib/users/setUserActiveStatus';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
setUserActiveStatus(userId: string, active: boolean, confirmRelinquish?: boolean): boolean;
|
||||
}
|
||||
}
|
||||
|
||||
export const executeSetUserActiveStatus = async (
|
||||
fromUserId: string,
|
||||
userId: string,
|
||||
active: boolean,
|
||||
confirmRelinquish?: boolean,
|
||||
): Promise<boolean> => {
|
||||
check(userId, String);
|
||||
check(active, Boolean);
|
||||
|
||||
if (!fromUserId || (await hasPermissionAsync(fromUserId, 'edit-other-user-active-status')) !== true) {
|
||||
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
|
||||
method: 'setUserActiveStatus',
|
||||
});
|
||||
}
|
||||
|
||||
await setUserActiveStatus(userId, active, confirmRelinquish, fromUserId);
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async setUserActiveStatus(userId, active, confirmRelinquish) {
|
||||
const uid = Meteor.userId();
|
||||
if (!uid) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
|
||||
method: 'setUserActiveStatus',
|
||||
});
|
||||
}
|
||||
|
||||
return executeSetUserActiveStatus(uid, userId, active, confirmRelinquish);
|
||||
},
|
||||
});
|
||||
51
apps/meteor/server/meteor-methods/users/setUserStatus.ts
Normal file
51
apps/meteor/server/meteor-methods/users/setUserStatus.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { Presence } from '@rocket.chat/core-services';
|
||||
import { UserStatus, type IUser } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { RateLimiterClass as RateLimiter } from '../../lib/RateLimiter';
|
||||
import { settings } from '../../settings';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
setUserStatus(statusType: IUser['status'], statusText: IUser['statusText']): void;
|
||||
}
|
||||
}
|
||||
|
||||
export const setUserStatusMethod = async (
|
||||
user: Pick<IUser, '_id' | 'username' | 'name' | 'status' | 'statusDefault' | 'roles' | 'statusText'>,
|
||||
statusType: IUser['status'],
|
||||
statusText: IUser['statusText'],
|
||||
): Promise<void> => {
|
||||
if (statusText != null && !settings.get('Accounts_AllowUserStatusMessageChange')) {
|
||||
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
|
||||
method: 'setUserStatus',
|
||||
});
|
||||
}
|
||||
|
||||
const effectiveStatus = statusType || user.statusDefault || UserStatus.ONLINE;
|
||||
|
||||
if (effectiveStatus === UserStatus.OFFLINE && !settings.get('Accounts_AllowInvisibleStatusOption')) {
|
||||
throw new Meteor.Error('error-status-not-allowed', 'Invisible status is disabled', {
|
||||
method: 'setUserStatus',
|
||||
});
|
||||
}
|
||||
|
||||
await Presence.setStatus(user._id, effectiveStatus, statusText);
|
||||
};
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
setUserStatus: async (statusType, statusText) => {
|
||||
const user = (await Meteor.userAsync()) as IUser;
|
||||
if (!user) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setUserStatus' });
|
||||
}
|
||||
|
||||
await setUserStatusMethod(user, statusType, statusText);
|
||||
},
|
||||
});
|
||||
|
||||
RateLimiter.limitMethod('setUserStatus', 1, 1000, {
|
||||
userId: () => true,
|
||||
});
|
||||
31
apps/meteor/server/meteor-methods/users/unblockUser.ts
Normal file
31
apps/meteor/server/meteor-methods/users/unblockUser.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { check } from 'meteor/check';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
import { unblockUserMethod } from '../../lib/users/unblockUser';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
unblockUser({ rid, blocked }: { rid: string; blocked: string }): boolean;
|
||||
}
|
||||
}
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async unblockUser({ rid, blocked }) {
|
||||
methodDeprecationLogger.method('unblockUser', '9.0.0', '/v1/im.blockUser');
|
||||
check(rid, String);
|
||||
check(blocked, String);
|
||||
|
||||
const userId = Meteor.userId();
|
||||
|
||||
if (!userId) {
|
||||
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'unblockUser' });
|
||||
}
|
||||
|
||||
await unblockUserMethod(userId, { rid, blocked });
|
||||
|
||||
return true;
|
||||
},
|
||||
});
|
||||
40
apps/meteor/server/meteor-methods/users/userPresence.ts
Normal file
40
apps/meteor/server/meteor-methods/users/userPresence.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { Presence } from '@rocket.chat/core-services';
|
||||
import { UserStatus } from '@rocket.chat/core-typings';
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
'UserPresence:setDefaultStatus'(status: UserStatus): boolean | undefined;
|
||||
'UserPresence:online'(): boolean | undefined;
|
||||
'UserPresence:away'(): boolean | undefined;
|
||||
}
|
||||
}
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
'UserPresence:setDefaultStatus'(status) {
|
||||
methodDeprecationLogger.method('UserPresence:setDefaultStatus', '9.0.0', '/v1/users.setStatus');
|
||||
const { userId } = this;
|
||||
if (!userId) {
|
||||
return;
|
||||
}
|
||||
return Presence.setStatus(userId, status);
|
||||
},
|
||||
'UserPresence:online'() {
|
||||
const { userId, connection } = this;
|
||||
if (!userId || !connection) {
|
||||
return;
|
||||
}
|
||||
return Presence.setConnectionStatus(userId, UserStatus.ONLINE, connection.id);
|
||||
},
|
||||
'UserPresence:away'() {
|
||||
const { userId, connection } = this;
|
||||
if (!userId || !connection) {
|
||||
return;
|
||||
}
|
||||
return Presence.setConnectionStatus(userId, UserStatus.AWAY, connection.id);
|
||||
},
|
||||
});
|
||||
39
apps/meteor/server/meteor-methods/users/userSetUtcOffset.ts
Normal file
39
apps/meteor/server/meteor-methods/users/userSetUtcOffset.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import type { ServerMethods } from '@rocket.chat/ddp-client';
|
||||
import { Users } from '@rocket.chat/models';
|
||||
import { check } from 'meteor/check';
|
||||
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
|
||||
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
|
||||
|
||||
declare module '@rocket.chat/ddp-client' {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
interface ServerMethods {
|
||||
userSetUtcOffset(utcOffset: number): void;
|
||||
}
|
||||
}
|
||||
|
||||
Meteor.methods<ServerMethods>({
|
||||
async userSetUtcOffset(utcOffset) {
|
||||
methodDeprecationLogger.method('userSetUtcOffset', '9.0.0', '/v1/users.setPreferences');
|
||||
check(utcOffset, Number);
|
||||
|
||||
if (!this.userId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await Users.setUtcOffset(this.userId, utcOffset);
|
||||
},
|
||||
});
|
||||
|
||||
DDPRateLimiter.addRule(
|
||||
{
|
||||
type: 'method',
|
||||
name: 'userSetUtcOffset',
|
||||
userId() {
|
||||
return true;
|
||||
},
|
||||
},
|
||||
1,
|
||||
60000,
|
||||
);
|
||||
Reference in New Issue
Block a user