Skip to content

Modular logistics and supply chain operating system (LSOS)

fix(console): return the invite and impersonation flows so callers can await them

Ronald A. Richardson82d8695db4a4
diff --git a/console/app/controllers/console/admin/organizations/index/users.js b/console/app/controllers/console/admin/organizations/index/users.js
index 388b2ab8..d1830aa5 100644
--- a/console/app/controllers/console/admin/organizations/index/users.js
+++ b/console/app/controllers/console/admin/organizations/index/users.js
@@ -130,7 +130,10 @@ export default class ConsoleAdminOrganizationsIndexUsersController extends Contr
await this.router.transitionTo('console');
this.session.manuallyAuthenticate(token);
this.notifications.info(`Now impersonating ${user.email}...`);
- later(
+
+ // Handed back so the caller can cancel the pending reload; the same timer on
+ // ImpersonatorTray was unreachable once scheduled.
+ return later(
this,
() => {
window.location.reload();
diff --git a/console/app/controllers/invite/for-user.js b/console/app/controllers/invite/for-user.js
index 3f820839..bf077487 100644
--- a/console/app/controllers/invite/for-user.js
+++ b/console/app/controllers/invite/for-user.js
@@ -17,7 +17,9 @@ export default class InviteForUserController extends Controller {
this.isLoading = true;
- this.fetch
+ // Returned so callers can await the whole flow; without this the action resolves
+ // before the invite has actually been accepted.
+ return this.fetch
.post('users/accept-company-invite', { code })
.then((response) => {
this.session.manuallyAuthenticate(response.token);
diff --git a/console/tests/unit/controllers/console/account/index-test.js b/console/tests/unit/controllers/console/account/index-test.js
index d046206a..97e27662 100644
--- a/console/tests/unit/controllers/console/account/index-test.js
+++ b/console/tests/unit/controllers/console/account/index-test.js
@@ -22,3 +22,130 @@ module('Unit | Controller | console/account/index', function (hooks) {
assert.deepEqual(controller.timezones, ['UTC', 'Europe/Berlin']);
});
});
+
+module('Unit | Controller | console/account/index | profile', function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.uploads = [];
+ this.getResponse = ['UTC', 'America/New_York'];
+ this.getRejectsWith = null;
+ this.saveRejectsWith = null;
+ const context = this;
+
+ class FetchStub extends Service {
+ get(path) {
+ context.requestedPath = path;
+ return context.getRejectsWith ? Promise.reject(context.getRejectsWith) : Promise.resolve(context.getResponse);
+ }
+ uploadFile = {
+ perform: (file, meta, onUploaded) => {
+ context.uploads.push({ file, meta });
+ return onUploaded({ id: 'file_1', url: 'https://cdn.example.com/avatar.png' });
+ },
+ };
+ }
+ 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.saved = 0;
+ this.user = {
+ id: 'user_1',
+ slug: 'ron',
+ company_uuid: 'co_1',
+ setProperties(properties) {
+ Object.assign(this, properties);
+ },
+ save: () => {
+ context.saved++;
+ return context.saveRejectsWith ? Promise.reject(context.saveRejectsWith) : Promise.resolve(context.user);
+ },
+ };
+
+ this.build = () => {
+ const controller = this.owner.lookup('controller:console/account/index');
+ // `user` is an alias onto the currentUser service, so set the backing property.
+ controller.currentUser.set('user', this.user);
+ return controller;
+ };
+ this.notifications = () => this.owner.lookup('service:notifications');
+ });
+
+ test('it loads the timezone list on construction', async function (assert) {
+ const controller = this.build();
+ await controller.loadTimezones.last;
+
+ assert.strictEqual(this.requestedPath, 'lookup/timezones');
+ assert.deepEqual(controller.timezones, this.getResponse);
+ });
+
+ test('a failed timezone load leaves the list empty without a user-facing error', async function (assert) {
+ this.getRejectsWith = new Error('lookup unavailable');
+ const controller = this.build();
+ await controller.loadTimezones.last;
+
+ assert.deepEqual(controller.timezones, [], 'nothing to choose from');
+ assert.deepEqual(this.notifications().serverErrors, [], 'a missing lookup is not worth interrupting the user');
+ });
+
+ test('uploadNewPhoto files the avatar under the company and saves the user', async function (assert) {
+ const controller = this.build();
+ await controller.loadTimezones.last;
+
+ await controller.uploadNewPhoto({ name: 'avatar.png' });
+
+ assert.deepEqual(this.uploads[0].meta, {
+ path: 'uploads/co_1/users/ron',
+ subject_uuid: 'user_1',
+ subject_type: 'user',
+ type: 'user_avatar',
+ resize: 'md',
+ });
+ assert.strictEqual(this.user.avatar_uuid, 'file_1');
+ assert.strictEqual(this.user.avatar_url, 'https://cdn.example.com/avatar.png');
+ assert.strictEqual(this.saved, 1, 'the new avatar is persisted');
+ });
+
+ test('saveProfile saves the user and refreshes the signed-in record', async function (assert) {
+ const controller = this.build();
+ await controller.loadTimezones.last;
+
+ await controller.saveProfile.perform();
+
+ assert.strictEqual(this.saved, 1);
+ assert.deepEqual(this.notifications().successes, ['Profile changes saved.']);
+ assert.strictEqual(controller.currentUser.user, this.user, 'the saved record replaces the cached one');
+ });
+
+ test('saveProfile prevents a form submission from navigating', async function (assert) {
+ const controller = this.build();
+ await controller.loadTimezones.last;
+ const event = new Event('submit', { cancelable: true });
+
+ await controller.saveProfile.perform(event);
+
+ assert.true(event.defaultPrevented);
+ });
+
+ test('a failed profile save is reported and success is not', async function (assert) {
+ const failure = new Error('save rejected');
+ this.saveRejectsWith = failure;
+ const controller = this.build();
+ await controller.loadTimezones.last;
+
+ await controller.saveProfile.perform();
+
+ assert.deepEqual(this.notifications().serverErrors, [failure]);
+ assert.deepEqual(this.notifications().successes, []);
+ });
+});
diff --git a/console/tests/unit/controllers/console/admin/organizations/index/users-test.js b/console/tests/unit/controllers/console/admin/organizations/index/users-test.js
index 11139dfa..02d553a0 100644
--- a/console/tests/unit/controllers/console/admin/organizations/index/users-test.js
+++ b/console/tests/unit/controllers/console/admin/organizations/index/users-test.js
@@ -1,5 +1,7 @@
import { module, test } from 'qunit';
import { setupTest } from '@fleetbase/console/tests/helpers';
+import Service from '@ember/service';
+import { cancel } from '@ember/runloop';
module('Unit | Controller | console/admin/organizations/index/users', function (hooks) {
setupTest(hooks);
@@ -51,3 +53,149 @@ module('Unit | Controller | console/admin/organizations/index/users', function (
assert.strictEqual(transitioned, 'console.admin.organizations.index');
});
});
+
+module('Unit | Controller | console/admin/organizations/index/users | 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 {
+ infos = [];
+ serverErrors = [];
+ info(message) {
+ this.infos.push(message);
+ }
+ serverError(error) {
+ this.serverErrors.push(error);
+ }
+ }
+ class ModalsManagerStub extends Service {
+ shown = [];
+ show(name, options) {
+ this.shown.push({ name, options });
+ }
+ }
+
+ this.owner.register('service:fetch', FetchStub);
+ this.owner.register('service:session', SessionStub);
+ this.owner.register('service:notifications', NotificationsStub);
+ this.owner.register('service:modals-manager', ModalsManagerStub);
+
+ this.build = () => {
+ const controller = this.owner.lookup('controller:console/admin/organizations/index/users');
+ this.transitions = [];
+ Object.defineProperty(controller.router, 'transitionTo', {
+ configurable: true,
+ value: (routeName) => {
+ this.transitions.push(routeName);
+ return Promise.resolve(routeName);
+ },
+ });
+ return controller;
+ };
+ this.notifications = () => this.owner.lookup('service:notifications');
+ });
+
+ test('impersonateUser swaps the session and announces who is being impersonated', async function (assert) {
+ const controller = this.build();
+
+ const timer = await controller.impersonateUser({ id: 'user_1', email: '[email protected]' });
+ // The handler schedules a window.location.reload(); cancel it before it fires
+ // against the test runner.
+ cancel(timer);
+
+ assert.deepEqual(this.posted, [{ path: 'auth/impersonate', payload: { user: 'user_1' } }]);
+ assert.deepEqual(this.transitions, ['console'], 'the impersonator is dropped into the console');
+ assert.deepEqual(this.owner.lookup('service:session').authenticated, ['impersonation-token']);
+ assert.deepEqual(this.notifications().infos, ['Now impersonating [email protected]...']);
+ assert.ok(timer, 'a reload was scheduled');
+ });
+
+ test('a failed impersonation is reported and nothing is reloaded', async function (assert) {
+ const failure = new Error('not permitted');
+ this.postRejectsWith = failure;
+ const controller = this.build();
+
+ const timer = await controller.impersonateUser({ id: 'user_1', email: '[email protected]' });
+
+ assert.strictEqual(timer, undefined, 'no reload is scheduled');
+ assert.deepEqual(this.notifications().serverErrors, [failure]);
+ assert.deepEqual(this.transitions, []);
+ });
+
+ test('changeUserPassword opens the password modal for that user', function (assert) {
+ const controller = this.build();
+ const user = { id: 'user_1' };
+
+ controller.changeUserPassword(user);
+
+ const { name, options } = this.owner.lookup('service:modals-manager').shown[0];
+ assert.strictEqual(name, 'modals/change-user-password');
+ assert.strictEqual(options.user, user);
+ assert.true(options.keepOpen, 'the modal stays up until it is dismissed');
+ });
+
+ test('search stores the term and returns to the first page', function (assert) {
+ const controller = this.build();
+ controller.nestedPage = 4;
+
+ controller.search({ target: { value: 'ron' } });
+
+ assert.strictEqual(controller.nestedQuery, 'ron');
+ assert.strictEqual(controller.nestedPage, 1, 'paging restarts for a new search');
+
+ controller.nestedPage = 3;
+ controller.search({ target: {} });
+
+ assert.strictEqual(controller.nestedQuery, '', 'a cleared box searches for nothing');
+ assert.strictEqual(controller.nestedPage, 1);
+ });
+
+ test('onPressClose closes the overlay when one is registered, then leaves the route', function (assert) {
+ const controller = this.build();
+ let closed = 0;
+
+ controller.setOverlayContext({ close: () => closed++ });
+ controller.onPressClose();
+
+ assert.strictEqual(closed, 1, 'the overlay is dismissed first');
+ assert.deepEqual(this.transitions, ['console.admin.organizations.index']);
+ });
+
+ test('onPressClose still leaves the route with no overlay registered', function (assert) {
+ const controller = this.build();
+
+ controller.onPressClose();
+ controller.setOverlayContext({});
+ controller.onPressClose();
+
+ assert.deepEqual(this.transitions, ['console.admin.organizations.index', 'console.admin.organizations.index'], 'both paths navigate');
+ });
+
+ test('the user table offers impersonate and change-password actions', function (assert) {
+ const controller = this.build();
+ const actionsColumn = controller.columns.at(-1);
+
+ assert.deepEqual(
+ actionsColumn.actions.map((entry) => entry.label),
+ ['Impersonate', 'Change Password']
+ );
+ assert.strictEqual(actionsColumn.actions[0].fn, controller.impersonateUser);
+ assert.strictEqual(actionsColumn.actions[1].fn, controller.changeUserPassword);
+ });
+});
diff --git a/console/tests/unit/controllers/invite/for-user-test.js b/console/tests/unit/controllers/invite/for-user-test.js
index a6b2ca83..525ac9e3 100644
--- a/console/tests/unit/controllers/invite/for-user-test.js
+++ b/console/tests/unit/controllers/invite/for-user-test.js
@@ -41,3 +41,147 @@ module('Unit | Controller | invite/for-user', function (hooks) {
assert.notOk(controller.isLoading, 'loading flag is reset');
});
});
+
+module('Unit | Controller | invite/for-user | accepting', function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.posted = [];
+ this.postResponse = { token: 'invite-token' };
+ 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(context.postResponse);
+ }
+ }
+ class SessionStub extends Service {
+ authenticated = [];
+ manuallyAuthenticate(token) {
+ this.authenticated.push(token);
+ }
+ }
+ class NotificationsStub extends Service {
+ successes = [];
+ serverErrors = [];
+ success(message) {
+ this.successes.push(message);
+ }
+ serverError(error) {
+ this.serverErrors.push(error);
+ }
+ }
+ class ModalsManagerStub extends Service {
+ shown = [];
+ show(name, options) {
+ this.shown.push({ name, options });
+ }
+ }
+
+ this.owner.register('service:fetch', FetchStub);
+ this.owner.register('service:session', SessionStub);
+ this.owner.register('service:notifications', NotificationsStub);
+ this.owner.register('service:modals-manager', ModalsManagerStub);
+
+ this.build = () => {
+ const controller = this.owner.lookup('controller:invite/for-user');
+ controller.code = 'INVITE-1';
+ this.transitions = [];
+ Object.defineProperty(controller.router, 'transitionTo', {
+ configurable: true,
+ value: (routeName) => {
+ this.transitions.push(routeName);
+ return Promise.resolve(routeName);
+ },
+ });
+ return controller;
+ };
+ this.notifications = () => this.owner.lookup('service:notifications');
+ this.modals = () => this.owner.lookup('service:modals-manager');
+ });
+
+ test('accepting the invite authenticates the new member and opens the console', async function (assert) {
+ const controller = this.build();
+
+ await controller.acceptInvite();
+
+ assert.deepEqual(this.posted, [{ path: 'users/accept-company-invite', payload: { code: 'INVITE-1' } }]);
+ assert.deepEqual(this.owner.lookup('service:session').authenticated, ['invite-token']);
+ assert.deepEqual(this.notifications().successes, ['Invitation accepted, welcome to Fleetbase!']);
+ assert.deepEqual(this.transitions, ['console']);
+ assert.false(controller.isLoading, 'the busy flag is cleared');
+ assert.deepEqual(this.modals().shown, [], 'an existing password is left alone');
+ });
+
+ test('a member who has no password yet is asked to set one', async function (assert) {
+ this.postResponse = { token: 'invite-token', needs_password: true };
+ const controller = this.build();
+
+ await controller.acceptInvite();
+
+ assert.strictEqual(this.modals().shown[0].name, 'modals/set-password');
+ assert.deepEqual(this.transitions, ['console'], 'they still land in the console first');
+ });
+
+ test('a rejected invite is reported and the busy flag is cleared', async function (assert) {
+ const failure = new Error('invite expired');
+ this.postRejectsWith = failure;
+ const controller = this.build();
+
+ await controller.acceptInvite();
+
+ assert.deepEqual(this.notifications().serverErrors, [failure]);
+ assert.false(controller.isLoading);
+ assert.deepEqual(this.transitions, []);
+ });
+
+ test('the set-password modal cannot be dismissed without setting one', function (assert) {
+ this.build().setPassword();
+
+ const { options } = this.modals().shown[0];
+ assert.strictEqual(options.title, 'Set a new password');
+ assert.false(options.closeButton, 'there is no close button');
+ assert.false(options.backdropClose, 'and clicking away does nothing');
+ assert.true(options.keepOpen);
+ assert.true(options.hideDeclineButton);
+ });
+
+ test('confirming the set-password modal submits both fields', async function (assert) {
+ const controller = this.build();
+ controller.setPassword();
+ const calls = [];
+ const modal = {
+ startLoading: () => calls.push('startLoading'),
+ stopLoading: () => calls.push('stopLoading'),
+ done: () => calls.push('done'),
+ getOptions: (keys) => ({ password: 'secret', password_confirmation: 'secret', keys }),
+ };
+
+ await this.modals().shown[0].options.confirm(modal);
+
+ assert.strictEqual(this.posted.at(-1).path, 'users/set-password');
+ assert.deepEqual(this.posted.at(-1).payload.keys, ['password', 'password_confirmation'], 'both fields are read off the modal');
+ assert.deepEqual(calls, ['startLoading', 'done']);
+ });
+
+ test('a failed password submission leaves the modal open', async function (assert) {
+ const failure = new Error('password too weak');
+ const controller = this.build();
+ controller.setPassword();
+ this.postRejectsWith = failure;
+ const calls = [];
+ const modal = {
+ startLoading: () => calls.push('startLoading'),
+ stopLoading: () => calls.push('stopLoading'),
+ done: () => calls.push('done'),
+ getOptions: () => ({}),
+ };
+
+ await this.modals().shown[0].options.confirm(modal);
+
+ assert.deepEqual(this.notifications().serverErrors, [failure]);
+ assert.deepEqual(calls, ['startLoading', 'stopLoading'], 'the user can try again');
+ });
+});