Skip to content

davidkovsky/rails-csrf

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

47 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

rails-csrf

ember-cli addon to keep track of your Rails CSRF-token.

Usage

  • npm install rails-csrf --save
  • In app.js add load initializers
loadInitializers(App, 'rails-csrf');
  • Add a before model to your application route so your token is fetched automatically.
export default Ember.Route.extend({
  beforeModel: function() {
    return this.csrf.fetchToken();
  }
});

Config

By default rails-csrf does a get request to /api/csrf, if you want to customize the end-point use setCsrfUrl on app.js

import { setCsrfUrl } from 'rails-csrf/config';

setCsrfUrl('/api/your/own/endpoint');
...
loadInitializers(App, 'rails-csrf');

Returning CSRF-token from Rails

The following controller will return the required payload to get everything working.

class Api::CsrfController < ApplicationController
  def index
    render json: { request_forgery_protection_token => form_authenticity_token }.to_json
  end
end

Add route

namespace :api do
  get :csrf, to: 'csrf#index'
end

Working With Integration Tests

Be sure to mock out the call to the csrf server endpoint. Otherwise your tests will fail with

"error while processing route: [route]"

messages in the browser console. For example:

server = new Pretender(function() {
this.get('/csrf', function(request) {
  return [200, {"Content-Type": "application/json"},
    JSON.stringify({
      "authenticity_token": "token"
    })
  ];
});

License

rails-csrf is MIT Licensed.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 99.5%
  • CSS 0.5%