Skip to content

Modular logistics and supply chain operating system (LSOS)

test(console): cover the organization index and both 2FA settings controllers

Ronald A. Richardson9bc38e8be029
diff --git a/console/app/controllers/console/admin/organizations/index.js b/console/app/controllers/console/admin/organizations/index.js
index 6677eba1..ca9a769a 100644
--- a/console/app/controllers/console/admin/organizations/index.js
+++ b/console/app/controllers/console/admin/organizations/index.js
@@ -311,12 +311,21 @@ export default class ConsoleAdminOrganizationsController extends Controller {
await this.router.transitionTo('console');
this.session.manuallyAuthenticate(token);
this.notifications.info(`Now impersonating ${owner?.email || 'organization owner'}...`);
- window.location.reload();
+ this.reloadWindow();
} catch (error) {
this.notifications.serverError(error);
}
}
+ /* istanbul ignore next -- window.location.reload() cannot be stubbed: the HTML spec
+ makes every Location member an own, non-configurable property, so defineProperty
+ throws and calling it for real would reload the test runner. Extracted so callers can
+ be tested by replacing reloadWindow() on the instance, mirroring
+ InstallationService.reloadConsole(). */
+ reloadWindow() {
+ window.location.reload();
+ }
+
resolveBelongsTo(record) {
if (!record) {
return null;
diff --git a/console/tests/unit/controllers/console/account/auth-test.js b/console/tests/unit/controllers/console/account/auth-test.js
index 20c7aa87..b1c52d01 100644
--- a/console/tests/unit/controllers/console/account/auth-test.js
+++ b/console/tests/unit/controllers/console/account/auth-test.js
@@ -148,3 +148,179 @@ module('Unit | Controller | console/account/auth', function (hooks) {
assert.deepEqual(posts.at(-1), { path: 'users/two-fa', payload: { twoFaSettings: { enabled: true } } });
});
});
+
+module('Unit | Controller | console/account/auth | credentials and 2FA', function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.requests = [];
+ this.responses = { 'two-fa/config': { enabled: true }, 'users/two-fa': { enabled: true, method: 'sms' } };
+ this.getRejectsWith = null;
+ this.postRejectsWith = null;
+ this.passwordIsValid = true;
+ const context = this;
+
+ class FetchStub extends Service {
+ get(path) {
+ context.requests.push({ method: 'get', path });
+ return context.getRejectsWith ? Promise.reject(context.getRejectsWith) : Promise.resolve(context.responses[path]);
+ }
+ post(path, payload) {
+ context.requests.push({ method: 'post', path, payload });
+ return context.postRejectsWith ? Promise.reject(context.postRejectsWith) : Promise.resolve({ ok: true });
+ }
+ }
+ class NotificationsStub extends Service {
+ successes = [];
+ serverErrors = [];
+ success(message) {
+ this.successes.push(message);
+ }
+ serverError(error, fallback) {
+ this.serverErrors.push([error, fallback]);
+ }
+ }
+ class ModalsManagerStub extends Service {
+ shown = [];
+ show(name, options) {
+ this.shown.push({ name, options });
+ options.onValidated?.(context.passwordIsValid);
+ return Promise.resolve();
+ }
+ }
+ this.owner.register('service:fetch', FetchStub);
+ this.owner.register('service:notifications', NotificationsStub);
+ this.owner.register('service:modals-manager', ModalsManagerStub);
+
+ this.build = async () => {
+ const controller = this.owner.lookup('controller:console/account/auth');
+ await controller.loadSystemTwoFaConfig.last;
+ await controller.loadUserTwoFaSettings.last;
+ return controller;
+ };
+ this.notifications = () => this.owner.lookup('service:notifications');
+ });
+
+ test('it loads the system config and the user 2FA settings on construction', async function (assert) {
+ const controller = await this.build();
+
+ assert.deepEqual(this.requests.map((request) => request.path).sort(), ['two-fa/config', 'users/two-fa']);
+ assert.true(controller.isSystemTwoFaEnabled);
+ assert.deepEqual(controller.twoFaSettings, this.responses['users/two-fa']);
+ });
+
+ test('failed 2FA loads are reported', async function (assert) {
+ const failure = new Error('two-fa unavailable');
+ this.getRejectsWith = failure;
+ await this.build();
+
+ assert.deepEqual(this.notifications().serverErrors, [
+ [failure, undefined],
+ [failure, undefined],
+ ]);
+ });
+
+ test('changeEmail posts the new address and clears the form', async function (assert) {
+ const controller = await this.build();
+ controller.newEmail = '[email protected]';
+ controller.currentPassword = 'secret';
+
+ await controller.changeEmail.perform();
+
+ assert.deepEqual(this.requests.at(-1), { method: 'post', path: 'users/change-email', payload: { email: '[email protected]', password: 'secret' } });
+ assert.strictEqual(controller.newEmail, undefined, 'the form is cleared');
+ assert.strictEqual(controller.currentPassword, undefined);
+ assert.strictEqual(this.notifications().successes.length, 1);
+ });
+
+ test('changeEmail prevents a form submission from navigating', async function (assert) {
+ const controller = await this.build();
+ const event = new Event('submit', { cancelable: true });
+
+ await controller.changeEmail.perform(event);
+
+ assert.true(event.defaultPrevented);
+ });
+
+ test('a failed email change is reported with its own fallback message', async function (assert) {
+ const failure = new Error('address already in use');
+ this.postRejectsWith = failure;
+ const controller = await this.build();
+
+ await controller.changeEmail.perform();
+
+ assert.deepEqual(this.notifications().serverErrors.at(-1), [failure, 'Failed to request email change.']);
+ });
+
+ test('changePassword validates the current password before changing it', async function (assert) {
+ const controller = await this.build();
+ controller.newPassword = 'new-secret';
+ controller.newConfirmPassword = 'new-secret';
+
+ await controller.changePassword.perform();
+
+ assert.strictEqual(this.owner.lookup('service:modals-manager').shown[0].name, 'modals/validate-password');
+ assert.deepEqual(this.requests.at(-1), {
+ method: 'post',
+ path: 'users/change-password',
+ payload: { password: 'new-secret', password_confirmation: 'new-secret' },
+ });
+ assert.deepEqual(this.notifications().successes, ['Password change successfully.']);
+ assert.strictEqual(controller.newPassword, undefined, 'the form is cleared');
+ });
+
+ test('a failed password validation abandons the change', async function (assert) {
+ this.passwordIsValid = false;
+ const controller = await this.build();
+ controller.newPassword = 'new-secret';
+ controller.newConfirmPassword = 'new-secret';
+
+ await controller.changePassword.perform();
+
+ assert.notOk(
+ this.requests.some((request) => request.path === 'users/change-password'),
+ 'nothing is submitted'
+ );
+ assert.strictEqual(controller.newPassword, undefined, 'the form is cleared anyway');
+ assert.deepEqual(this.notifications().successes, []);
+ });
+
+ test('a failed password change is reported with its own fallback message', async function (assert) {
+ const failure = new Error('password too weak');
+ const controller = await this.build();
+ this.postRejectsWith = failure;
+
+ await controller.changePassword.perform();
+
+ assert.deepEqual(this.notifications().serverErrors.at(-1), [failure, 'Failed to change password.']);
+ assert.strictEqual(controller.newPassword, undefined);
+ });
+
+ test('the 2FA toggles patch one field each and saving posts them', async function (assert) {
+ const controller = await this.build();
+
+ controller.onTwoFaToggled(false);
+ assert.false(controller.twoFaSettings.enabled);
+
+ controller.onTwoFaMethodSelected('email');
+ assert.strictEqual(controller.twoFaSettings.method, 'email');
+ assert.false(controller.twoFaSettings.enabled, 'the earlier change survives');
+
+ controller.saveTwoFactorAuthSettings();
+ await controller.saveUserTwoFaSettings.last;
+
+ assert.deepEqual(this.requests.at(-1), { method: 'post', path: 'users/two-fa', payload: { twoFaSettings: controller.twoFaSettings } });
+ assert.deepEqual(this.notifications().successes, ['2FA Settings saved successfully.']);
+ });
+
+ test('a failed 2FA save is reported', async function (assert) {
+ const controller = await this.build();
+ this.postRejectsWith = new Error('save rejected');
+
+ controller.saveTwoFactorAuthSettings();
+ await controller.saveUserTwoFaSettings.last;
+
+ assert.strictEqual(this.notifications().serverErrors.length, 1);
+ assert.deepEqual(this.notifications().successes, []);
+ });
+});
diff --git a/console/tests/unit/controllers/console/admin/organizations/index-test.js b/console/tests/unit/controllers/console/admin/organizations/index-test.js
index 1edc6940..9e0632f6 100644
--- a/console/tests/unit/controllers/console/admin/organizations/index-test.js
+++ b/console/tests/unit/controllers/console/admin/organizations/index-test.js
@@ -277,3 +277,249 @@ module('Unit | Controller | console/admin/organizations/index', function (hooks)
}
});
});
+
+module('Unit | Controller | console/admin/organizations/index | actions', function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.posted = [];
+ this.postRejectsWith = null;
+ const context = this;
+
+ class FetchStub extends Service {
+ post(path, payload) {
+ context.posted.push({ path, payload });
+ return context.postRejectsWith ? Promise.reject(context.postRejectsWith) : Promise.resolve({ token: 'impersonation-token' });
+ }
+ }
+ class SessionStub extends Service {
+ authenticated = [];
+ manuallyAuthenticate(token) {
+ this.authenticated.push(token);
+ }
+ }
+ class NotificationsStub extends Service {
+ errors = [];
+ infos = [];
+ successes = [];
+ serverErrors = [];
+ error(message) {
+ this.errors.push(message);
+ }
+ info(message) {
+ this.infos.push(message);
+ }
+ success(message) {
+ this.successes.push(message);
+ }
+ serverError(error) {
+ this.serverErrors.push(error);
+ }
+ }
+ class CrudStub extends Service {
+ exported = [];
+ export(type, options) {
+ this.exported.push({ type, options });
+ }
+ }
+ this.owner.register('service:fetch', FetchStub);
+ this.owner.register('service:session', SessionStub);
+ this.owner.register('service:notifications', NotificationsStub);
+ this.owner.register('service:crud', CrudStub);
+
+ this.build = () => {
+ const controller = this.owner.lookup('controller:console/admin/organizations/index');
+ this.transitions = [];
+ Object.defineProperty(controller.router, 'transitionTo', {
+ configurable: true,
+ value: (...args) => {
+ this.transitions.push(args);
+ return Promise.resolve();
+ },
+ });
+ this.reloads = 0;
+ Object.defineProperty(controller, 'reloadWindow', { configurable: true, value: () => this.reloads++ });
+ return controller;
+ };
+ this.notifications = () => this.owner.lookup('service:notifications');
+ });
+
+ test('search stores the term and returns to the first page', function (assert) {
+ const controller = this.build();
+ controller.page = 5;
+
+ controller.search({ target: { value: 'fleetbase' } });
+ assert.strictEqual(controller.query, 'fleetbase');
+ assert.strictEqual(controller.page, 1);
+
+ controller.search({ target: {} });
+ assert.strictEqual(controller.query, '', 'a cleared box searches for nothing');
+ });
+
+ test('the row actions navigate to the organization and its activity', function (assert) {
+ const controller = this.build();
+
+ controller.goToCompany({ public_id: 'company_1' });
+ controller.openActivity({ public_id: 'company_1' });
+
+ assert.deepEqual(this.transitions, [
+ ['console.admin.organizations.details', 'company_1'],
+ ['console.admin.organizations.details.activity', 'company_1'],
+ ]);
+ });
+
+ test('resolveBelongsTo unwraps a loaded owner and withholds an unloaded one', function (assert) {
+ const controller = this.build();
+ const record = { id: 'user_1' };
+
+ assert.strictEqual(controller.resolveBelongsTo(null), null);
+ assert.strictEqual(controller.resolveBelongsTo({ content: record }), record, 'a resolved proxy yields its content');
+ assert.strictEqual(controller.resolveBelongsTo(record), record, 'a plain record is used as-is');
+ assert.strictEqual(controller.resolveBelongsTo({ isPending: true }), null);
+ assert.strictEqual(controller.resolveBelongsTo({ isFulfilled: false }), null);
+ assert.strictEqual(controller.resolveBelongsTo({ then: () => {} }), null);
+ });
+
+ test('impersonateOwner refuses when the organization has no owner', async function (assert) {
+ const controller = this.build();
+
+ await controller.impersonateOwner({ name: 'Ownerless Co' });
+
+ assert.deepEqual(this.notifications().errors, ['This organization does not have an owner to impersonate.']);
+ assert.deepEqual(this.posted, [], 'nothing is requested');
+ });
+
+ test('impersonateOwner switches into the owner session and reloads', async function (assert) {
+ const controller = this.build();
+
+ await controller.impersonateOwner({ owner: { content: { id: 'user_1', email: '[email protected]' } } });
+
+ assert.deepEqual(this.posted, [{ path: 'auth/impersonate', payload: { user: 'user_1' } }]);
+ assert.deepEqual(this.transitions, [['console']]);
+ assert.deepEqual(this.owner.lookup('service:session').authenticated, ['impersonation-token']);
+ assert.deepEqual(this.notifications().infos, ['Now impersonating [email protected]...']);
+ assert.strictEqual(this.reloads, 1, 'the window is reloaded into the new session');
+ });
+
+ test('impersonateOwner falls back to the owner uuid on the organization', async function (assert) {
+ const controller = this.build();
+
+ await controller.impersonateOwner({ owner_uuid: 'user_2' });
+
+ assert.deepEqual(this.posted, [{ path: 'auth/impersonate', payload: { user: 'user_2' } }]);
+ assert.deepEqual(this.notifications().infos, ['Now impersonating organization owner...'], 'with no email it says so generically');
+ });
+
+ test('a failed impersonation is reported and nothing reloads', async function (assert) {
+ const failure = new Error('not permitted');
+ this.postRejectsWith = failure;
+ const controller = this.build();
+
+ await controller.impersonateOwner({ owner_uuid: 'user_2' });
+
+ assert.deepEqual(this.notifications().serverErrors, [failure]);
+ assert.strictEqual(this.reloads, 0);
+ });
+
+ test('copyId writes to the clipboard and reports what was copied', function (assert) {
+ const controller = this.build();
+ const written = [];
+ const original = navigator.clipboard;
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: (value) => written.push(value) } });
+
+ try {
+ controller.copyId('company_1', 'Public ID');
+ controller.copyId('uuid-1');
+ controller.copyId(null);
+ } finally {
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: original });
+ }
+
+ assert.deepEqual(written, ['company_1', 'uuid-1'], 'an empty value is not copied');
+ assert.deepEqual(this.notifications().successes, ['Public ID copied to clipboard.', 'ID copied to clipboard.'], 'the label defaults to ID');
+ });
+
+ test('exportOrganization exports the selected rows, or all of them', function (assert) {
+ const controller = this.build();
+ const crud = this.owner.lookup('service:crud');
+
+ controller.exportOrganization();
+ assert.deepEqual(crud.exported.at(-1), { type: 'companies', options: { params: { selections: [] } } }, 'no table means no selection');
+
+ controller.table = { selectedRows: [{ id: 'a' }, { id: 'b' }] };
+ controller.exportOrganization();
+ assert.deepEqual(crud.exported.at(-1), { type: 'companies', options: { params: { selections: ['a', 'b'] } } });
+ });
+
+ test('each saved view sets its own filter and clears the others', function (assert) {
+ const controller = this.build();
+ controller.page = 3;
+
+ controller.applySavedView('needs_attention');
+ assert.strictEqual(controller.needs_attention, 1);
+ assert.strictEqual(controller.page, 1, 'paging restarts');
+
+ controller.applySavedView('missing_owner');
+ assert.strictEqual(controller.missing_owner, 1);
+ assert.strictEqual(controller.needs_attention, null, 'the previous view is cleared');
+
+ controller.applySavedView('incomplete_onboarding');
+ assert.false(controller.onboarding_completed);
+
+ controller.applySavedView('inactive_status');
+ assert.strictEqual(controller.inactive_status, 1);
+ assert.strictEqual(controller.onboarding_completed, null);
+
+ controller.applySavedView('not-a-view');
+ assert.strictEqual(controller.inactive_status, null, 'an unknown view just clears everything');
+ });
+
+ test('clearSavedView drops every filter and returns to the first page', function (assert) {
+ const controller = this.build();
+ controller.applySavedView('needs_attention');
+ controller.page = 4;
+
+ controller.clearSavedView();
+
+ assert.strictEqual(controller.needs_attention, null);
+ assert.strictEqual(controller.missing_owner, null);
+ assert.strictEqual(controller.inactive_status, null);
+ assert.strictEqual(controller.onboarding_completed, null);
+ assert.strictEqual(controller.page, 1);
+ });
+
+ test('the toolbar offers the saved views and an export action', function (assert) {
+ const controller = this.build();
+ const [views, exportButton] = controller.actionButtons;
+
+ assert.deepEqual(
+ views.items.filter((item) => item.label).map((item) => item.label),
+ ['Needs Attention', 'Missing Owner', 'Incomplete Onboarding', 'Inactive Status', 'Clear View']
+ );
+ assert.strictEqual(exportButton.onClick, controller.exportOrganization);
+ assert.deepEqual(
+ controller.bulkActions.map((action) => action.label),
+ ['Export selected']
+ );
+
+ views.items[0].onClick();
+ assert.strictEqual(controller.needs_attention, 1, 'the menu item applies its view');
+ });
+
+ test('the row dropdown copies the public id and uuid through copyId', function (assert) {
+ const controller = this.build();
+ const written = [];
+ const original = navigator.clipboard;
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: (value) => written.push(value) } });
+ const actions = controller.columns.at(-1).actions;
+
+ try {
+ actions.find((action) => action.label === 'Copy Public ID').fn({ public_id: 'company_1', uuid: 'uuid-1' });
+ actions.find((action) => action.label === 'Copy UUID').fn({ public_id: 'company_1', uuid: 'uuid-1' });
+ } finally {
+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: original });
+ }
+
+ assert.deepEqual(written, ['company_1', 'uuid-1']);
+ });
+});
diff --git a/console/tests/unit/controllers/console/settings/two-fa-test.js b/console/tests/unit/controllers/console/settings/two-fa-test.js
index d56f2c84..58ca6e04 100644
--- a/console/tests/unit/controllers/console/settings/two-fa-test.js
+++ b/console/tests/unit/controllers/console/settings/two-fa-test.js
@@ -31,3 +31,108 @@ module('Unit | Controller | console/settings/two-fa', function (hooks) {
assert.true(controller.twoFaSettings.enforced);
});
});
+
+module('Unit | Controller | console/settings/two-fa | loading and saving', function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.requests = [];
+ this.responses = {
+ 'two-fa/config': { enabled: true },
+ 'companies/two-fa': { enabled: true, enforced: true, method: 'email' },
+ 'users/two-fa': { enabled: false, method: 'sms' },
+ };
+ this.postRejectsWith = null;
+ const context = this;
+
+ class FetchStub extends Service {
+ get(path) {
+ context.requests.push({ method: 'get', path });
+ return Promise.resolve(context.responses[path]);
+ }
+ post(path, payload) {
+ context.requests.push({ method: 'post', path, payload });
+ return context.postRejectsWith ? Promise.reject(context.postRejectsWith) : Promise.resolve({ ok: true });
+ }
+ }
+ class NotificationsStub extends Service {
+ successes = [];
+ serverErrors = [];
+ success(message) {
+ this.successes.push(message);
+ }
+ serverError(error) {
+ this.serverErrors.push(error);
+ }
+ }
+ this.owner.register('service:fetch', FetchStub);
+ this.owner.register('service:notifications', NotificationsStub);
+
+ this.build = async () => {
+ const controller = this.owner.lookup('controller:console/settings/two-fa');
+ await controller.loadSystemTwoFaConfig.last;
+ await controller.loadCompanyTwoFaSettings.last;
+ await controller.loadUserTwoFaSettings.last;
+ return controller;
+ };
+ this.notifications = () => this.owner.lookup('service:notifications');
+ });
+
+ test('it loads the system, company and user settings on construction', async function (assert) {
+ const controller = await this.build();
+
+ assert.deepEqual(this.requests.map((request) => request.path).sort(), ['companies/two-fa', 'two-fa/config', 'users/two-fa'], 'all three sources are consulted');
+ assert.true(controller.isSystemTwoFaEnabled, 'the system flag comes from the config');
+ assert.true(controller.isTwoFaEnforced, 'enforcement comes from the company');
+ assert.false(controller.isUserTwoFaEnabled, 'the user flag comes from their own settings');
+ assert.ok(controller.methods.length > 0);
+ });
+
+ test('empty responses leave every flag at its default', async function (assert) {
+ this.responses = {};
+ const controller = await this.build();
+
+ assert.false(controller.isSystemTwoFaEnabled);
+ assert.false(controller.isTwoFaEnforced);
+ assert.false(controller.isUserTwoFaEnabled);
+ assert.deepEqual(controller.twoFaSettings, {});
+ assert.deepEqual(controller.twoFaConfig, {});
+ });
+
+ test('each toggle patches one field and leaves the rest alone', async function (assert) {
+ const controller = await this.build();
+
+ controller.onTwoFaToggled(true);
+ assert.true(controller.twoFaSettings.enabled);
+
+ controller.onTwoFaMethodSelected('authenticator');
+ assert.strictEqual(controller.twoFaSettings.method, 'authenticator');
+ assert.true(controller.twoFaSettings.enabled, 'the earlier change survives');
+
+ controller.onTwoFaEnforceToggled(true);
+ assert.true(controller.twoFaSettings.enforced);
+ assert.strictEqual(controller.twoFaSettings.method, 'authenticator');
+ });
+
+ test('saveTwoFactor posts the settings for the organization', async function (assert) {
+ const controller = await this.build();
+
+ controller.saveTwoFactor();
+ await controller.saveTwoFactorSettingsForCompany.last;
+
+ assert.deepEqual(this.requests.at(-1), { method: 'post', path: 'companies/two-fa', payload: { twoFaSettings: controller.twoFaSettings } });
+ assert.deepEqual(this.notifications().successes, ['2FA Settings saved for organization successfully.']);
+ });
+
+ test('a failed save is reported', async function (assert) {
+ const failure = new Error('save rejected');
+ this.postRejectsWith = failure;
+ const controller = await this.build();
+
+ controller.saveTwoFactor();
+ await controller.saveTwoFactorSettingsForCompany.last;
+
+ assert.deepEqual(this.notifications().serverErrors, [failure]);
+ assert.deepEqual(this.notifications().successes, []);
+ });
+});