Rolling your own basic user authorizations with devise

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:

  1. You are using the devise gem and have set it up
  2. 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

  1.  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
  2. Next we define require_permission and say that if the current user is NOT the user on file for the given post… proceed.
  3. 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.
  4. 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!

Advertisements
Rolling your own basic user authorizations with devise

One thought on “Rolling your own basic user authorizations with devise

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s