mardi 21 avril 2015

ember-cli simple-auth custom authorization

i am trying to use ember-simple-auth with custom authentication and authorization: authenticator works but authorizer doesn't. Token successfully assigned but there is no injection in ajax calls.

app/authenticator/custom.js

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

export default Base.extend({
    tokenEndpoint: 'http://...',

    restore: function(data) {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      if (!Ember.isEmpty(data.token)) {
        resolve(data);
      } else {
        reject();
      }
    });
  },

  authenticate: function(credentials) {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.ajax({
        url:         _this.tokenEndpoint,
        type:        'POST',
        data:        JSON.stringify({ username: 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) {
      Ember.$.ajax({ url: _this.tokenEndpoint, type: 'DELETE' }).always(function() {
        resolve();
      });
    });
  },
});

app/authorizers/custom.js

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

export default Base.extend({
    authorize: function(jqXHR, requestOptions) {

        if (this.get('session.isAuthenticated') && !Ember.isEmpty(this.get('session.secure.token'))) {
            jqXHR.setRequestHeader('X-CSRFToken', this.get('session.secure.token'));
        }
    }
});

app/initializers/authentication.js

import CustomAuthenticator from 'app/authenticators/custom';
import CustomAuthorizer from 'app/authorizers/custom';

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

config/environment.js

  ENV['simple-auth'] = {
    authorizer: 'authorizer:custom',
    crossOriginWhitelist: ['http://...']
  };

app/controllers/login.js

import Ember from 'ember';

export default Ember.Controller.extend({
    actions: {
        authenticate: function(){
            var credentials = this.getProperties('identification', 'password');
            this.get('session').authenticate('authenticator:custom', credentials);

        }
    }
});




Aucun commentaire:

Enregistrer un commentaire