In order to migrate my data with a unqiue index, I had a bunch of de-duping to do. It was a bit trickier than usual because I had to de-dupe based on multiple attributes. I wrote a quick class in ruby to take of this and decided I should share it. Let me know if you have a better way. I sorta went with the fastest because I’m up against a deadline right now.

I spent yesterday coding a very abbreviated version of an authentication service that uses Sinatra, Mongoid and RSpec 2. It took more than a couple hours because there are so many outdated code samples on the web that just don’t work. I put my code up on github for people to see. Just clone the repository and run:

rake spec

While the current example is very basic, I will update it with enhancements and talk more about how to write a good authentication service. For this example I quickly rolled my own basic authentication since the main purpose is to get you up and running quickly with Sinatra, Mongoid, and RSpec2 . I may end up using Authlogic, Devise, or improving on my own authentication functionality.

About two months ago I wrote an article on getting started with Devise and CanCan. Since then, I’ve implemented the Devise + CanCan combo on three projects and wrote a couple specs for Ryan Bates to help improve CanCan functionality. This article will focus more on Devise with some CanCan sprinkled in there.

If you read my first article on Devise + CanCan, you have some questions on your mind. The most common question was how to create a RESTful interface for a super admin to CRUD users. This is a common requirement for managing users and/or keeping registration private. This is really easy.

I’m going to show you how to keep the awesome functionality provided by Devise while adding your custom stuff with no major time cost!

Step 1 – Configure Routes
Since you probably want to keep your public interface for logging in and password recovery, leave your devise routes and add RESTful routes for users:

devise_for :users
resources :users

Step 2 – The User Controller
Next you need to set up your CRUD actions in the controller. Most of the actions are typical:

CanCan provides the class level accessible_by method that I am using to retrieve all users that can be viewed by the current user. The load_and_authorize_resource filter provided by CanCan actually does this accessibility filtering for you to keep things DRY and it recognizes collections as of this issue fix. I support sorting in my actual code so I didn’t want to use the CanCan filter to grab my user objects in the index action.

The other two filters – get_user and accessible_roles – are pretty basic:

# Get roles accessible by the current user#----------------------------------------------------def accessible_roles
@accessible_roles = Role.accessible_by(current_ability,:read)end# Make the current user object available to views#----------------------------------------def get_user
@current_user = current_user
end

Finally, respond_to_not_found is an application wide helper I use to respond when a requested object is not found. I stole it from the Fat Free CRM source code.

Next we’ll look at the Update action which has some non standard code.

That was easy!

The only unusual code we added is to clean up the password request params if the user’s password field is blank, and validate the password with Devise’s valid_password? method if it’s not blank. That allows us to provide a UI that looks like this:Step 3 – Add you views
It may seem a bit redundant to show all of my view code, but I’m going to do it anyway so you can see how I’m using CanCan everywhere.

I’m tired of spending loads of time creating user authentication systems with permissions or swimming against the current to customize what’s available. There’s great open source stuff out there but until now, I haven’t gotten the full package with really easy customization.

The Devise and CanCan combo for user authentication and permissions in Rails is my combo of choice.

With Devise and CanCan, you can create a customized authentication and registration process in 15 minutes, and spend another 15 minutes implementing roles and permissions.

It’s pure beauty.

Note that the code here uses Rails 3. The difference in Rails 3 and Rails 2 code for this purpose should be minimal, but please refer to the documentation for differences.

Step 2 – Configuration
Configuration is super easy with Devise. Just choose which of the 11 available modules you would like to include in your authentic model (most up-to-date list here):

Database Authenticatable: encrypts and stores a password in the database to validate the authenticity of an user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.

Token Authenticatable: signs in an user based on an authentication token (also known as “single access token”). The token can be given both through query string or HTTP Basic Authentication.

This simple modular approach to authentication is hot. Devise also makes it really easy for you to customize views. The out-of-the-box views are great for prototyping, but if you need more, just generate the views and edit them:

rails generate devise:views

Devise will generate all of the views it is using and place them in an app/views/devise directory. Now you have complete control over your views.

The next thing you might want to do is customize your controllers. This is a bit more tricky with devise and we’ll get to that in a minute. Right now I want to touch on permissions and then I’ll tie it all together.

Let’s consider an example where your website is in Alpha/Beta or maybe an internal tool. You want to restrict user registration to only an administrator. Enter CanCan created by Ryan Bates.

CanCan

CanCan is a great gem for implementing model permissions. The main reasons I chose CanCan are:

The code written to check permissions is very readable

The code written to declare permissions is very concise and readable

It keeps permission logic in a single location so it is not duplicated across controllers, views, etc.

Ryan Bates has a great screen cast on using CanCan here, but I do not recommend using his roles mask method (mentioned in the screen cast). It certainly works but it’s bad database design and you will feel the pain later.

After you install CanCan (instructions here), I recommend you set up a typical users HABTM roles relationship. So you end up with migrations that look like this:

Most of this is application specific but you can see some conveniences right away. For example, the super admin role “can manage all”. That line is saying “If the user has the super_admin role, he may perform any action on any model.” Easy enough. Also notice that the product team can “read” products and assets. This means that they can access the index or show action of either of those models. You can pass a block to the can method for more complicated permission checks, but that is beyond the scope of this post and pretty easy to figure out.

Let’s take a look at the role method. I store role names as CamelCase strings in the database but I access them with underscores which is more ruby like. The method looks like this:

Tying it all together

Now let’s go back to the situation I mentioned earlier – you want to protect user registrations. This requires us to use CanCan to check for permissions but customize the Devise Registrations controller to restrict access.

One way to do this is to copy the devise controllers into your controllers directory and start customizing. That may be the best way to go and it’s certainly an obvious path, but all I want to do restrict registration. Should I really have to re-implement the registrations controller to do that? For now, I will not. It might make sense when there are more customizations. Instead I inherit from the Devise Registrations controller. Here are the steps:

The check permissions method is really simple. It calls the CanCan method, authorize!, and checks if the current user can create users. We use resource here because devise uses resource to refer to the model that can be authenticated. Also notice how I removed the require_no_authentication filter, a Devise filter which allows access to actions without authentication.

Step 4 – Handle the CanCan::AccessDenied exception
At this point if you hit the users/sign_up page when not logged in, you will notice that a CanCan::AccessDenied is thrown. This exception is thrown anytime permission is denied so you should customize it to your liking. I put the handler in my ApplicationController:

I realize I skipped some steps in here but this post + Devise documentation + CanCan documentation should help you set up authentication with roles and permissions very quickly. Let me know if you have any questions. Enjoy!

I don’t like the Spotlight indexing and search that is included in Mac OS X. I use Quicksilver instead but have been procrastinating turning off Spotlight.

Well I finally got around to disabling Spotlight and wanted to go about it in a safe way. I came across too many forum posts doing dangerous things to disable Spotlight. I also wanted and easy way to remove it from the menu bar. Below are aliases I added to my bash profile to conveniently enable and disable spotlight. I am not a bash scripting master, so feedback is welcome and appreciated.

$ ps aux |grep SystemUIServer.app
# take note of the PID which is the first number you will see
$ kill-HUP<insert PID here>

You could potentially restart your computer instead of performing Step 4, but that is inconvenient. Let me know if you have any comments or a nice way to include everything in one script. I didn’t have time to condense this process further.