views:

34

answers:

2

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
    @team = 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)

Thanks in advance

+1  A: 

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.

John Drummond
Yeah, I do this to. Users that are not signed in can use Index/Show. To create you have to be signed in. But the question was how to check if an object that is about to be destroyed or edited really belongs to the user or the action is done by a admin.
Staffan Jonsson
To make sure the user can only edit the items they own I do:@team = current_user.teams.find( params[:id] )I usually do a separate set of controllers for administration functions.
John Drummond
I have to try that. That seems like a good solution.
Staffan Jonsson
A: 

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.

brad