Skip to content

Instantly share code, notes, and snippets.

@leepfrog
Forked from jgwhite/example.js
Last active August 29, 2015 14:00
Show Gist options
  • Save leepfrog/4801db407cb5a07ebf6d to your computer and use it in GitHub Desktop.
Save leepfrog/4801db407cb5a07ebf6d to your computer and use it in GitHub Desktop.
class CsrfController < ApplicationController
def index
render json: { request_forgery_protection_token => form_authenticity_token }.to_json
end
end
// app/initializers/csrf.js
export default {
name: 'csrf',
initialize: function(container, app) {
app.inject('route', 'csrf', 'service:csrf');
app.inject('controller', 'csrf', 'service:csrf');
}
};
// app/services/csrf.js
export default Em.Object.extend({
fetchToken: function() {
var _this = this;
return Em.$.ajax({
url: '/csrf'
}).done( function(data) {
// TODO: Error check
var param = Object.keys(data)[0];
_this.set('token', data);
_this.set('param', param);
});
}
});
// app/routes/application.js
export default Ember.Route.extend({
beforeModel: function() {
return this.csrf.fetchToken();
}
});
// app/controllers/something.js
// ...
// You can now use this.get('csrf.token')
@jgwhite
Copy link

jgwhite commented Apr 30, 2014

You could drop lines 22–25 and just access the token in routes and controllers like this:

this.get('csrf.token');

@leepfrog
Copy link
Author

@jgwhite oh thanks!

@abuiles
Copy link

abuiles commented May 2, 2014

@leepfrog @jgwhite thanks, I just used this for an app I'm moving to ember-cli, and refactor some parts to use ic-ajax abuiles/facturas@675d6c7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment