Simple Authentication Guide Create Authentication in Rails

Joshua Chipile
4 min readOct 28, 2021

--

We are going to create simple authentication in Rails. We want our users to add privilege to access certain web pages.

Authentication in Rails

Prerequisite:

  • Ruby version — 3.0
  • Rails version — 6.1.4
  • Rails Packages
  • Configuration of the rails app (to use rbenv — Rails virtual environment)
  • Creating new Rails Web App

Ruby and Rails versions

Before we start our Rails project,we need to ensure that we tick the items on the prerequisite list .

# Ruby and Rails version
1: Ruby 3.0
2: Rails 6.1.4
Ruby and Rails versions

Create our Simple Authentication web app

Ensure the project is in directory. To create new project in Rails type the command “rails new session_authentication”.

# Rails Simple  Authentication$ cd session_authentication
1: rails new session_authentication

Install Rails Packages

# Install Rails packages and bundle install$ cd session_authentication1: gem install bcrypt
2: gem install bootstrap-sass
3: bundle install

Below is an image of GemFile currently using for project.

Gemfile

Below is GemFile file currently used for our project.

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '3.0.2'# Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main'
gem 'rails', '~> 6.1.4', '>= 6.1.4.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~> 1.4'
# Use Puma as the app server
gem 'puma', '~> 5.0'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 5.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
gem 'bcrypt', '~> 3.1.7'
# Use Active Storage variant
# gem 'image_processing', '~> 1.2'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.4', require: false
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 4.1.0'
# Display performance information such as SQL time and flame graphs for each request in your browser.
# Can be configured to work on production as well see: https://github.com/MiniProfiler/rack-mini-profiler/blob/master/README.md
gem 'rack-mini-profiler', '~> 2.0'
gem 'listen', '~> 3.3'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 3.26'
gem 'selenium-webdriver'
# Easy installation and use of web drivers to run system tests with browsers
gem 'webdrivers'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'bootstrap-sass', '~> 3.4.1'

Model:

We going to create a model. The command will help us generate model for Authentication (users).

1: User Model

# Creating Models in rails$ cd session_authentication
rails g model user username password_digest

1a: User Model

Add the information in our user model:

class User < ApplicationRecord     
has_secure_password
end

2: Migrate database

# Migrate Database$ cd session_authentication
rails db:migrate

3: Controllers

Create controller in the app. Controller is the logical center of your application. The command will generate controllers (users).

# Create controllers for our rails project$ cd session_authenticationrails g controller sessions new create login welcomerails g controller users new create

4: Migrate the database

# Migrate Database  for the models we have created.$ cd session_authentication1: rails db:migrate

5: Routes

The routing module provides URL rewriting in native Ruby. We have custom routes for the Authentication project. $ session_authentication/config/routes.rb

Rails.application.routes.draw do
resources :users, only: [:new, :create]
get 'login', to: 'sessions#new'
post 'login', to: 'sessions#create'
get 'welcome', to: 'sessions#welcome'
get 'authorized', to: 'sessions#page_requires_login'
end

6: Views

Views : Shares data with controllers and model. View is saved as an erb program. A views created inside app/views/sessions/welcome.index.erb.

6a: Welcome Page

<h1>Welcome</h1>welcome.index.erb
<%= button_to "Login", '/login', method: :get%>
<%= button_to "Sign Up", '/users/new', method: :get%>

6b: Sign up

Creating sign up page.

app/views/users/new.html.erb

<h1>Sign Up</h1><%= form_for @user do |f|%>  
<%= f.label :username%><br> <%= f.text_field :username%>
<br> <%= f.label :password%><br>
<%= f.password_field :password%><br>
<%= f.submit %>
<%end%>

6c: New User

Creating new user.

app/views/sessions/new.html.erb

<h1>Login</h1>
<%= form_tag '/login' do %> <%= label_tag :username%>
<%= text_field_tag :username %>
<%= label_tag :password%>
<%= password_field_tag :password%>
<%= submit_tag "Login"%><%end%>

7: User Controller

7a: Users Controller is the logical of application.

app/controllers/users_controller.rb

class UsersController < ApplicationController
skip_before_action :authorized, only: [:new, :create]
def new
@user = User.new
end
def create
@user = User.find_by(username: params[:username])
if @user && @user.authenticate(params[:password])
sessions[:user_id] = @user.id
redirect_to '/welcome'
else
redirect_to '/login'
end

end
end

7b: Application Controller

Application Controller is the logical of application.

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

before_action :authorized
helper_method :current_user
helper_method :logged_in?
def current_user
User.find_by(id: session[:user_id])
end
def logged_in?
!current_user.nil?
end
def authorized
redirect_to '/welcome' unless logged_in?
end
end

7c: Sessions Controller

Sessions Controller is the logical of application.

app/controllers/sessions_controller.rb

class SessionsController < ApplicationControllerskip_before_action :authorized, only: [:new, :create, :welcome]

def new
end
def create
user = User.find_by(username: params[:username])
if user && user.authenticate(params[:password])
sessions[:user_id] = user.id
redirect_to '/welcome'
end
end
def welcome

end
def login
end
def page_requires_login
end

end

You clone the repo github and modify the code

The End. Happy coding :)

--

--

Joshua Chipile

Software Developers Advocate||Software Engineer /Software Developer|| Technical Write || Trainer || OSCA- Lusaka - Lead