Upgrading to Ember Simple Auth 1.0 - ic-ajax authorization

Hey :smile:

As Ember Simple Auth is 1.0 now I wanted to upgrade. But I realized that they removed “auto-authorization”. We are using ember-cli-ic-ajax and in our application we have many things like the following:

import Request from 'ic-ajax'; 
new Request(params).then(...)

Now I wonder what is the best way to authorize these ic-ajax requests without rewriting all the requests in the whole app.

@marcoow What do you think would be the approach with the tiniest impact on the existing codebase?

Thanks a lot, Tschoartschi

I would extract a service that wraps

import Request from 'ic-ajax'; 
new Request(params).then(...)

and inject the authorization header if applicable. I don’t really see a better way. Of course you could also monkey-patch that into ic-ajax somehow but that’s not really great for obvious reasons. Also using a service should be a pretty straight forwards change.

@marcoow thanks for the quick response. I also had the idea of a service and I also thought about “monkey patching” it into ic-ajax. But if a service is the way to go I’ll implement it. As you said, the changes in the code should not be that much.

I just wonder how other ember-simple-auth users are authorizing theier ic-ajax requests. I think this issue effects more people than just me. But I found not much about it on the internet.

In order to get this working I replaced ic-ajax with ember-ajax (which seems like it is a good idea anyway)

Then I created a custom service that looks like:

import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';

const { service } = Ember.inject;

export default AjaxService.extend({
  session: service(),
  headers: Ember.computed('session', {
    get() {
      let headers = {};
      this.get('session').authorize('authorizer:token', (headerName, headerValue) => {
        headers[headerName] = headerValue;
      });
      
      return headers;
    }
  }),
  
});

Then I call that service like:

this.get('ajax').request(url).then(data => {

@jrjohnson: Thanks for your detailed code example. Basically this is what I ended up doing. Though I didn’t switch ic-ajax to ember-ajax right now. But I still have a problem, maybe @marcoow could help me.

I’m using the DataAdapterMixin from ember-simple-auth/mixins/data-adapter-mixin and the DataAdapterMixin requires an Authorizer. This works quite well but I have to set different headers if we access an ember-data model called items. Now there is the question where to set these headers. In the authorizer I have no information which model is accessed. I could write a custom adapter for the items model but then the authorization logic would be split across the authorizer and the adapter. What would be a nice solution?

Defining a specific adapter for the items model and customizing the authorization code there is the way to go.