开发者

Best way to restrict actions (edit/delete) with Ruby on Rails and Devise

开发者 https://www.devze.com 2023-01-18 19:09 出处:网络
I am fairly new to Ruby On Rails and right now I am doing a simple app. In this app a user can create many items and I use devise for authentication. Ofcourse I want to make sure that you are the owne

I am fairly new to Ruby On Rails and right now I am doing a simple app. In this app a user can create many items and I use devise for authentication. Ofcourse I want to make sure that you are the owner in order to delete items (Teams, Players etc) and the way I do it now is:

def destroy
    @t开发者_Python百科eam = Team.find(params[:id])
    if current_user.id == @team.user_id 
      @team.destroy    
      redirect_to(teams_url, :notice => 'The team was deleted.')
    else
      redirect_to root_path
    end      
end

Is this the best way? I was thinking about putting a method in the model but I am not sure I can access current_user from there. I was also thinking about a before_filer, something like:

before_filter :check_ownership, :only => [:destroy, :update]

I that case and if I want to code only one method for all objects (all objects this relates to have a "user_id"-field)


In my application controller I put:

before_filter :authorize

def authorize
  false # Or use code here to check if user is admin or not
end

Then I override the authorize method in my actual controller to allow access to various actions.


You're looking for an authorization solution on top of your authentication (devise)

You can't access current user in the model no. I've had a fair amount of success using Makandra's Aegis for authorization. It allows you to create roles specify permissions attributed to each role. The docs are pretty good and I know it works fine with Devise, it's pretty agnostic that way, I've also used it with Clearance. It also passes an implicit "current_user" to your permissions so you can specify and check that your current user can take appropriate actions.

0

精彩评论

暂无评论...
验证码 换一张
取 消