In my application controller, I have a function like this:
def is_owner_or_admin(user_id)
if cur_user.role != “Admin” && cur_user.id != Integer(user_id)
flash[:error] = “Access denied”
redirect_to(:controller => :users, :action => :account) and return
false
end
end
I call it in my users controller like so:
def show
is_owner_or_admin(params[:id]) @user = User.find_by_id(params[:id])
unless @user
flash[:error] = “User not found”
redirect_to :action => :account
end
end
If @user ends up being nil, however, then I get a DoubleRender error.
My question is, what can I put in “is_owner_or_admin” that will redirect
and not complete the “show” action?
If @user ends up being nil, however, then I get a DoubleRender error.
My question is, what can I put in “is_owner_or_admin” that will redirect
and not complete the “show” action?
I ended with throwing a SecurityError instead of redirecting, makes it
more DRY: I catch the exception and do what I want with it.
In your ApplicationController :
# 1/ save the original exception handling
alias_method :rescue_action_without_security_error, :rescue_action
# 2/ handle the SecurityError case
def rescue_action(exception)
return rescue_action_without_security_error(exception) unless
There is actually a lot wrong here. First of all you can never trust
params with anything as important as access control. What happens
when a user passes in param[:id] equal to an admins? They have admin
access under your code. You need to do some sort of user
authentication, store the user_id in the session and then check that
in your code. Example:
There is actually a lot wrong here. First of all you can never trust
params with anything as important as access control. What happens
when a user passes in param[:id] equal to an admins? They have admin
access under your code. You need to do some sort of user
authentication, store the user_id in the session and then check that
in your code. Example: