Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Web service with authentication??? User logged in ??

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??

like image 277
newbie on rails Avatar asked Nov 11 '10 01:11

newbie on rails


1 Answers

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:

  • 192 - Authorization with CanCan
  • 188 - Declarative Authorization
like image 198
John Avatar answered Nov 09 '22 23:11

John