Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check user's permission by id?

In Rails3 application i have a number of models with user_id - this way i'm saying: it was created by some user.

Like:

current_user.id #=> 1
@item.user_id #=> 1
# this item created by user with id 1

And i want to restrict current_user's acess to items which was not created by him/her.

Something like:

if @item.user_id == current_user.id
  #everything is fine
else
  #redirect somwhere with flash "You don't have an access here"
end

What is the best way for this, because i have multiple number of models (and controllers to show/edit/destroy) with such a user_id?

like image 386
There Are Four Lights Avatar asked Dec 04 '25 13:12

There Are Four Lights


1 Answers

Use CanCan!

With it you will be able to define permissions declaratively, like this:

can :read, Project, :user_id => user.id

And later enforce this rule:

def show
  @project = Project.find(params[:id])
  authorize! :read, @project
end

authorize! will raise an exception, but you can check in a more peaceful manner:

<%= link_to 'Link to a project', @project if can? :read, @project %>

You can intercept authorization errors and handle them in one place:

class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end
end
like image 104
Sergio Tulentsev Avatar answered Dec 07 '25 06:12

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!