Jon
Jon

Reputation: 179

restrict_access using tokens in Rails

I'm generating a token to restrict access to certain post for certain people. Everything's working fine but it's allowing anyone with a token to look at any post instead of the post the that they're allowed to view only. For an example, if a token was generated for post/1 & post/1 only, the user can still visit post/2 using the same token. How do I fix this?

Here's my post controller

before_filter :restrict_access, only: [:show]

Here's my *private restrict_access method* in my posts controller

def restrict_access
  link_token = LinkToken.find_by_token(params[:token])
  head :unauthorized unless link_token
end

Thanks in advance

Getting "Couldn't find Post without an ID"

def restrict_access
  post = Post.find(params[:post_id])
  link_token = LinkToken.find_by_token(params[:token])
  head :unauthorized unless link_token
end

Upvotes: 0

Views: 206

Answers (1)

s.krueger
s.krueger

Reputation: 1043

Because you only check if the token exists, it doesn't matter which token is entered. I suppose in your LinkToken model the post is kept as a foreign key, overwise you won't be able to fix it.

When yes, try something like this (find_by_x helpers are deprecated as of Rails 4) they return a single resource:

link_token = LinkToken.where(post_id: params[:id], token: params[:token]).first

Upvotes: 1

Related Questions