Tintin81
Tintin81

Reputation: 10207

How can I make sure that a user can only edit his own entries?

I have Users that have many People that have many Projects.

For example, a new project can be created like this:

def new
  @project = Project.new(:person_id => params[:person_id])
  @title = "New project"
end

How can I make sure that a user can only insert a person_id here that really belongs to him?

Upvotes: 0

Views: 86

Answers (2)

Brendan Benson
Brendan Benson

Reputation: 773

Consider using implicit authorization for this. Your end result should look like:

# GET people/1/projects/new
def new
  user = User.find(session[:current_user_id])
  @project = user.people.find(params[:person_id]).projects.build(:title => "New Project")
end

# POST people/1/projects
def create
  user = User.find(session[:current_user_id])
  user.people.find(params[:person_id]).projects.create(params[...])
end

Then in routes.rb:

resources :people do
  resources :projects
end

With this approach, the new project will be attributed to the user automatically.

On a side note, you should consider using something like Devise or a before_filter so you can access the current user more conveniently without having to do User.find in each action.

And additionally, you should not have an additional @title variable in your controller action. Each controller action should be responsible for sharing a resource or collection of resources.

Upvotes: 1

Siwei
Siwei

Reputation: 21569

get user_id from session(server side), but not the parameter (client side), e.g.

def new
  @project = Project.new(:person_id => session[:current_user_id])
end

or, make the interface more restrict:

def new
  @project = Project.create_for_current_user(session)
end

def Project.create_for_current_user(session)
  return Project.new(:person_id => session[:current_user_id])
end 

Upvotes: 1

Related Questions