Community for developers to learn, share their programming knowledge. Register!
User Authentication and Authorization

Creating User Registration and Login Forms in Ruby on Rails


Welcome to our article on Creating User Registration and Login Forms in Ruby on Rails! Here, you can get training on how to effectively implement user authentication and authorization systems in your Rails applications. This topic is crucial for any web application, and mastering these concepts will enhance your development skills and improve the security of your applications.

Building User Registration Forms

When developing a web application, the first step in user authentication is often the creation of a user registration form. In Ruby on Rails, this process can be streamlined using built-in form helpers and strong parameters.

Setting Up the User Model

First, you need to generate a User model. Open your terminal and run the following command:

rails generate model User username:string email:string password_digest:string

This command creates a new User model with the necessary fields. The password_digest field is essential for securely storing user passwords using encryption.

Next, migrate the database to create the corresponding table:

rails db:migrate

Installing bcrypt

To handle password hashing, you’ll need the bcrypt gem. Add it to your Gemfile:

gem 'bcrypt', '~> 3.1.7'

Run bundle install to install the gem, and then update your User model to include password handling:

class User < ApplicationRecord
  has_secure_password
end

The has_secure_password method adds functionality for securely managing user passwords, including validations and methods for authentication.

Creating the Registration Form

Now, let’s create a registration form. In your UsersController, add the following methods:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to root_path, notice: 'User registered successfully!'
    else
      render :new
    end
  end

  private

  def user_params
    params.require(:user).permit(:username, :email, :password)
  end
end

In the new.html.erb view, create the form:

<%= form_with model: @user, local: true do |form| %>
  <div>
    <%= form.label :username %>
    <%= form.text_field :username %>
  </div>

  <div>
    <%= form.label :email %>
    <%= form.email_field :email %>
  </div>

  <div>
    <%= form.label :password %>
    <%= form.password_field :password %>
  </div>

  <div>
    <%= form.submit 'Register' %>
  </div>
<% end %>

This simple form captures the username, email, and password from the user.

Implementing Login Functionality

After creating a registration form, the next step is to implement the login functionality. This allows users to access their accounts after registration.

Setting Up Sessions

Rails provides a simple way to manage user sessions. In your SessionsController, add the following methods:

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:email])
    if user&.authenticate(params[:password])
      session[:user_id] = user.id
      redirect_to root_path, notice: 'Logged in successfully!'
    else
      flash.now[:alert] = 'Invalid email or password'
      render :new
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_path, notice: 'Logged out successfully!'
  end
end

Creating the Login Form

Create the login form in new.html.erb within your sessions view:

<%= form_with url: login_path, local: true do |form| %>
  <div>
    <%= form.label :email %>
    <%= form.email_field :email %>
  </div>

  <div>
    <%= form.label :password %>
    <%= form.password_field :password %>
  </div>

  <div>
    <%= form.submit 'Login' %>
  </div>
<% end %>

Routing for Sessions

Ensure you have the necessary routes in your config/routes.rb file:

Rails.application.routes.draw do
  resources :users, only: [:new, :create]
  get 'login', to: 'sessions#new'
  post 'login', to: 'sessions#create'
  delete 'logout', to: 'sessions#destroy'
end

With these routes set up, users can access the login page and authenticate themselves.

Validating User Input

Validating user input is essential for maintaining application integrity and security. In this section, we will implement validations in the User model to ensure that user data is both accurate and secure.

Adding Validations

In your User model, you can add the following validations:

class User < ApplicationRecord
  has_secure_password
  
  validates :username, presence: true, uniqueness: true
  validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }
  validates :password, presence: true, length: { minimum: 6 }
end

These validations ensure that:

  • The username is unique and present.
  • The email is unique, present, and follows a valid format.
  • The password is present and has a minimum length of six characters.

Error Handling in Views

To provide feedback to users when validations fail, you can update your form views to display error messages. For example, in new.html.erb for user registration, add the following code at the top:

<% if @user.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
    <ul>
      <% @user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
    </ul>
  </div>
<% end %>

This block will render any validation errors, helping users correct their input.

Summary

In this article, we covered the essential steps for Creating User Registration and Login Forms in Ruby on Rails. We explored how to build user registration forms, implement login functionality, and validate user input for security and integrity. Understanding these components is vital for any developer looking to enhance user authentication and authorization in their Rails applications.

By mastering these concepts, you will not only improve your skills but also ensure that your applications are robust and secure. For further reading, consider checking out the Ruby on Rails Guides and the official bcrypt documentation for more in-depth information.

Last Update: 31 Dec, 2024

Topics:
Ruby on Rails