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:
@@ -0,0 +1,154 @@
|
||||
import { MeteorError } from '@rocket.chat/core-services';
|
||||
import { expect } from 'chai';
|
||||
import { describe, it, beforeEach, afterEach } from 'mocha';
|
||||
import mock from 'proxyquire';
|
||||
import Sinon from 'sinon';
|
||||
|
||||
type SendUserEmailFn = (subject: string, html: string, user: { email?: string; password?: string; name?: string }) => Promise<void>;
|
||||
type SendHelperFn = (user: { email?: string; password?: string; name?: string }) => Promise<void>;
|
||||
|
||||
const userData = {
|
||||
email: 'test@example.com',
|
||||
password: '123456',
|
||||
name: 'Test User',
|
||||
};
|
||||
|
||||
const makeStubs = () => {
|
||||
const MailerStub = {
|
||||
getTemplate: Sinon.stub(),
|
||||
send: Sinon.stub(),
|
||||
};
|
||||
|
||||
const SettingsStub = {
|
||||
settings: {
|
||||
get: Sinon.stub().callsFake((key: string) => {
|
||||
if (key === 'From_Email') return 'no-reply@example.com';
|
||||
if (key === 'Accounts_UserAddedEmail_Subject') return 'Welcome [name]!';
|
||||
if (key === 'Password_Changed_Email_Subject') return 'Password Changed';
|
||||
return '';
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
const MeteorStub = {
|
||||
Meteor: {
|
||||
startup: Sinon.stub(),
|
||||
},
|
||||
};
|
||||
|
||||
return { MailerStub, SettingsStub, MeteorStub };
|
||||
};
|
||||
|
||||
describe('sendUserEmail (Mocha + TS)', () => {
|
||||
let MailerStub: { getTemplate: Sinon.SinonStub; send: Sinon.SinonStub };
|
||||
let SettingsStub: { settings: { get: Sinon.SinonStub } };
|
||||
let MeteorStub: { Meteor: { startup: Sinon.SinonStub } };
|
||||
|
||||
let sendUserEmail: SendUserEmailFn;
|
||||
let sendWelcomeEmail: SendHelperFn;
|
||||
let sendPasswordEmail: SendHelperFn;
|
||||
|
||||
beforeEach(() => {
|
||||
const stubs = makeStubs();
|
||||
MailerStub = stubs.MailerStub as any;
|
||||
SettingsStub = stubs.SettingsStub as any;
|
||||
MeteorStub = stubs.MeteorStub as any;
|
||||
|
||||
const mod = mock.noCallThru().load('../../../../../../server/lib/users/saveUser/sendUserEmail.ts', {
|
||||
'../../notifications/email/api': MailerStub,
|
||||
'../../../settings': SettingsStub,
|
||||
'meteor/meteor': MeteorStub,
|
||||
}) as any;
|
||||
|
||||
sendUserEmail = mod.sendUserEmail as SendUserEmailFn;
|
||||
sendWelcomeEmail = mod.sendWelcomeEmail as SendHelperFn;
|
||||
sendPasswordEmail = mod.sendPasswordEmail as SendHelperFn;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Sinon.restore();
|
||||
});
|
||||
|
||||
describe('sendUserEmail', () => {
|
||||
it('should not send email if userData.email is missing', async () => {
|
||||
await sendUserEmail('subject', '<p>html</p>', { ...userData, email: undefined });
|
||||
|
||||
Sinon.assert.notCalled(MailerStub.send);
|
||||
});
|
||||
|
||||
it('should send email with correct parameters', async () => {
|
||||
await sendUserEmail('subject', '<p>html</p>', userData);
|
||||
|
||||
Sinon.assert.calledOnce(MailerStub.send);
|
||||
const callArg = MailerStub.send.getCall(0).args[0];
|
||||
expect(callArg).to.be.an('object');
|
||||
expect(callArg).to.include({
|
||||
to: userData.email,
|
||||
from: SettingsStub.settings.get('From_Email'),
|
||||
subject: 'subject',
|
||||
html: '<p>html</p>',
|
||||
});
|
||||
expect(callArg.data).to.include({
|
||||
email: userData.email,
|
||||
password: userData.password,
|
||||
name: userData.name,
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw MeteorError if Mailer.send fails', async () => {
|
||||
MailerStub.send.throws(new Error('fail'));
|
||||
|
||||
let thrown = false;
|
||||
try {
|
||||
await sendUserEmail('subject', '<p>html</p>', userData);
|
||||
} catch (err) {
|
||||
thrown = true;
|
||||
expect(err).to.be.instanceOf(MeteorError);
|
||||
}
|
||||
expect(thrown).to.equal(true);
|
||||
});
|
||||
|
||||
it('should mask password in email data if password is not provided', async () => {
|
||||
await sendUserEmail('subject', '<p>html</p>', { ...userData, password: undefined });
|
||||
|
||||
Sinon.assert.calledOnce(MailerStub.send);
|
||||
const callArg = MailerStub.send.getCall(0).args[0];
|
||||
expect(callArg.data).to.include({
|
||||
email: userData.email,
|
||||
password: '******',
|
||||
name: userData.name,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('sendWelcomeEmail', () => {
|
||||
it('should call sendUserEmail with welcome subject and template', async () => {
|
||||
await sendWelcomeEmail(userData);
|
||||
|
||||
Sinon.assert.calledOnce(MailerStub.send);
|
||||
const callArg = MailerStub.send.getCall(0).args[0];
|
||||
expect(callArg).to.include({
|
||||
subject: `Welcome [name]!`,
|
||||
to: userData.email,
|
||||
});
|
||||
expect(callArg.data).to.deep.equal({
|
||||
email: userData.email,
|
||||
password: userData.password,
|
||||
name: userData.name,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('sendPasswordEmail', () => {
|
||||
it('should call sendUserEmail with password subject and template', async () => {
|
||||
await sendPasswordEmail(userData);
|
||||
|
||||
Sinon.assert.calledOnce(MailerStub.send);
|
||||
const callArg = MailerStub.send.getCall(0).args[0];
|
||||
expect(callArg).to.include({
|
||||
subject: 'Password Changed',
|
||||
to: userData.email,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
336
apps/meteor/tests/unit/server/lib/users/setUsername.spec.ts
Normal file
336
apps/meteor/tests/unit/server/lib/users/setUsername.spec.ts
Normal file
@@ -0,0 +1,336 @@
|
||||
import { expect } from 'chai';
|
||||
import proxyquire from 'proxyquire';
|
||||
import sinon from 'sinon';
|
||||
|
||||
describe('setUsername', () => {
|
||||
const userId = 'userId';
|
||||
const username = 'validUsername';
|
||||
|
||||
const stubs = {
|
||||
Users: {
|
||||
findOneById: sinon.stub(),
|
||||
setUsername: sinon.stub(),
|
||||
},
|
||||
Subscriptions: {
|
||||
findUserFederatedRoomIds: sinon.stub(),
|
||||
},
|
||||
Accounts: {
|
||||
sendEnrollmentEmail: sinon.stub(),
|
||||
},
|
||||
settings: {
|
||||
get: sinon.stub(),
|
||||
},
|
||||
api: {
|
||||
broadcast: sinon.stub(),
|
||||
},
|
||||
Invites: {
|
||||
findOneById: sinon.stub(),
|
||||
},
|
||||
callbacks: {
|
||||
run: sinon.stub(),
|
||||
runAsync: sinon.stub(),
|
||||
},
|
||||
checkUsernameAvailability: sinon.stub(),
|
||||
validateUsername: sinon.stub(),
|
||||
saveUserIdentity: sinon.stub(),
|
||||
joinDefaultChannels: sinon.stub(),
|
||||
getAvatarSuggestionForUser: sinon.stub(),
|
||||
setUserAvatar: sinon.stub(),
|
||||
addUserToRoom: sinon.stub(),
|
||||
notifyOnUserChange: sinon.stub(),
|
||||
underscore: {
|
||||
escape: sinon.stub(),
|
||||
},
|
||||
SystemLogger: sinon.stub(),
|
||||
};
|
||||
|
||||
const { setUsernameWithValidation, _setUsername } = proxyquire.noCallThru().load('../../../../../server/lib/users/setUsername', {
|
||||
'../../database/utils': { onceTransactionCommitedSuccessfully: async (cb: any, _sess: any) => cb() },
|
||||
'meteor/meteor': { Meteor: { Error } },
|
||||
'@rocket.chat/core-services': { api: stubs.api },
|
||||
'@rocket.chat/models': { Users: stubs.Users, Invites: stubs.Invites, Subscriptions: stubs.Subscriptions },
|
||||
'meteor/accounts-base': { Accounts: stubs.Accounts },
|
||||
'underscore': stubs.underscore,
|
||||
'../../settings': { settings: stubs.settings },
|
||||
'../notifyListener': { notifyOnUserChange: stubs.notifyOnUserChange },
|
||||
'../rooms/addUserToRoom': { addUserToRoom: stubs.addUserToRoom },
|
||||
'./checkUsernameAvailability': { checkUsernameAvailability: stubs.checkUsernameAvailability },
|
||||
'./getAvatarSuggestionForUser': { getAvatarSuggestionForUser: stubs.getAvatarSuggestionForUser },
|
||||
'../rooms/joinDefaultChannels': { joinDefaultChannels: stubs.joinDefaultChannels },
|
||||
'./saveUserIdentity': { saveUserIdentity: stubs.saveUserIdentity },
|
||||
'./setUserAvatar': { setUserAvatar: stubs.setUserAvatar },
|
||||
'./validateUsername': { validateUsername: stubs.validateUsername },
|
||||
'../callbacks': { callbacks: stubs.callbacks },
|
||||
'../logger/system': { SystemLogger: stubs.SystemLogger },
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
stubs.Subscriptions.findUserFederatedRoomIds.returns({
|
||||
hasNext: sinon.stub().resolves(false),
|
||||
close: sinon.stub().resolves(),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
stubs.Users.findOneById.reset();
|
||||
stubs.Users.setUsername.reset();
|
||||
stubs.Subscriptions.findUserFederatedRoomIds.reset();
|
||||
stubs.Accounts.sendEnrollmentEmail.reset();
|
||||
stubs.settings.get.reset();
|
||||
stubs.api.broadcast.reset();
|
||||
stubs.Invites.findOneById.reset();
|
||||
stubs.callbacks.run.reset();
|
||||
stubs.callbacks.runAsync.reset();
|
||||
stubs.checkUsernameAvailability.reset();
|
||||
stubs.validateUsername.reset();
|
||||
stubs.saveUserIdentity.reset();
|
||||
stubs.joinDefaultChannels.reset();
|
||||
stubs.getAvatarSuggestionForUser.reset();
|
||||
stubs.setUserAvatar.reset();
|
||||
stubs.addUserToRoom.reset();
|
||||
stubs.notifyOnUserChange.reset();
|
||||
stubs.underscore.escape.reset();
|
||||
stubs.SystemLogger.reset();
|
||||
});
|
||||
|
||||
describe('setUsernameWithValidation', () => {
|
||||
it('should throw an error if username is invalid', async () => {
|
||||
try {
|
||||
await setUsernameWithValidation(userId, '');
|
||||
} catch (error: any) {
|
||||
expect(error.message).to.equal('error-invalid-username');
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw an error if user is not found', async () => {
|
||||
stubs.Users.findOneById.withArgs(userId).returns(null);
|
||||
|
||||
try {
|
||||
await setUsernameWithValidation(userId, username);
|
||||
} catch (error: any) {
|
||||
expect(stubs.Users.findOneById.calledOnce).to.be.true;
|
||||
expect(error.message).to.equal('error-invalid-user');
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw an error if username change is not allowed', async () => {
|
||||
stubs.Users.findOneById.resolves({ username: 'oldUsername' });
|
||||
stubs.settings.get.withArgs('Accounts_AllowUsernameChange').returns(false);
|
||||
|
||||
try {
|
||||
await setUsernameWithValidation(userId, username);
|
||||
} catch (error: any) {
|
||||
expect(stubs.settings.get.calledOnce).to.be.true;
|
||||
expect(error.message).to.equal('error-not-allowed');
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw an error if username is not valid', async () => {
|
||||
stubs.Users.findOneById.resolves({ username: null });
|
||||
stubs.validateUsername.returns(false);
|
||||
|
||||
try {
|
||||
await setUsernameWithValidation(userId, 'invalid-username');
|
||||
} catch (error: any) {
|
||||
expect(stubs.validateUsername.calledOnce).to.be.true;
|
||||
expect(error.message).to.equal('username-invalid');
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw an error if username is already in use', async () => {
|
||||
stubs.Users.findOneById.resolves({ username: null });
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.checkUsernameAvailability.resolves(false);
|
||||
|
||||
try {
|
||||
await setUsernameWithValidation(userId, 'existingUsername');
|
||||
} catch (error: any) {
|
||||
expect(stubs.checkUsernameAvailability.calledOnce).to.be.true;
|
||||
expect(error.message).to.equal('error-field-unavailable');
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw an error if local user is in federated rooms', async () => {
|
||||
stubs.Users.findOneById.resolves({ _id: userId, username: null });
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
stubs.Subscriptions.findUserFederatedRoomIds.returns({
|
||||
hasNext: sinon.stub().resolves(true),
|
||||
close: sinon.stub().resolves(),
|
||||
});
|
||||
|
||||
try {
|
||||
await setUsernameWithValidation(userId, 'newUsername');
|
||||
} catch (error: any) {
|
||||
expect(stubs.Subscriptions.findUserFederatedRoomIds.calledOnce).to.be.true;
|
||||
expect(error.message).to.equal('error-not-allowed');
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw an error if user is federated', async () => {
|
||||
stubs.Users.findOneById.resolves({
|
||||
_id: userId,
|
||||
username: null,
|
||||
federated: true,
|
||||
federation: { version: 1, mui: '@user:origin', origin: 'origin' },
|
||||
});
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
|
||||
try {
|
||||
await setUsernameWithValidation(userId, 'newUsername');
|
||||
} catch (error: any) {
|
||||
expect(stubs.Subscriptions.findUserFederatedRoomIds.notCalled).to.be.true;
|
||||
expect(error.message).to.equal('error-not-allowed');
|
||||
}
|
||||
});
|
||||
|
||||
it('should save the user identity when valid username is set', async () => {
|
||||
stubs.Users.findOneById.resolves({ _id: userId, username: null });
|
||||
stubs.settings.get.withArgs('Accounts_AllowUsernameChange').returns(true);
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
stubs.saveUserIdentity.resolves(true);
|
||||
|
||||
await setUsernameWithValidation(userId, 'newUsername');
|
||||
|
||||
expect(stubs.saveUserIdentity.calledOnce).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe('_setUsername', () => {
|
||||
it('should return false if userId or username is missing', async () => {
|
||||
const result = await _setUsername(null, '', {});
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
|
||||
it('should return false if username is invalid', async () => {
|
||||
stubs.validateUsername.returns(false);
|
||||
|
||||
const result = await _setUsername(userId, 'invalid-username', {});
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
|
||||
it('should return user if username is already set', async () => {
|
||||
stubs.validateUsername.returns(true);
|
||||
const mockUser = { username };
|
||||
|
||||
const result = await _setUsername(userId, username, mockUser);
|
||||
expect(result).to.equal(mockUser);
|
||||
});
|
||||
|
||||
it('should set username when user has no previous username', async () => {
|
||||
const mockUser = { _id: userId, emails: [{ address: 'test@example.com' }] };
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.Users.findOneById.resolves(mockUser);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
|
||||
await _setUsername(userId, username, mockUser);
|
||||
|
||||
expect(stubs.Users.setUsername.calledOnceWith(userId, username));
|
||||
expect(stubs.checkUsernameAvailability.calledOnceWith(username));
|
||||
expect(stubs.api.broadcast.calledOnceWith('user.autoupdate', { user: mockUser }));
|
||||
});
|
||||
|
||||
it('should set username when user has and old that is different from new', async () => {
|
||||
const mockUser = { _id: userId, username: 'oldUsername', emails: [{ address: 'test@example.com' }] };
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.Users.findOneById.resolves(mockUser);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
|
||||
await _setUsername(userId, username, mockUser);
|
||||
|
||||
expect(stubs.Users.setUsername.calledOnceWith(userId, username));
|
||||
expect(stubs.checkUsernameAvailability.calledOnceWith(username));
|
||||
expect(stubs.api.broadcast.calledOnceWith('user.autoupdate', { user: mockUser }));
|
||||
});
|
||||
|
||||
it('should set username when user has and old that is different from new', async () => {
|
||||
const mockUser = { _id: userId, username: 'oldUsername', emails: [{ address: 'test@example.com' }] };
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.Users.findOneById.resolves(mockUser);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
|
||||
await _setUsername(userId, username, mockUser);
|
||||
|
||||
expect(stubs.Users.setUsername.calledOnceWith(userId, username));
|
||||
expect(stubs.checkUsernameAvailability.calledOnceWith(username));
|
||||
expect(stubs.api.broadcast.calledOnceWith('user.autoupdate', { user: mockUser }));
|
||||
});
|
||||
|
||||
it('should join the default channels and run afterCreateUser on the first username', async () => {
|
||||
const mockUser = { _id: userId, roles: ['user'] };
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
|
||||
await _setUsername(userId, username, mockUser);
|
||||
|
||||
expect(stubs.joinDefaultChannels.calledOnceWith(userId)).to.be.true;
|
||||
expect(stubs.callbacks.runAsync.calledWith('afterCreateUser')).to.be.true;
|
||||
expect(stubs.callbacks.runAsync.withArgs('afterCreateUser').firstCall.args[1]).to.include({ username });
|
||||
});
|
||||
|
||||
it('should not join the default channels when the username is only being changed', async () => {
|
||||
const mockUser = { _id: userId, username: 'oldUsername', roles: ['user'] };
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
|
||||
await _setUsername(userId, username, mockUser);
|
||||
|
||||
expect(stubs.joinDefaultChannels.notCalled).to.be.true;
|
||||
expect(stubs.callbacks.runAsync.calledWith('afterCreateUser')).to.be.false;
|
||||
});
|
||||
|
||||
it('should set avatar if Accounts_SetDefaultAvatar is enabled', async () => {
|
||||
const mockUser = { _id: userId, username: null };
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.Users.findOneById.resolves(mockUser);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
stubs.settings.get.withArgs('Accounts_SetDefaultAvatar').returns(true);
|
||||
stubs.getAvatarSuggestionForUser.resolves({ gravatar: { blob: 'blobData', contentType: 'image/png' } });
|
||||
|
||||
await _setUsername(userId, username, mockUser);
|
||||
|
||||
expect(stubs.setUserAvatar.calledOnceWith(mockUser, 'blobData', 'image/png', 'gravatar')).to.be.true;
|
||||
});
|
||||
|
||||
it('should not set avatar if Accounts_SetDefaultAvatar is disabled', async () => {
|
||||
const mockUser = { _id: userId, username: null };
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.Users.findOneById.resolves(mockUser);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
stubs.settings.get.withArgs('Accounts_SetDefaultAvatar').returns(false);
|
||||
|
||||
await _setUsername(userId, username, mockUser);
|
||||
|
||||
expect(stubs.setUserAvatar.called).to.be.false;
|
||||
});
|
||||
|
||||
it('should not set avatar if no avatar suggestions are available', async () => {
|
||||
const mockUser = { _id: userId, username: null };
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.Users.findOneById.resolves(mockUser);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
stubs.settings.get.withArgs('Accounts_SetDefaultAvatar').returns(true);
|
||||
stubs.getAvatarSuggestionForUser.resolves({});
|
||||
|
||||
await _setUsername(userId, username, mockUser);
|
||||
|
||||
expect(stubs.setUserAvatar.called).to.be.false;
|
||||
});
|
||||
|
||||
it('should add user to room if inviteToken is present', async () => {
|
||||
const mockUser = { _id: userId, username: null, inviteToken: 'invite token' };
|
||||
stubs.validateUsername.returns(true);
|
||||
stubs.Users.findOneById.resolves(mockUser);
|
||||
stubs.checkUsernameAvailability.resolves(true);
|
||||
stubs.settings.get.withArgs('Accounts_SetDefaultAvatar').returns(true);
|
||||
stubs.getAvatarSuggestionForUser.resolves({ gravatar: { blob: 'blobData', contentType: 'image/png' } });
|
||||
stubs.Invites.findOneById.resolves({ rid: 'room id' });
|
||||
|
||||
await _setUsername(userId, username, mockUser);
|
||||
|
||||
expect(stubs.addUserToRoom.calledOnceWith('room id', mockUser)).to.be.true;
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { expect } from 'chai';
|
||||
import proxyquire from 'proxyquire';
|
||||
import sinon from 'sinon';
|
||||
|
||||
describe('validateUsername', () => {
|
||||
const getStub = sinon.stub();
|
||||
|
||||
const proxySettings = {
|
||||
settings: {
|
||||
get: getStub,
|
||||
},
|
||||
};
|
||||
|
||||
const { validateUsername } = proxyquire.noCallThru().load('../../../../../server/lib/users/validateUsername', {
|
||||
'../../settings': proxySettings,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
getStub.reset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore();
|
||||
});
|
||||
|
||||
describe('with default settings', () => {
|
||||
beforeEach(() => {
|
||||
getStub.withArgs('UTF8_User_Names_Validation').returns('[0-9a-zA-Z-_.]+');
|
||||
});
|
||||
|
||||
it('should return true for a valid username', () => {
|
||||
const result = validateUsername('valid_username.123');
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
|
||||
it('should return false for an invalid username containing special HTML tags', () => {
|
||||
const result = validateUsername('username<div>$</div>');
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
|
||||
it('should return false for an empty username', () => {
|
||||
const result = validateUsername('');
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
|
||||
it('should return false for a username with invalid characters', () => {
|
||||
const result = validateUsername('invalid*username!');
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
|
||||
it('should return true for a username with allowed special characters', () => {
|
||||
const result = validateUsername('username-_.');
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe('with custom regex settings', () => {
|
||||
beforeEach(() => {
|
||||
getStub.withArgs('UTF8_User_Names_Validation').returns('[a-zA-Z]+');
|
||||
});
|
||||
|
||||
it('should return true for a username matching the custom regex', () => {
|
||||
const result = validateUsername('ValidUsername');
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
|
||||
it('should return false for a username that does not match the custom regex', () => {
|
||||
const result = validateUsername('username123');
|
||||
expect(result).to.be.false;
|
||||
});
|
||||
});
|
||||
|
||||
describe('with null regex settings', () => {
|
||||
beforeEach(() => {
|
||||
getStub.withArgs('UTF8_User_Names_Validation').returns(null);
|
||||
});
|
||||
|
||||
it('should fallback to the default regex pattern if the settings value is null', () => {
|
||||
const result = validateUsername('username');
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
});
|
||||
|
||||
describe('with invalid regex settings', () => {
|
||||
beforeEach(() => {
|
||||
getStub.withArgs('UTF8_User_Names_Validation').returns('invalid[');
|
||||
});
|
||||
|
||||
it('should fallback to the default regex pattern if the settings value is invalid', () => {
|
||||
const result = validateUsername('username');
|
||||
expect(result).to.be.true;
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user