1
votes

I have an Ember.js app backed by a RESTful API. Session control is done through an authentication token: once a user logs in, he appends his authentication token to each request he makes to the server. I do this by adding the authentication to the data in $.ajaxSetup.

$.ajaxSetup({
  data: { auth_token: this.get('authToken') }
});

Now, this works fine for GET requests. However, when saving models to the server through a POST or PUT request, the Ember Data RESTAdapter stringifies the data object. In DS.RESTAdapter.ajax it does

....
if (hash.data && type !== 'GET') {
  hash.contentType = 'application/json; charset=utf-8';
  hash.data = JSON.stringify(hash.data);
}
...

Because of this, the authentication token is not merged into the data. In this jQuery ticket they say that it's something they are never going to support.

What's the most elegant way of solving this? I'd rather not override the Ember's RESTAdapter.ajax function because the code is changing so quickly so my overridden function might not be compatible with the rest of the codebase at the next release.

1

1 Answers

1
votes

In the end, I couldn't find another solution besides overriding RESTAdapter.ajax. I ended up adding three parameters: auth[token], auth[school] and auth[name].

DS.RESTAdapter.reopen({
  /* Override to add the authToken, school and name */
  ajax: function(url, type, hash) { 
    var adapter = this;

    return new Ember.RSVP.Promise(function(resolve, reject) { 
      hash = hash || {};
      hash.url = url;
      hash.type = type;
      hash.dataType = 'json';
      hash.context = adapter;

      if (hash.data && type !== 'GET') { 
        hash.contentType = 'application/json; charset=utf-8';

        /* Add the data to the hash before it's stringified. */
        if (HstryEd.Session.get('isLoggedIn')) { 
          hash.data.auth = {};
          hash.data.auth.token = HstryEd.Session.get('authToken');
          hash.data.auth.school = HstryEd.Session.get('currentUser').get('school');
          hash.data.auth.name = HstryEd.Session.get('currentUser').get('name');
        } 

        hash.data = JSON.stringify(hash.data);
      } 

      if (adapter.headers !== undefined) { 
        var headers = adapter.headers;
        hash.beforeSend = function (xhr) { 
          forEach.call(Ember.keys(headers), function(key) { 
            xhr.setRequestHeader(key, headers[key]);
          });
        };
      } 

      hash.success = function(json) { 
        Ember.run(null, resolve, json);
      };

      hash.error = function(jqXHR, textStatus, errorThrown) { 
        if (jqXHR) { 
          jqXHR.then = null;
        } 

        Ember.run(null, reject, jqXHR);
      };

      Ember.$.ajax(hash);
    });
  } 
});