8

Any idea how I would go about have a rails REST web service where a user can only get, put, post, delete only their own data ? I am using Devise as my user authentication gem, but I am not sure if this handles things in a RESTful manner.

How would I assure that the user is 'logged in' and can change their data? Do I have to pass some kind of token around in every request??

2 Answers2

3

Devise will only provide you with authentication. This meaning that you have some level of certainty that the user is identified and is who he/she says he/she is. Given this information, you can use Rails mechanisms or other Rails gems (i.e., CanCan, Aegis, declarative_authorization) to authorize users and define permissions.

A simple method would be to use a before_filter on your controller in question, to determine if, for example, a BlogPost belongs to the user that is signed in.

Here's a simple example of what I mean:

class BlogPostsController < ApplicationController
  before_filter :is_user_allowed, :only => [:edit, :delete, :show]

  # default Rails generated RESTful methods here    

  def is_user_allowed
    if BlogPost.find(params[:id]).try(:user_id) != current_user.id
      redirect_to access_denied_page_path
    end
  end
end

The is_user_allowed method retrieves the BlogPost that is being queried and determines whether the current_user is allowed to perform the action by comparing the user IDs. If the inequality is true, then it redirects to our infamous access_denied_page_path.

For more information on filters, see this Edge Guides article.

For more information on Rails gems that can provide you this functionality (and more), take a look around on Google and search for rails authorization. Furthrmore, here are some Railscasts that should provide some insight:

John
  • 9,254
  • 12
  • 54
  • 75
  • 2
    This part is fine when logging in through a web browser where there is session data. If I were to try to do restricted methods through a curl call. This does not handle it, as I'm actually trying to go for a REST API. So there were two ways I saw, which is either using basic http authentication or doing something with an API key to identify a particular user. Both ways seem very weak security wise for me :( – newbie on rails Nov 11 '10 at 02:40
3

Take a look at AuthLogic's single_access_token. It was designed for authenticating REST APIs.

Steve Wilhelm
  • 6,200
  • 2
  • 32
  • 36