[RUBY] Login function implementation with rails


This is a post following Last time! This time, I will summarize the implementation of the login function! !!

table of contents

  1. Create User Model (#Chapter1)
  2. Introduce gem
  3. Add to user.rb
  4. Login function implementation
  5. Get login information
  6. Implementation of logout function
  7. What to do if you are not logged in
  8. References

<!-Each chapter->

Create User model

First, create a User model.

rails g model User name:string email:string password_digest: string

Do this and rails db: migrate. password_digest is a naming convention when using the standard Rails function has_secure_password.

Introduced gem

The password_digest created earlier contains an irreversible hash of the entered password. If you save the password in the DB as it is, it is very dangerous if it leaks, so doing so will prevent leakage. Therefore, we will introduce a gem called "bcrypt" that provides a hash function.

gem 'bcrypt', '~> 3.1.7'

After adding to the gemfile, bundle install.

Added to user.rb

After introducing gem, there is only one thing to do. Add the following.



You're ready to go! Next, we will implement the controller.

Login function implementation

The login function is realized by holding the user's id in the session [: user_id]. First, create sessions_controller.rb with a new method for login.

rails g controller Sessions new 

This new action is the transition to the login screen. This time, I made the following form.

h1 login

= form_with scope: :session, local: true do |f|
    = f.label :email, 'mail address'
    = f.text_field :email, class: 'form-control', id: 'session_email'
    = f.label :password, 'password'
    = f.password_field :password, class: 'form-control', id: 'session_password'
  = f.submit 'log in', class: 'btn btn-primary'

Login process is performed based on the sent parameters. First, edit the routes.


  get '/login', to: 'sessions#new'
  post '/login', to: 'sessions#create' //Add here


  def create
    //Search the users table for a matching email address.
    user = User.find_by(email: session_params[:email])
    //If the email address exists, password authentication is performed with the authenticate method.
    if user&.authenticate(session_params[:password])
      //After successful authentication, hold the user's id in session.
      session[:user_id] = user.id
      redirect_to root_url, notice: 'You are now logged.'
      render :new

  def session_params
    params.require(:session).permit(:email, :password)

Get login information

You can get the user's information with the following code.

User.find_by(id: session[:user_id])

However, it is troublesome to write this every time, so define a variable called current_user in application.rb so that it can be used from any controller. Also, specify helper_method and write it so that it can be used in view!


  helper_method :current_user

  def current_user
    // session[:user_id]If there is a value in (if you are logged in),@current_Store login user information in user
    @current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]

Logout function implementation

The logout function is realized by deleting session [: user_id].


delete 'logout', to: 'session#destroy'


  def destroy
    redirect_to root_url, notice: 'logged out'

The view looks like this


- if current_user
  li.nav-item= link_to 'Log out', logout_path, method: :delete, class: 'nav-link'
- else
  li.nav-item= link_to 'Login', login_path, class: 'nav-link'

What to do if you are not logged in

If you want to disable all features without logging in, add a method to application_controller.


before_action :login_required

  def login_required
    // current_user is nil(Not logged in)When redirecting to the login screen
    redirect_to login_url unless current_user

In the case of the above description, it will be a chaotic situation that you can not see the login screen unless you log in. Therefore, only session_controller removes this restriction.


  skip_before_action :login_required


-Ruby on Rails 5 Quick Learning Practice Guide that can be used in the field

Recommended Posts

Login function implementation with rails
Make a login function with Rails anyway
Rails search function implementation
Implementation of Ruby on Rails login function (Session)
[Rails 6] Implementation of search function
[Rails] Implementation of category function
Login function with Spring Security
[Rails] Implementation of tutorial function
[Rails] Implementation of like function
[Rails 6] Pagination function implementation (kaminari)
Ruby on Rails <2021> Implementation of simple login function (form_with)
[Rails] Implementation of drag and drop function (with effect)
Implementation of Ruby on Rails login function (devise edition)
Login function
[Rails] Implementation of CSV import function
[Rails] Asynchronous implementation of like function
[rails] Login screen implementation in devise
Implemented mail sending function with rails
[Rails] About implementation of like function
[Rails] Implementation of user withdrawal function
[Rails] Implementation of CSV export function
Implement simple login function in Rails
[Rails] gem ancestry category function implementation
[Ruby on Rails] Comment function implementation
[Rails 6] Like function (synchronous → asynchronous) implementation
[Rails] Comment function implementation procedure memo
[Ruby on Rails] Implement login function by add_token_to_users with API
[Apple login] Sign in with Apple implementation procedure (Ruby on Rails)
Implement login function simply with name and password in Rails (3)
[Rails] Function restrictions in devise (login / logout)
DM function implementation
Rails Addition of easy and easy login function
[Rails 6] Ranking function
[Rails withdrawal] Create a simple withdrawal function with rails
[Ruby on Rails] Follow function implementation: Bidirectional
[Rails] Category function
Rails [For beginners] Implementation of comment function
Rails follow function
Rails Basic CRUD function implementation procedure scaffold
[Rails 6] Implementation of SNS (Twitter) sharing function
[Vue.js] Implementation of menu function Implementation version rails6
[Ruby on rails] Implementation of like function
[Vue.js] Implementation of menu function Vue.js introduction rails6
Login function implementation by Spring Security (securityConfig)
[Rails] Notification function
[Rails] Implementation of search function using gem's ransack
Validation settings for Ruby on Rails login function
[Rails 6] Implementation of inquiry function using Action Mailer
Today's learning summary: With user management function implementation
[Rails] Implementation of image enlargement function using lightbox2
[Rails 6.0] "Easy login" implementation procedure required for portfolio
Try to implement login function with Spring Boot
[Rails] Implementation of retweet function in SNS application
Ruby on Rails Email automatic sending function implementation
Let's make a search function with Rails (ransack)
[Note] Summary of rails login function using devise ①
Create an EC site with Rails 5 ⑩ ~ Create an order function ~
Rails hashtag search implementation
Rails6 countdown timer implementation
[rails] gem'payjp' implementation procedure
Comment function (Ajax) implementation