Search code examples
authenticationember.jsember-simple-auth

Invalidate session with custom authenticator


Using ember-cli 0.1.2 and ember-cli-simple-auth 0.7.0, I need to invalidate the session both on client and server. As explained here I need to do something similar to the authenticate method making an ajax request to the server and ensuring its success before emptying the session:

import Ember from 'ember';
import Base from "simple-auth/authenticators/base";

var CustomAuthenticator = Base.extend({
  tokenEndpoint: 'http://127.0.0.1:3000/api/v1/auth/login',

  restore: function(data) {

  },

  authenticate: function(credentials) {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.ajax({
        url:         _this.tokenEndpoint,
        type:        'POST',
        data:        JSON.stringify({ email: credentials.identification, password: credentials.password }),
        contentType: 'application/json'
      }).then(function(response) {
        Ember.run(function() {
          resolve({ token: response.token });
        });
      }, function(xhr, status, error) {
        var response = JSON.parse(xhr.responseText);
        Ember.run(function() {
          reject(response.error);
        });
      });
    });
  },

  invalidate: function() {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.ajax({ 
        url: _this.tokenEndpoint, 
        type: 'DELETE' 
      }).then(function(response) {
        resolve();
      }, function(xhr, status, error) {
        var response = JSON.parse(xhr.responseText);
        Ember.run(function() {
          reject(response.error);
        });
      });
    });
  }

  // invalidate: function() {
  //   var _this = this;
  //   return new Ember.RSVP.Promise(function(resolve) {
  //     Ember.$.ajax({ url: _this.tokenEndpoint, type: 'DELETE' }).always(function() {
  //       resolve();
  //     });
  //   });
  // }
});

export default {
  name : 'authentication',
  before : 'simple-auth',
  initialize : function(container) {
    container.register('authenticator:custom', CustomAuthenticator);
  }
};

My logout API endpoint need the token (in the headers). How do I pass it? I read this but my authorizer seems ignoring it and I got a 401:

import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';

var CustomAuthorizer = Base.extend({
  authorize: function(jqXHR, requestOptions){
    Ember.debug("AUTHORIZING!");
  }
});

export default {
  name : 'authorization',
  before : 'simple-auth',
  initialize : function(container) {
    container.register('authorizer:custom', CustomAuthorizer);
  }
};

My environment.js:

/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'wishhhh',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  // TODO: disabled because of https://github.com/stefanpenner/ember-cli/issues/2174
  ENV.contentSecurityPolicyHeader = 'Disabled-Content-Security-Policy'

  ENV['simple-auth'] = {
    authorizer: 'authorizer:custom',
    // crossOriginWhitelist: ['http://localhost:3000']
    crossOriginWhitelist: ['*']
  }

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'auto';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};

The following is the Ember inspector output when, eventually, I try to logout: enter image description here


Solution

  • Thanks to marcoow, I found out that it was actually a problem with every request not only the logout one. My authorizer never got called. Problem was environment setup of crossOriginWhitelist which, in order to work with my dev API, I had to set to ['http://127.0.0.1:3000']. Neither ['http://localhost:3000'] nor [*] worked.