mainmatter / mainmatter.com

The source code for https://mainmatter.com
16 stars 9 forks source link

Idea for ESA tips blog post #190

Open geekygrappler opened 6 years ago

geekygrappler commented 6 years ago

This is from my experience of setting up ESA at the weekend. It could be that my solutions are not the best, or that the problems are covered in the docs and I just didn't read thoroughly enough.

Setting up log in redirects

import Route from '@ember/routing/route'; import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Route.extend(ApplicationRouteMixin, {
  routeAfterAuthentication: 'dashboard'
});

OR

// app/instance-initializers/session-events.js
export function initialize(instance) {
  const applicationRoute = instance.container.lookup('route:application');
  const session          = instance.container.lookup('service:session');
  session.on('authenticationSucceeded', function() {
    applicationRoute.transitionTo('index');
  });
  session.on('invalidationSucceeded', function() {
    applicationRoute.transitionTo('bye');
  });
};

export default {
  initialize,
  name:  'session-events',
  after: 'ember-simple-auth'
};

But the latter causes issues in the test, it’s not up to date. Far simpler to use the mixin and override that property.

The already authenticated redirect

import Route from '@ember/routing/route';
import UnauthenticatedRouteMixin from 'ember-simple-auth/mixins/unauthenticated-route-mixin';

export default Route.extend(UnauthenticatedRouteMixin, {
  routeIfAlreadyAuthenticated: 'dashboard'
});

Testing - mock already logged in for your protected routes

this.owner.lookup('service:session').set('isAuthenticated', true);

Easy when you know it.

Testing - respond to login correctly in test

     import { mock } from 'ember-data-factory-guy';

    test('after successful login the user is redirected to the dashboard', async function(assert) {
      mock({
        type: 'POST',
        url: '/token',
        responseText: { access_token: 'rubbish' }
      });

      await visit('/login');

      await click('[data-test-login-button]');

      assert.equal(currentURL(), '/dashboard', 'The user is redirected to dashboard after login');
    });
geekygrappler commented 6 years ago

I feel like there may be more as I play with it some more.

marcoow commented 6 years ago

I guess we could have an "ESA best practices" series or so. Some of these things probably indicate a lack of documentation though.