mercredi 30 septembre 2015

ember-simple-auth: Persisting session in localstorage using custom authenticator

Setup:

  • Ember : 2.0.2
  • Ember Data : 2.0.1
  • jQuery : 1.11.3
  • Ember Simple Auth : 1.0.0 (jjAbrams Branch)
  • Ember CLI : 1.13.8

I'm using pretender to mock a server.

Usecase:

Using a custom authenticator to interface with the server.

Have 2 routes: login, protected (and by default index,application)

When I login with the right credentials, the authenticate method of the authenticator gets called and successfully logs the response object which is passed to resolve().

Observations:

  1. After logging in and being directed to the protected page, Refreshing the protected route (Which has AuthenticatedRouteMixin) leads back to login page.

  2. Localstorage has no values bound to it even after successful login. Before login: ember_simple_auth:session -> {"authenticated":{}}

  3. restore() method of authenticator never called.

  4. Going to another route from the protected route after auth and coming back goest to login page again.

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


export default Base.extend({
  restore: function (data) {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      console.log("RESOLVE",data);
      if (!Ember.isEmpty(data.token)) {
        //TODO Remove log

        resolve(data);
      } else {
        console.log("REJECTING",data);
        reject();
      }
    });
  },
  authenticate(credentials) {
    
    return new Ember.RSVP.Promise((resolve, reject) =>
      Ember.$.ajax({
        url: '/token',
        type: 'POST',
        data: JSON.stringify({
          email: credentials.identification,
          password: credentials.password
        }),
        contentType: 'application/json;charset=utf-8',
        dataType: 'json'
      }).then(function (response) {
        Ember.run(function () {
          //This logs the expected information
          console.log("Response", response, response.token, response.user);
          resolve(response);
        });
      }, function (xhr, status, error) {
        console.log("error", error, xhr.responseText);
        var response = xhr.responseText;
        Ember.run(function () {
          reject(response);
        });
      }));
  },

  invalidate(token) {
    return API.logout(token);
  }
});
//environment.js
ENV['ember-simple-auth'] = {
  store: 'session-store:local-storage',
  routeAfterAuthentication: '/protected'
};

TLDR; How do I make the session persist?




Aucun commentaire:

Enregistrer un commentaire