There seems to be very little written about this in the Rails literature out there, so I thought I’d make a contribution. There’s very much posted about using authorization management gems like CanCan (which is well and good) but for those of us creating a small basic app, such gems are overkill. It’s also worth using a filter just to get an understanding of what’s going on if you’re new to rails (like me!)
Goal:
To create a stupid-simple authorization system that makes sure that only admins and the owner of a post can edit that post.
Assumptions:
- You are using the devise gem and have set it up
- You have created an Admin model (Option 1 in the Devise Wiki)
Proceess
(It’s really short)
To only allow admins and users that own the given post edit authorization, put the following in your post controller:
before_filter :require_permission, only: [:edit, :update, :destroy]
def require_permission
if user_signed_in?
if current_user != Post.find(params[:id]).user
if !admin_signed_in?
redirect_to :root, notice: "Access Denied."
end
end
else
if !admin_signed_in?
authenticate_user!
end
end
end
(Do make your indentation better than the code above; I’m up against wordpress’s auto-correct and don’t feel like fighting with it)
Anyway, that’s it!
The explanation
So why? Let’s start with the top
- We’re adding a method, called require_permission which we are defining below to the methods edit, update and destroy. Meaning any users engaging these methods must fit the requirements outlined in require_permission
- Next we define require_permission and say that if the current user is NOT the user on file for the given post… proceed.
- Then we check if the session user is an admin or, more accurately, if the user is NOT the admin (note the exclamation point). Because user and admin are two different models, devise has defined two different sets of very similar methods when referring to either one. Check them out here. It helps clarify things.
- Finally we add the redirect to the homepage with an ominous “ACCESS DENIED” message at the top.
So to recap, if the user is not the owner of the post AND not signed into the admin model, they get booted back to the homepage. Otherwise, they can do whatever they want to the post.
Enjoy!