I’m a relative rails newbie, just getting started on learning how to DRY my code, and am not sure if I need to be creating a helper, or decorator, or model method, or some kind overloading class to do some very common “is this user allowed to access this data?” checking….
My rails 3.1 app uses devise for user authentication, and I have (per devise docs) added a simple admin:boolean flag that lets certain users do things other users cannot (like view/edit other users’ profile)
to prevent url spoofing etc I use this near the top of a LOT of my methods:
if current_user.nil?
redirect_to root_path, :alert => "You must sign in to do XXXX" and return
end
if !current_user.admin? && (current_user.id != MYMODEL.user_id)
redirect_to MYMODEL_path, :alert => "The ZZZZ you tried to XXXXX is not yours" and return
end
if current_user.admin? && (current_user.id != MYMODEL.user_id)
flash[:alert] = "Hey ADMIN: You know you are XXXX another user's ZZZZ, right?"
end
The message in each case is different, but the logic is the same.
Can someone show me the easiest way to put that logic in one place (for one controller) that all methods in a controller can use it (optionally) passing in the 3 custom messages?
How about a
before_filter?I’d recommend against explicitly telling the user there’s a valid object they’re not allowed to edit; they don’t need to know that–just tell them it’s not found.
You could also explore gems like “cancan”.