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!

Advertisement
Rolling your own basic user authorizations with devise

Managing Administrator accounts with Devise

I’ve been using the Devise gem for a couple apps in my recent exploration of Ruby on Rails.  It works pretty well and has a lot of great features but the documentation on how to best go about setting up administrators on it is a bit vague.  I would write up some notes on how to do it but  I’d basically be plagiarizing another post on the matter which really cleared things up for me.  Check it out: http://jonallured.com/2011/04/30/using-devise-for-admin-accounts.html

Managing Administrator accounts with Devise

Setting Up Mailer Using Devise For Forgot Password

Really cleared up my confusion about sending email in both development and production environments.

Ruby on Rails Help

In this tutorial I will show you how to set up the mailer for the forgot password feature in Devise. In the tutorial I will be setting up a Gmail account and I will show you how its done using local environment variables. I will also be using Heroku and Foreman to set up environment variables.

I am using Rails 4 and Devise 3 for this tutorial.

Seting Up Development Environment

First we will set up the development mailer for use on your local machine. In “config/environments/development.rb” you should already have included

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

when you installed devise.

Next you should turn on the option to raise an exception if there is an error when sending an email. You can do this by including

config.action_mailer.raise_delivery_errors = true

in the same file. Next we will add the email delivery method. You should leave the values as…

View original post 672 more words

Setting Up Mailer Using Devise For Forgot Password

Notes: basic psql commands

As I’m learning postgresql to develop with Heroku, here are my notes on some of the basic commands that are necessary to move around within the command-line interface.

Logging in under the postgres user (this would be like root in mysql)
psql -U postgres -h localhost

To list all databases:
\list

To connect to a database (similar to use database in mysql):
\c the_database

To list tables in that database:
\d

To list the columns in a particular table:
\d table_name

To view all rows in a given connected table (just the standard sql command):
select * from the_table

To quit out of the psql command-line utility:
\q

Notes: basic psql commands

Notes: Adding themes to rails app

To add themes to a rails app

  • Drop respective css and javascript files into appropriate directory under vendor/assets/.
    Note: Files should have unique name (I name them after the theme so flatty-theme/css/style.css simply becomes flatty.css.
  • Add the following code to your config/application.rb under # add custom validators path in the Application class

    config.assets.paths << "#{Rails.root}/vendor/assets/*"
    config.assets.paths << "#{Rails.root}/vendor/assets/fonts"
    config.assets.paths << "#{Rails.root}/vendor/assets/stylesheets"
  • Adjust whatever views you’re using to use the appropriate classes in your theme

…And that’s it!

Notes: Adding themes to rails app

How to Override and Customize the Devise Controller in Rails

Was an absolute lifesaver when I was trying to add additional registration information to my sign-up page.

How I Learned Ruby on Rails

Judging by the number of different StackOverflow questions, there are a lot of people trying to do this, and a lot of confusion. Here is how I did it, and hopefully it helps you.

I have a User and a Verifier model.  What I want to do is create a new Verifier every time I create a new user, and pass in the user.id for the User into the verifier.user_id so that they are mapped together.

In order to do this I want to not really override but add additional functionality to the existing devise controller that handles when new users are created (and destroyed).  So I need to access the RegistrationsController#Create function in devise.

First thing is to create a new folder in the ‘app/controllers‘ folder where we can put my custom controller.  I called mine ‘app/controllers/my_devise‘.  Then create a new file in this folder…

View original post 534 more words

How to Override and Customize the Devise Controller in Rails

Boot Error: Gave up waiting for root device

So today my computer threw this really strange error when I was booting it up.  Still don’t know what caused it but you can bet your bottom dollar that I’m backing up that hard disk now that I recovered it.  While I was booting up I was confronted with the following error:

Gave up waiting for root device

I’d never seen this before and the screen looked like this (though this isn’t my image):

Image

I booted to a live cd and found that my root file system (sda2) wouldn’t mount, nor could it be repaired by gparted.  After a lot of trial and error with other solutions, I gave fsck a try (with a little help from here) and it worked like a charm.  Below is what I did:

  1. entered sudo fsck /dev/sda2/
  2. This scanned my disk and immediately reported that there were problems.  It asked if I wanted to fix them.
  3. I entered y to signify that it should do so
  4. fsck came up with well over 100 block count errors, asking me each time if I wanted to fix it.  I kept entering y and finally threw caution to the wind and held the key down until it finished.
  5. I restarted and it worked.

Of course this isn’t guaranteed to fix everyone’s issue but if you’re out of ideas, give it a try.  I’m sure glad that I did!

Boot Error: Gave up waiting for root device

Editing KDE Desktop Themes

Today, I was looking to rebrand the KDE desktop with my own flair.  I read this very good tutorial at techbase.kde.org.  However, there were a few subtleties that I found it lacking with regard to editing the brand.svg file, as well as any other icon in a theme’s library.

A little background:

Theme data can be found in one of two key directories:

  1. /usr/share/kde4/apps/desktoptheme/
  2. ~/.kde/share/apps/desktoptheme/

There are a couple other files that can be found here and there (for example, Ubuntu declares their own default branding for the Air theme in /usr/share/kubuntu-default-settings/kde4-profile/default/share/apps/desktoptheme/) but most themes reside in one of those two directories above.

To create one’s own theme, I recommend finding something close to what you want to create in KDE’s theme library, then access its files in one of the directories above.  Virtually all of the theme’s graphics are contained in some sort of .svg file.

The tricky stuff:

The particular element that I wanted to edit is the little bit of branding in the upper right-hand corner of the application launcher menu as depicted below.  However this procedure applies to just about all aesthetic edits in the theme. androbit

Now the particular theme that I happened to be editing was called “Androbit.”  But this principle should work for all themes (maybe with some minor variation).

  1. To edit the icon, I navigated to the file /home/sam/.local/share/Trash/files/Androbit/widgets/branding.svg.  The file for this in pretty much all themes seems to be branding.svg or branding.svgz.
  2. An svg is a vector image.  The go-to open source tool to edit one of these is Inkscape.  Don’t open it in Gimp or alike because, while gimp can open vector graphics it will save them as bitmaps which is no good for what we’re doing.  So, open it in Inkscape.
  3. Once you’re in inkscape, you’ll need to grab some key info from the existing icon that’s necessary to properly insert your brand object into the theme.
    1. Select the item and right click on it and select “Object Properties”.ObjectProperties
    2. Within the “Object Properties” window, you will find two text strings: “Id” and “Label”.  Write down both strings; you’ll need them in a couple steps.ObjectPropertiesWindow
  4. Now, go ahead and delete the original bit of branding and put your own in its place.YourBranding
  5. Now, to make this text show up, we have to convert it to a path.  This step is a bit odd and I can’t tell if it’s a glitch with Inkscape or if it’s meant to be that way but in either case, here we go.  Note: if it’s just an image that you put in, you won’t need to do this step.
    1. Select the text object you just wrote in.Test
    2. Next, go up to path and select “Object to Path.” ToPath
    3. There, now the text will show up in the theme (only took me a couple hours to figure that out).
  6. Now, remember that text string from step 2?  Good, you’ll need them.  Right click on your new object and select “Object Properties.”  (Just like before)
  7. Then write in the two text strings for “Id” and “Label.”new object properties
  8. Now save the file and that’s it.  Your new branding should be in your application launcher menu.
Editing KDE Desktop Themes