Skip to content

Modular logistics and supply chain operating system (LSOS)

fix(console): resolve the three flagged items — dead resolver, session, resend guards

Ronald A. Richardson9ac580e527c9
diff --git a/console/app/components/onboarding/verify-email.js b/console/app/components/onboarding/verify-email.js
index a2d0deaa..a5050110 100644
--- a/console/app/components/onboarding/verify-email.js
+++ b/console/app/components/onboarding/verify-email.js
@@ -24,7 +24,7 @@ export default class OnboardingVerifyEmailComponent extends Component {
this.code = this.urlSearchParams.get('code');
this.session = this.args.context.get('session') ?? this.urlSearchParams.get('session');
this.initialized = true;
- this.verification.start();
+ this.verification.start({ session: this.session });
}
@task *verify(event) {
diff --git a/console/app/models/report.js b/console/app/models/report.js
index 0637551a..69dd0da6 100644
--- a/console/app/models/report.js
+++ b/console/app/models/report.js
@@ -2,6 +2,7 @@ import Model, { attr } from '@ember-data/model';
import { computed } from '@ember/object';
import { isArray } from '@ember/array';
import { getOwner } from '@ember/application';
+import fleetbaseApiFetch from '@fleetbase/ember-core/utils/fleetbase-api-fetch';
import { isPresent } from '@ember/utils';
import { format, formatDistanceToNow } from 'date-fns';
@@ -357,71 +358,49 @@ export default class ReportModel extends Model {
return response;
}
- // Static methods for direct query operations
+ /**
+ * Ad-hoc query operations that are not tied to a saved report.
+ *
+ * These are static, so there is no container to resolve a service from — getOwner() on
+ * the class itself returns undefined, which meant every one of these threw the moment it
+ * was called. fleetbaseApiFetch needs no owner: it builds the URL from config and reads
+ * the bearer token out of the persisted session, so it works from a static context.
+ */
static async executeQuery(queryConfig) {
- const owner = getOwner(this);
- const fetch = owner.lookup('service:fetch');
-
- const response = await fetch.post('reports/execute-query', {
+ return fleetbaseApiFetch('POST', 'reports/execute-query', {
query_config: queryConfig,
});
-
- return response;
}
static async exportQuery(queryConfig, format = 'csv', options = {}) {
- const owner = getOwner(this);
- const fetch = owner.lookup('service:fetch');
-
- // fetch here is the injected service, not a callable — every sibling posts through it.
- const response = await fetch.post('reports/export-query', {
+ return fleetbaseApiFetch('POST', 'reports/export-query', {
query_config: queryConfig,
format,
options,
});
-
- return response;
}
static async validateQuery(queryConfig) {
- const owner = getOwner(this);
- const fetch = owner.lookup('service:fetch');
-
- const response = await fetch.post('reports/validate-query', { query_config: queryConfig });
- return response;
+ return fleetbaseApiFetch('POST', 'reports/validate-query', { query_config: queryConfig });
}
static async analyzeQuery(queryConfig) {
- const owner = getOwner(this);
- const fetch = owner.lookup('service:fetch');
-
- const response = await fetch.post('reports/analyze-query', { query_config: queryConfig });
- return response;
+ return fleetbaseApiFetch('POST', 'reports/analyze-query', { query_config: queryConfig });
}
+ // null rather than the default {}, so the GET is not given an empty query string.
static async getTables() {
- // Was reaching for a bare `fetch`, which resolved to the global window.fetch and has
- // no .get() — resolve the service the same way every sibling does.
- const owner = getOwner(this);
- const fetch = owner.lookup('service:fetch');
-
- const { tables } = await fetch.get('reports/tables');
+ const { tables } = await fleetbaseApiFetch('GET', 'reports/tables', null);
return tables;
}
static async getTableSchema(tableName) {
- const owner = getOwner(this);
- const fetch = owner.lookup('service:fetch');
-
- const { schema } = await fetch.get(`reports/tables/${tableName}/schema`);
+ const { schema } = await fleetbaseApiFetch('GET', `reports/tables/${tableName}/schema`, null);
return schema;
}
static async getExportFormats() {
- const owner = getOwner(this);
- const fetch = owner.lookup('service:fetch');
-
- const { formats } = await fetch.get('reports/export-formats');
+ const { formats } = await fleetbaseApiFetch('GET', 'reports/export-formats', null);
return formats;
}
diff --git a/console/app/resolver.js b/console/app/resolver.js
deleted file mode 100644
index fefaf116..00000000
--- a/console/app/resolver.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import Resolver from 'ember-resolver';
-
-export default class extends Resolver {
- resolveRoute(parsedName) {
- if (parsedName.fullNameWithoutType === 'main') {
- return import('./router.generated');
- }
-
- return super.resolveRoute(parsedName);
- }
-}
diff --git a/console/app/services/user-verification.js b/console/app/services/user-verification.js
index 3ad48b1b..66fe43a8 100644
--- a/console/app/services/user-verification.js
+++ b/console/app/services/user-verification.js
@@ -17,7 +17,19 @@ export default class UserVerificationService extends Service {
@tracked ready;
@tracked waiting = false;
+ /**
+ * The onboarding session the verification code was issued against, named for the
+ * `hello` query param the auth and onboard verification screens carry it in. The resend
+ * endpoints need it to tie a new code to the session already in progress; `session` is
+ * taken by the injected service above.
+ */
+ @tracked hello;
+
@action start(options = {}) {
+ if (options?.session !== undefined) {
+ this.setSession(options.session);
+ }
+
// Hand the timer back so callers can cancel it. Without this the 75s wait is
// unreachable once scheduled and will still fire after its caller has gone away.
return this.#wait(options?.timeout ?? 75000);
@@ -42,6 +54,7 @@ export default class UserVerificationService extends Service {
const phone = modal.getOption('phone');
if (!phone) {
this.notifications.error('No phone number provided.');
+ return modal.stopLoading();
}
try {
@@ -65,7 +78,8 @@ export default class UserVerificationService extends Service {
modal.startLoading();
const email = modal.getOption('email');
if (!email) {
- this.notifications.error('No email number provided.');
+ this.notifications.error('No email address provided.');
+ return modal.stopLoading();
}
try {
@@ -108,6 +122,10 @@ export default class UserVerificationService extends Service {
this.code = code;
}
+ setSession(session) {
+ this.hello = session;
+ }
+
// start() is the only caller and always resolves the timeout itself, so this takes no
// default of its own.
#wait(timeout) {
diff --git a/console/config/coverage.js b/console/config/coverage.js
index f5638d77..7f0b9bb2 100644
--- a/console/config/coverage.js
+++ b/console/config/coverage.js
@@ -35,12 +35,7 @@ module.exports = {
// Exclude generated/vendor and test files from the coverage denominator.
// app/extensions/** are auto-generated extension manifests (declarative config
// written by the extensions generator) — not hand-written, testable logic.
- // app/resolver.js is dead code: app/app.js imports Resolver straight from 'ember-resolver'
- // and nothing else references it. It is also broken — its resolveRoute() calls
- // super.resolveRoute(), which ember-resolver does not define, so every non-'main' route
- // would throw the moment the file was actually wired up. It is excluded rather than
- // tested; the file should be deleted or repaired separately.
- excludes: ['*/mirage/**', '*/tests/**', '**/*-test.js', '**/extensions/**', '**/resolver.js'],
+ excludes: ['*/mirage/**', '*/tests/**', '**/*-test.js', '**/extensions/**'],
modifyAssetLocation(root, relativePath) {
if (relativePath.startsWith(MODULE_PREFIX)) {
diff --git a/console/tests/unit/models/report-test.js b/console/tests/unit/models/report-test.js
index 415fc9d3..3bbb5884 100644
--- a/console/tests/unit/models/report-test.js
+++ b/console/tests/unit/models/report-test.js
@@ -1,8 +1,8 @@
import { module, test } from 'qunit';
import { setupTest } from '@fleetbase/console/tests/helpers';
import Service from '@ember/service';
-import { getOwner, setOwner } from '@ember/application';
import ReportModel from '@fleetbase/console/models/report';
+import config from 'ember-get-config';
// A query_config shaped the way the model expects, with knobs for each feature.
function queryConfig(overrides = {}) {
@@ -309,101 +309,125 @@ module('Unit | Model | report', function (hooks) {
});
/**
- * The static query helpers resolve their fetch service through getOwner(this), where `this`
- * is the class itself. Nothing in the app ever gives the class an owner, so as written they
- * cannot work when called as ReportModel.getTables() — flagged on the PR rather than
- * redesigned here. Supplying an owner lets the logic inside them be exercised.
+ * The static query helpers are not tied to a saved report and have no container to resolve a
+ * service from, so they go through fleetbaseApiFetch, which builds the request itself. That
+ * means stubbing the global fetch rather than service:fetch.
*/
module('Unit | Model | report | static query API', function (hooks) {
setupTest(hooks);
hooks.beforeEach(function () {
- this.posted = [];
- this.gets = [];
- this.getResponse = {
- 'reports/tables': { tables: [{ name: 'orders' }] },
- 'reports/tables/orders/schema': { schema: { columns: ['id'] } },
- 'reports/export-formats': { formats: ['csv', 'pdf'] },
- };
+ this.requests = [];
+ this.response = {};
const self = this;
- class FetchStub extends Service {
- post(path, payload) {
- self.posted.push({ path, payload });
- return Promise.resolve({ ok: true });
- }
- get(path) {
- self.gets.push(path);
- return Promise.resolve(self.getResponse[path]);
- }
- }
- this.owner.register('service:fetch', FetchStub);
+ this.originalFetch = window.fetch;
+ window.fetch = (url, options) => {
+ self.requests.push({ url, method: options.method, body: options.body ? JSON.parse(options.body) : undefined, headers: options.headers });
- this.previousOwner = getOwner(ReportModel);
- setOwner(ReportModel, this.owner);
+ return Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve(self.response),
+ });
+ };
+
+ // fleetbaseApiFetch prefixes every path with the configured API host and namespace.
+ this.prefix = `${config.API.host}/${config.API.namespace}/`;
+ this.lastRequest = () => self.requests.at(-1);
});
hooks.afterEach(function () {
- setOwner(ReportModel, this.previousOwner);
+ window.fetch = this.originalFetch;
});
test('executeQuery posts the config to the ad-hoc endpoint', async function (assert) {
- const config = { table: { name: 'orders' } };
+ this.response = { ok: true };
+ const queryConfig = { table: { name: 'orders' } };
- const response = await ReportModel.executeQuery(config);
+ const response = await ReportModel.executeQuery(queryConfig);
- assert.deepEqual(this.posted.at(-1), { path: 'reports/execute-query', payload: { query_config: config } });
+ const request = this.lastRequest();
+ assert.strictEqual(request.url, `${this.prefix}reports/execute-query`);
+ assert.strictEqual(request.method, 'POST');
+ assert.deepEqual(request.body, { query_config: queryConfig });
assert.deepEqual(response, { ok: true }, 'the server response is handed back');
});
test('exportQuery posts the config with its format and options', async function (assert) {
- const config = { table: { name: 'orders' } };
+ const queryConfig = { table: { name: 'orders' } };
- await ReportModel.exportQuery(config, 'pdf', { landscape: true });
+ await ReportModel.exportQuery(queryConfig, 'pdf', { landscape: true });
- assert.deepEqual(this.posted.at(-1), {
- path: 'reports/export-query',
- payload: { query_config: config, format: 'pdf', options: { landscape: true } },
- });
+ const request = this.lastRequest();
+ assert.strictEqual(request.url, `${this.prefix}reports/export-query`);
+ assert.deepEqual(request.body, { query_config: queryConfig, format: 'pdf', options: { landscape: true } });
});
test('exportQuery defaults to csv with no options', async function (assert) {
await ReportModel.exportQuery({ table: { name: 'orders' } });
- assert.strictEqual(this.posted.at(-1).payload.format, 'csv');
- assert.deepEqual(this.posted.at(-1).payload.options, {});
+ assert.strictEqual(this.lastRequest().body.format, 'csv');
+ assert.deepEqual(this.lastRequest().body.options, {});
});
test('validateQuery and analyzeQuery post to their own endpoints', async function (assert) {
- const config = { table: { name: 'orders' } };
+ const queryConfig = { table: { name: 'orders' } };
- await ReportModel.validateQuery(config);
- assert.deepEqual(this.posted.at(-1), { path: 'reports/validate-query', payload: { query_config: config } });
+ await ReportModel.validateQuery(queryConfig);
+ assert.strictEqual(this.lastRequest().url, `${this.prefix}reports/validate-query`);
+ assert.deepEqual(this.lastRequest().body, { query_config: queryConfig });
- await ReportModel.analyzeQuery(config);
- assert.deepEqual(this.posted.at(-1), { path: 'reports/analyze-query', payload: { query_config: config } });
+ await ReportModel.analyzeQuery(queryConfig);
+ assert.strictEqual(this.lastRequest().url, `${this.prefix}reports/analyze-query`);
+ assert.deepEqual(this.lastRequest().body, { query_config: queryConfig });
});
test('getTables unwraps the table list from the response', async function (assert) {
+ this.response = { tables: [{ name: 'orders' }] };
+
const tables = await ReportModel.getTables();
- assert.deepEqual(this.gets, ['reports/tables']);
+ const request = this.lastRequest();
+ assert.strictEqual(request.url, `${this.prefix}reports/tables`, 'no empty query string is appended');
+ assert.strictEqual(request.method, 'GET');
assert.deepEqual(tables, [{ name: 'orders' }], 'the tables are unwrapped, not the envelope');
});
test('getTableSchema requests the schema for the named table', async function (assert) {
+ this.response = { schema: { columns: ['id'] } };
+
const schema = await ReportModel.getTableSchema('orders');
- assert.deepEqual(this.gets, ['reports/tables/orders/schema']);
+ assert.strictEqual(this.lastRequest().url, `${this.prefix}reports/tables/orders/schema`);
assert.deepEqual(schema, { columns: ['id'] });
});
test('getExportFormats unwraps the available formats', async function (assert) {
+ this.response = { formats: ['csv', 'pdf'] };
+
const formats = await ReportModel.getExportFormats();
- assert.deepEqual(this.gets, ['reports/export-formats']);
+ assert.strictEqual(this.lastRequest().url, `${this.prefix}reports/export-formats`);
assert.deepEqual(formats, ['csv', 'pdf']);
});
+
+ test('a persisted session is sent as a bearer token', async function (assert) {
+ window.localStorage.setItem('ember_simple_auth-session', JSON.stringify({ authenticated: { token: 'session-token' } }));
+
+ try {
+ await ReportModel.getTables();
+
+ assert.strictEqual(this.lastRequest().headers.Authorization, 'Bearer session-token');
+ } finally {
+ window.localStorage.removeItem('ember_simple_auth-session');
+ }
+ });
+
+ test('an unauthenticated caller sends no authorization header', async function (assert) {
+ await ReportModel.getTables();
+
+ assert.strictEqual(this.lastRequest().headers.Authorization, undefined);
+ });
});
module('Unit | Model | report | execution display', function (hooks) {
diff --git a/console/tests/unit/services/user-verification-test.js b/console/tests/unit/services/user-verification-test.js
index 5f16385a..4c0265ee 100644
--- a/console/tests/unit/services/user-verification-test.js
+++ b/console/tests/unit/services/user-verification-test.js
@@ -255,6 +255,7 @@ module('Unit | Service | user-verification', function (hooks) {
this.owner.register('service:modals-manager', ModalsManagerStub);
const service = this.owner.lookup('service:user-verification');
+ service.setSession('sess_abc');
service.resendBySms();
const modal = fakeModal({ phone: '+15550001111' });
@@ -262,9 +263,7 @@ module('Unit | Service | user-verification', function (hooks) {
assert.strictEqual(request.path, 'onboard/send-verification-sms');
assert.strictEqual(request.body.phone, '+15550001111');
- // Documenting current behaviour, not endorsing it: the service reads `this.hello`,
- // which it never defines, so the session is always sent as undefined.
- assert.strictEqual(request.body.session, undefined, 'session is always undefined — see this.hello');
+ assert.strictEqual(request.body.session, 'sess_abc', 'the resent code is tied to the session in progress');
assert.deepEqual(modal.calls, ['startLoading', 'done']);
assert.deepEqual(this.owner.lookup('service:notifications').successes, ['Verification code SMS sent!']);
});
@@ -284,11 +283,12 @@ module('Unit | Service | user-verification', function (hooks) {
const service = this.owner.lookup('service:user-verification');
service.resendBySms();
- await this.owner.lookup('service:modals-manager').shown[0].options.confirm(fakeModal({ phone: '' }));
+ const modal = fakeModal({ phone: '' });
+ await this.owner.lookup('service:modals-manager').shown[0].options.confirm(modal);
assert.deepEqual(this.owner.lookup('service:notifications').errors, ['No phone number provided.']);
- // Current behaviour: the guard has no `return`, so the request goes out anyway.
- assert.true(posted, 'the request is still sent despite the missing number');
+ assert.false(posted, 'nothing is sent without a number to send it to');
+ assert.deepEqual(modal.calls, ['startLoading', 'stopLoading'], 'the modal stops spinning so the user can correct it');
});
test('a failed sms send is surfaced and the modal is left open', async function (assert) {
@@ -364,10 +364,12 @@ module('Unit | Service | user-verification', function (hooks) {
const service = this.owner.lookup('service:user-verification');
service.resendEmail();
- await this.owner.lookup('service:modals-manager').shown[0].options.confirm(fakeModal({ email: '' }));
+ const modal = fakeModal({ email: '' });
+ await this.owner.lookup('service:modals-manager').shown[0].options.confirm(modal);
- assert.deepEqual(this.owner.lookup('service:notifications').errors, ['No email number provided.']);
- assert.true(posted, 'the request is still sent despite the missing address');
+ assert.deepEqual(this.owner.lookup('service:notifications').errors, ['No email address provided.']);
+ assert.false(posted, 'nothing is sent without an address to send it to');
+ assert.deepEqual(modal.calls, ['startLoading', 'stopLoading'], 'the modal stops spinning so the user can correct it');
});
test('a failed email send is surfaced and the modal is left open', async function (assert) {
@@ -391,3 +393,39 @@ module('Unit | Service | user-verification', function (hooks) {
assert.deepEqual(modal.calls, ['startLoading', 'stopLoading']);
});
});
+
+module('Unit | Service | user-verification | session', function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.service = this.owner.lookup('service:user-verification');
+ });
+
+ hooks.afterEach(function () {
+ cancel(this.timer);
+ });
+
+ test('start records the session the verification was issued against', function (assert) {
+ assert.strictEqual(this.service.hello, undefined, 'nothing is assumed before a caller supplies one');
+
+ this.timer = this.service.start({ session: 'sess_from_caller' });
+
+ assert.strictEqual(this.service.hello, 'sess_from_caller');
+ });
+
+ test('start without a session leaves any previously recorded one alone', function (assert) {
+ this.service.setSession('sess_existing');
+
+ this.timer = this.service.start();
+
+ assert.strictEqual(this.service.hello, 'sess_existing', 'a bare start() does not wipe the session');
+ });
+
+ test('an explicitly empty session is recorded as given', function (assert) {
+ this.service.setSession('sess_existing');
+
+ this.timer = this.service.start({ session: null });
+
+ assert.strictEqual(this.service.hello, null, 'the caller is trusted over the previous value');
+ });
+});