Updates to SimplestAuth

I recently committed a set of changes to simplest_auth on Github that I'd like to cover. I'll start with the simple changes and bug-fixes and move into more complex stuff. All of these changes abide by our original goal to do what needs to be done and stay out of the user's way otherwise.

The first change is that the user_class method we used to require be defined to return the class you're using for users will now default to User.

Second, the password is hashed automatically before create if a password is required. Which brings us nicely into the next change: password_required? is now defined for you to check for an empty crypted_password or the existence of a new password. If the situation arises that you need additional logic feel free to override this method and know that it will be checked.

Onto a larger change: a new macro to define the field by which to authenticate a user. Previously, your user class was required to have both crypted_password and an email address. After much deliberation I added authenticate_by to define the field by which to find your users. For example:

 class User < ActiveRecord::Base include SimplestAuth::Model authenticate_by :username end 

This will properly define an authenticate method which will take the username and password. The aforementioned method will then try and find_by_username to locate the appropriate user before checking that their password matches.

Finally, it isn't new but I would like to highlight the use of authorized? in a controller. In this contrived example we want to require login to everything except the index and show actions. In addition, we want the user that is logged in to have a fancy premium account, denoted by a simple boolean flag.

 class BooksController < ApplicationController before_filter :login_required, :except => [:index, :show] def index; end def new; end def create; end def show; end def edit; end def update; end def destroy; end private def authorized? logged_in? && current_user.premium? end end 

To control what happens to a user if they fail to pass authorization you can override the methods access_denied (to redirect and display a flash message) and/or login_message to simply change the message displayed.

I hope this extra information helps to illuminate these new additions and give more insight into the flow around authentication and authorization in the controller.

The original simplest_auth announcement

simplest_auth Github Documentation

Tony Pitale

Posted in Article Category: #Code