views:

60

answers:

1

Hey guys I have a ruby on rails app with a before filter setup in my application controller to ensure only the owner can edit a document, but my permission check is always failing even when it shouldn't. Here is the code:

def get_logged_in_user
  id = session[:user_id]
  unless id.nil?
    @current_user = User.find(id)
  end
end

def require_login
  get_logged_in_user
  if @current_user.nil?
    session[:original_uri] = request.request_uri
    flash[:notice] = "You must login first."
    redirect_to login
  end
end

def check_current_user_permission
  require_login
  logger.debug "user id is #{params[:user_id]}"
  logger.debug "current user id is #{session[:user_id]}"
  if session[:user_id] != params[:user_id]
    flash[:notice] = "You don't have permission to do that."
    redirect_to :controller => 'home'
  end
end

The code to note is in the check_current_user_permission. Here is an example of my log output:

user id is 3
current user id is 3
Redirected to http://localhost:3000/home
Filter chain halted as [:check_current_user_permission] rendered_or_redirected.

Can anyone shed some light into why this is failing? Obviously the user_id of 3 is equal to the session's user_id of 3. What is going wrong?

+1  A: 

If session[:user_id] is '3' and params[:user_id] is '3' and they are not equal maybe you should .to_i them first?

I only say this because I have this problem where I have two DateTime objects that when you .to_s them they are equal but for some reason that don't evaluate to equal because somehow they are a fraction of a second different.

Ruby is an awesome language but one draw back is the weakly typed features.. well its a double edged sword because weakly typed features allow for some cool stuff.

Glad that helped!

DJTripleThreat
I'd say it would be better to convert to an integer, not a string.
mathepic
@~mthepic, I agree... I'm used to working with strongly typed languages so converting to string is usually easier to do. Not so in Ruby. I'll edit my post.
DJTripleThreat