Last week I spoke at Silicon Valley Ruby Group about PlataformaTec’s open source tools, mainly Devise, Simple Form and Responders.
When talking about Devise, I’ve mentioned that, before creating Devise, we were alternating between using Authlogic or Clearance in our projects. However, we soon realized that we needed a solution that was as customizable as Authlogic (allowing us to choose behaviors and several configuration options) and as complete as Clearance (whole MVC stack). It is fun to remember this happened more than 2 years ago.
After the presentation, someone came to talk to me about Sorcery and said it would be nice if Devise provided the same kind of tooling, allowing someone to build their own controllers and views around Devise instead of using Devise built-in controllers and views. His proposal surprised me, because this approach is totally possible with Devise and it was one of our design goals since day one.
That said, we realized that we were probably not “advertising” the bare-bone, stripped-down aspect of Devise well enough. That’s why I am writing this blog post. Devise already makes it easy for you to customize your own views, using the generator rails g devise:views
which copies the views to your application. But what if you want to roll out your own views AND controllers?
To show you how we can achieve that, let’s write some code! The first step is to create a Rails application:
rails new devise-only-model
Next, we will add Devise to the Gemfile:
gem "devise", "~> 1.4.6"
And run the installation generator:
bundle install && rails g devise:install
The installation generator is going to give you some extra instructions, so don’t forget to do that as well. Next, let’s generate our basic User model, but we will pass an extra parameter called --skip-routes
:
rails g devise User --skip-routes
By passing this extra parameter, Devise is going to generate everything as usual, with a small difference on config/routes.rb
:
devise_for :users, :skip => :all
This parameter tells Devise to not generate any route at all. You can check that by executing bundle exec rake routes
. However, you may be wondering: why can’t we simply remove the devise_for
call? If we remove the route, Devise wouldn’t actually know that you have added Devise configuration to the User model, as all models are lazy loaded. So we need the route to tell Devise it needs to setup the appropriate helpers for the user, like authenticate_user!
.
With Devise configured, we are ready to create the controllers and views on our own. In this blog post, we are going to create the SessionsController
as an example allowing us to sign in and sign out. First, let’s add our routes:
root :to => "sessions#new"
post "/users/sign_in" => "sessions#create"
delete "/users/sign_out" => "sessions#destroy"
Our SessionsController
at app/controllers/sessions_controller
looks like:
class SessionsController :create
def new
@user = User.new(params[:user])
end
def create
# Since the authentication happens in the rack layer,
# we need to tell Devise to call the action "sessions#new"
# in case something goes bad. Feel free to change it.
user = authenticate_user!(:recall => "sessions#new")
flash[:notice] = "You are now signed in!"
sign_in user
redirect_to root_path
end
def destroy
sign_out
flash[:notice] = "You are now signed out!"
redirect_to root_path
end
end
The controller implementation is quite straightforward. With the controller in hands, we just need to generate the view for the new action at app/views/sessions/new.html.erb
:
<% if user_signed_in %>
You are signed in as <% current_user.email %>. <% link_to out users_sign_out_path :method=""> :delete %>.
<% else %>
<% form_for @user :url=""> users_sign_in_path do |f| %>
<% f.label :email %>
<% f.email_field :email %>%>%>
<% f.label :password %>
<% f.password_field :password %>%>%>
<% f.check_box :remember_me %> <% f.label :remember_me %>%>%>
<% f.submit in %>%>
<% end %>
<% end %>
%>%>%>%>%>%>%>
The view shows a message if the user is signed in, otherwise it shows a sign in form. Now we are almost ready to check if it works. First, we need to run the migrations:
bundle exec rake db:migrate
Remove the index page:
rm public/index.html
And create a user in the database so we can sign in. We can do that in rails console
:
User.create!(:email => "jose@example.com", :password => "123456")
Now, start the server and you are ready to sign in and sign out. You can also block user access in any controller by calling authenticate_user!
in a before filter. Just remember that, if you add the filter to your application controller, remember to skip the filter on the sessions controller, otherwise you won’t be able to sign in in the first place.
You can now freely proceed to implement the other controllers and views in your application. Keep in mind that if you have devise :recoverable
in your model, all the related methods like User.send_reset_password_instructions
will already be available in your model, so you can use them straight away to implement your own reset password feature. Since Devise use all those methods internally, if you have any questions about implementing your own reset password feature, you can always take a look at Devise own controllers for some help.
I hope this post can help you to roll out your own controllers if this is the kind of feature you expect from Devise. Also, if you are worried about the overhead of using Devise even if you are not using its controllers, there is no need to worry at all. Devise does the smart thing and only loads the controllers you are actually using. Also, it lazily loads all behaviors, so if you are not using recoverable, no code related to recoverable will be loaded at all.
It is important to keep in mind that Devise was built by us to be flexible and capable of handling different requirements from different clients, so it is PlataformaTec’s priority to have it as flexible as possible! So, what would you like to see in “bare-bone, stripped-down Devise” in order to better use it in your applications?
Hmmm, quite useful.
I’ll give it a try!
Thanks for posting this kind of ultrahelper posts.
Devise Rocks!
I’m glad you took some time to write this article and I really would like to see more article on behind-the-scene topics, just like you did in your wonderful book.
Cool thanks. It’s the controllers in the engine that’s stopped me using devise in the past.
Great Jose, the custom controllers are what my team needs. For a bare-bones stripped-down authentication, how about removing password confirmation from the model, and letting the app do it elsewhere like in the controller?
Great Jose, the custom controllers are what my team needs. For a bare-bones stripped-down authentication, how about removing password confirmation from the model, and letting the app do it elsewhere like in the controller?
Hey Joel, you can already roll out your own confirmation settings as well by simply removing the validatable from your model. Then you can validate on the controller as you wish!
Hey Joel, you can already roll out your own confirmation settings as well by simply removing the validatable from your model. Then you can validate on the controller as you wish!
I love information like this – explaining the intentions and goals behind a project like devise is great. Following it up with practical examples is even better.
I’m trying to understand Devise so I can understand its relationship to Refinery CMS. This has helped me take another couple of steps along the route.
Thanks.
I love information like this – explaining the intentions and goals behind a project like devise is great. Following it up with practical examples is even better.
I’m trying to understand Devise so I can understand its relationship to Refinery CMS. This has helped me take another couple of steps along the route.
Thanks.
This is great. just wish we had a generator for the controllers. Good job on Devise!
THANK YOU!!! I so appreciate this site.This is news I need to know.