27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The projects API<br />

The respond_with method here will return the JSON representation of Project.all<br />

when you make a JSON request to this path by calling to_json on the object. Rails<br />

knows to return JSON data back from any request with the format (that’s the bit after<br />

the dot in api/v1/projects.json) of JSON. Rails handles all of this internally for you,<br />

which is nice of it to do. Let’s find out if this new controller and its only action make<br />

the spec pass with bin/rspec spec/api/v1/projects_spec.rb:<br />

1 example, 0 failures<br />

There you have it, your first API route and action are serving up data! Now you’re<br />

going to need to restrict what this action returns to only the projects that the user can<br />

read, but you’ll need to first authenticate a user based on their token, which is made<br />

easy with Devise.<br />

13.1.3 API authentication<br />

Your next task is authenticating the user who’s making the request in your API. The<br />

first step is to do something with the token parameter that gets passed through with<br />

your request. A sensible place to check this token would be in Api::V1::Base-<br />

Controller, because you want to authenticate for all controllers in the API (although<br />

there’s only one, for now). For this authentication, you’ll find if there’s a user with the<br />

token passed in by using a before_filter like this in app/controllers/api/v1/base<br />

_controller.rb:<br />

before_filter :authenticate_user<br />

private<br />

def authenticate_user<br />

@current_user = User.find_by_authentication_token(params[:token])<br />

end<br />

def current_user<br />

@current_user<br />

end<br />

To check and see if this is working, you’ll alter your test in spec/api/v1/<br />

projects_spec.rb to generate another project, give the user read access to only that<br />

project, and check that the response from the API only contains that project. To do<br />

this, you’ll add a new before to the “projects viewable by this user” context inside the<br />

spec, using the code from the following listing.<br />

Listing 13.4 spec/api/v1/projects_spec.rb<br />

context "projects viewable by this user" do<br />

before do<br />

Factory(:project, :name => "Access Denied")<br />

end<br />

...<br />

end<br />

355

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!