lundi 30 mai 2016

Emberjs: How to invalidate session in custom authentication initializer

I'm using ember-simple-auth 1.1.0 with cookie authentication and I created a custom authenticator with functions (restore, authenticate and invalidate) and an initializer of the custom authenticator.

I bind on ajaxError event so we can catch any errors. For example accessing a route with a server response 401 Not Authorized. I would like to invalidate the session and redirect the user back to the login page.

At the moment I'm not able to get the ember-simple-auth default session in the initializer so I can invalidate the session. I didn't create any custom session for my application.

What is the best way to do this?

If it is not possible, is it better to trigger an event on initializer and catch that event in a route? How we can do this?

My custom initializer looks like:

import BasicAuthenticator from '../authenticators/basic';

export default {
  before: 'ember-simple-auth',
  name: 'basic-authenticator',
  initialize(application) {
    application.register('authenticator:basic', BasicAuthenticator);
    Ember.$(document).ajaxError((event, jqxhr, settings, reason) => {
      if (jqxhr.status === 401) {

      }
    });
  }
};

My Custom Authenticator:

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

export default Base.extend({
  restore() {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      let sessionCookie = window.Cookies.get('beaker.session.id');
      if(!window.isUndefined(sessionCookie)) {
        resolve(true);
      }else{
        reject();
      }
    });
  },
  authenticate(data) {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      Ember.$.ajax({
        type: 'post',
        url: '/core/authentication/basic/login',
        data: data
    }).then((response) => {
        resolve({
          responseText: response
        });
      }, (error) => {
        reject(error);
      });
    });
  },
  invalidate() {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      Ember.$.ajax({
        type: 'post',
        url: '/core/authentication/basic/logout'
      }).then(() => {
         resolve(true);
       }, () => {
         reject();
      });
    });
  }
});




Aucun commentaire:

Enregistrer un commentaire