Simon
Simon

Reputation: 629

Limiting action via session

So I have implemented a session system, but I have some troubles.
First of all, when I create a new pokemon, I link the session[:user_id] to it with this code.

@pokemon = Pokemon.new(params[:pokemon])
@pokemon.user_id = @current_user 

When I create one with my account 1, the user_id is 1, but when I create a pokemon with my account 2, the user_id is set to 1 again.

Also, how can I protect the edit/show/destroy pages to sessions only ? Right now, I can edit any of the pokemons with any of the account, if I use directly the address bar.

I put my controllers in a Gist (I suppose it all happens in them)

Thanks in advance.

Upvotes: 0

Views: 23

Answers (1)

sites
sites

Reputation: 21795

Maybe this is not an answer, but is too long to be a comment.

First, I am not sure @pokemon.user_id can be set to an user instance, I would try with:

@pokemon.user = current_user

or:

@pokemon.user_id = current_user.id

Second, I would not user @current_user, instead current_user as above.

Third, it is not clear where you are setting session[:user_id], to debug your problem I would print all related variables in create action of pokemons controller:

  def create
    @pokemon = Pokemon.new(params[:pokemon])
    @pokemon.user_id = current_user 
    p current_user
    p session[:user_id]

Secure actions

You can scope your resource with current_user:

@pokemon = current_user.pokemons.find(params[:id])

That way you will find just pokemons for that user. I am not sure if this method raises an exception or just returns nil when user has not created pokemon with params[:id]. You have to handle whichever of these two (exception or nil) to redirect other users to another page:

for exception

begin
@pokemon = current_user.pokemons.find(params[:id])
rescue ActiveRecord::RecordNotFound => e
  redirect_to :back
end

for nil

@pokemon = current_user.pokemons.find(params[:id])
unless @pokemon
  redirect_to :back
end

Upvotes: 1

Related Questions