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??
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With