af83

Request authentication from the router with devise

Devise is an awesome authentication engine for Ruby on Rails, based on the Warden middleware.

I will not present you Devise in depth, there's already a ton of resources about this topic, I will just present a feature I find very useful.

Request authentication from the router

Devise allow you to do the latter :

AwesomeRailsApplication::Application.routes.draw do
  devise_for :administrators

  authenticate :administrator do
    resources :users
  end
end

What happens here ?

devise_for will generate all the routes for administrator authentication.

authenticate is the interesting part. To access the resources defined in the authenticate, an administrator has to be loggued.

This has the same effect as adding this code in your protected controllers :

before_filter :authenticate_administrator!

But, directly from the router.

Authenticate rack app with devise.

As a Rails app grows, it's common to use rack app to add features. The most common case is probably the web interface provided by Resque, but it can also be a rails engine, or a sinatra application. Well, any rack app.

But you probably don't want to expose those apps to anyone.

AwesomeRailsApplication::Application.routes.draw do
  devise_for :administrators

  authenticate :administrator do
    mount AwesomeEngine::Engine => "/awesome"
    mount Resque::Server        => "/resque"
  end
end

In this example, Resque::Server and the AwesomeEngine::Engine rails engine are protected by Devise with the same authenticate method, only administrators have access to those resources.

Other benefit of this method : administrators only have to log in once.

This is possible thanks to Devise, Warden and Rack.

blog comments powered by Disqus