Project Ramon

A learning journey from a Ruby noob perspective

API Design in Ruby (pt. 3)

api4_header_img

In yesterday’s post I have been continuing my reading of a book titled Rails 3 in Action by: Ryan Bigg and Yehuda Katz.

Today we’ll be continuing by learning how to handle use-cases where our user’s authentication token is either invalid or missing.

Handling an Invalid token against an API

When a user makes a request with an invalid token we need to make sure we’re alerting them of this error.
We can do this by returning a JSON error like so:

In order to be able to test this, we can make an API request without an authentication token and then make our spec pass in this token instead. Lets add a new test file covering our user’s authentication behavior. Inside of spec/apis/v1/authentication_spec.rb we can add:

Now that we have defined the user token as an empty string, GET will pass it in as the token for our spec. Running rspec spec/apis/v1/authentication_spec.rb shows that our test fails. This is because when we attempt to make a request without a valid token, the call to User.find_by_authentication_token in our base_cotroller will return nil.

We can add a condition where if the user has not been found an error will be triggered. Lets add the following code to our authenticate_user method in app/controllers/apis/v1/base_controller.rb.

If the @current_user is nil we have now built in a JSON error response that will be triggered, and running rspec spec/apis/v1/project_spec.rb should show the spec passing.

We now have the apis/v1/projects URL returning a list of only the projects that a user is authorized to read, and we have used Devise’s token authentication functionality to verify which user this is.

Stay tuned…

Advertisements

Categories: Ruby on rails

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s