diff --git a/app/routes/team.js b/app/routes/team.js index e3749f6..c954642 100644 --- a/app/routes/team.js +++ b/app/routes/team.js @@ -13,6 +13,18 @@ export default class TeamRoute extends Route { Authorization: `Bearer ${this.get('tokenStorage.token')}`, }), method: 'POST', - }).then(response => response.json()); + }) + .then(response => { + if (response.ok) { + return response.json(); + } else { + throw new Error(); + } + }) + .catch(() => { + this.tokenStorage.reset(); + this.controllerFor('application').set('error', 'Invalid token'); + this.transitionTo('application'); + }); } } diff --git a/app/templates/application.hbs b/app/templates/application.hbs index edeb66a..d0b9dbf 100644 --- a/app/templates/application.hbs +++ b/app/templates/application.hbs @@ -28,6 +28,9 @@ {{outlet}} {{else}} + {{#if this.error}} +

{{this.error}}

+ {{/if}} diff --git a/tests/acceptance/require-setup-test.js b/tests/acceptance/require-setup-test.js index 9889efa..8ff97b8 100644 --- a/tests/acceptance/require-setup-test.js +++ b/tests/acceptance/require-setup-test.js @@ -2,6 +2,7 @@ import { module, test } from 'qunit'; import { click, fillIn, visit } from '@ember/test-helpers'; import { setupApplicationTest } from 'ember-qunit'; import { setupMirage } from 'ember-cli-mirage/test-support'; +import { Response } from 'ember-cli-mirage'; import resetStorages from 'ember-local-storage/test-support/reset-storage'; module('Acceptance | require setup', function(hooks) { @@ -33,4 +34,30 @@ module('Acceptance | require setup', function(hooks) { assert.dom('.text-2xl').exists(); assert.dom('[data-test-team-name]').hasText('our team'); }); + + test('it returns to the token field when auth fails', async function(assert) { + const applicationController = this.owner.lookup('controller:application'); + applicationController.set('tokenStorage.token', 1); + + this.server.post('/auth', () => { + return new Response(401, {}, {}); + }); + + await visitWithAbortedTransition('/team'); + + assert.dom('.text-2xl').doesNotExist(); + assert.dom('[data-test-token-field]').exists(); + assert.dom('[data-test-error]').hasText('Invalid token'); + }); }); + +async function visitWithAbortedTransition(url) { + try { + await visit(url); + } catch (error) { + const { message } = error; + if (message !== 'TransitionAborted') { + throw error; + } + } +}