This screencast shows how to add a simple password authentication for your Ruby on Rails 4.2 application without using the big shots like Devise or OmniAuth (see ruby-toolbox.com for a list of popular authentication gems).
Create the Rails application
We start with a fresh Ruby on Rails application.
For the has_secure_password method we need the bcrypt gem. And because we don’t need a JSON API in this application deactivate the jbuilder gem.
After saving the Gemfile we need to run bundle.
Generate a Root Page
As a start we create a Page controller with an index view:
We use that view as the root_path:
We start the rails development server:
Fire up the browser and open http://0.0.0.0:3000
Generate a User scaffold
We use a User model to store the user information and the password digest. We do not store the password in clear text in the database.
In the User model we add a couple of validations and a to_s method.
Create a new user
We create the User “Jon Smith” with
Create a Session controller
Having a User model is nice but we need a Session mechanism to create a login and logout procedure. Because we live in a RESTful world login would be new plus create and logout would be destroy in a Sessions controller.
Now we create a couple of routes for this to work:
The login form is the new.html.erb view for a new Session.
The Session controller needs 3 actions:
With that we use the RESTful approach.
Create a current_user method
We need a mechanism to access the current_user everywhere in the application. For that we add a current_user method to the ApplicationController and use helper_method to provide a helper method for the views too.
To show a user if he/she is already logged in and if not where to login or where to sign up we add a little header HTML in application.html.erb
Additionally I add some code to show flash messages if there are any.
Because we render the flash messages in application.html.erb we can delete them in the following files:
Auto login when a new user signs up
When ever a new user signs up it makes sense for him to be logged in right away. That’s easy done by setting the session session[:user_id] = @user.id in the users_controller.rb.
In the next screencast I’ll show how to use this authentication to setup an authorization system which grands or denies access to specific users.