[RUBY] [Implementation procedure] Create a user authentication function using sorcery in Rails

Note that I had a hard time implementing the authentication function in Rails

Work environment

What is sorcery

A library for implementing authentication functions in Rails. Similarly, devise is one of the authentication functions, but sorcery is simpler and more customizable. Click here for sorcer's github

Implementation procedure

installation of sorcery

Gemfile


gem 'sorcery'

Terminal


$ bundle install

Generate User model and migration file

Terminal


$ rails g sorcery:install

By typing the above command, the migration file of the user model and database will be generated. ・ App / models / user.rbConfig / initializers / sorcery.rbDb / migrate / yyyymmddhhmmss_sorcery_core.rb

Constraint the database

db/migrate/yyyymmddhhmmss_sorcery_core.rb


class SorceryCore < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      t.string :name, null: false
      t.string :email, null: false
      t.string :crypted_password
      t.string :salt, null: false

      t.timestamps null: false
    end

    add_index :users, :email, unique: true
  end
end

This time, let's assume that we have columns for name, email, and password.

--Added null: false to the required items.

--The reason for putting restrictions is that if you do not put restrictions on the database side, executing SQL or directly manipulating data may result in inconsistent data prohibited by the model.

--Add to add_index for items that you want to make uniqueness: true in the model. The description method for add_index is as follows. add_index: table name,: column name, unique: true

Terminal


$ rails db:migrate

--After describing the restrictions on migration, generate the users table with the above command.

Constraint the User model

app/modeks/user.rb


class User < ApplicationRecord
  authenticates_with_sorcery!
  validates :name, presence: true, length: { maximum: 255 } #Constraint length with length
  validates :email, presence: true, uniqueness: true #Constraint uniqueness with uniqueness
  validates :password, length: { minimum: 3 }, if: -> { new_record? || changes[:crypted_password] }
  validates :password, confirmation: true, if: -> { new_record? || changes[:crypted_password] }
  validates :password_confirmation, presence: true, if: -> { new_record? || changes[:crypted_password] }
end

--By writing presence: true, you can prevent SQL from saving in an empty state without inputting empty characters from the browser.

--Since I added the constraint (null: false and add_index: users,: email, unique: true) on the database side, Let's also constrain (presence: true or uniqueness in validates) on the model side.

Generate users controller

Terminal


$ rails g controller users new create

app/controllers/users_controller.rb


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

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to login_path
    else
      render :new
    end
  end

  private

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

--If user registration is successful with create action, redirect to the login screen. If it fails, you can return to the login screen again.

Generation of user registration screen (new registration)

ruby:app/views/users/new.html.erb


<%= form_with model: @user, local: true do |f| %>
  <div class="form-group">
    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :email %>
    <%= f.text_field :email, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :password %>
    <%= f.text_field :password, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :password_confirmation %>
    <%= f.text_field :password_confirmation, class: 'form-control' %>
  </div>
  <%= f.submit 'Registration', class: 'btn btn-primary' %>
<% end %>
<div class='text-center'>
  <%= link_to 'Go to login page', login_path %>
</div>

--Template for user registration.

--How to use form_with. Pass the entered value to the instance variable @user! Declared. It can also be described as users_path. The data entered here is sent to create. The contents of the form are in user_params or params [: user].

Recommended Posts

[Implementation procedure] Create a user authentication function using sorcery in Rails
Create authentication function in Rails application using devise
Implementation of user authentication function using devise (2)
Creating a user authentication function using devise
Implementation of user authentication function using devise (1)
Implementation of user authentication function using devise (3)
Create a login authentication screen using the session function
Add a search function in Rails.
[Rails] Implementation of user withdrawal function
Create a new app in Rails
Create a filtering function using acts-as-taggable-on
[Rails] Comment function implementation procedure memo
Let's create a TODO application in Java 4 Implementation of posting function
Let's create a TODO application in Java 6 Implementation of search function
Let's create a TODO application in Java 8 Implementation of editing function
[Rails] Create an evaluation function using raty.js
[Rails withdrawal] Create a simple withdrawal function with rails
Rails Basic CRUD function implementation procedure scaffold
Create a login function using Swift's Optional
How to create a query using variables in GraphQL [Using Ruby on Rails]
[Rails] I will explain the implementation procedure of the follow function using form_with.
Create a SPA with authentication function with Rails API mode + devise_token_auth + Vue.js 3 (Rails edition)
[Rails] Implementation of search function using gem's ransack
[Rails 6] Implementation of inquiry function using Action Mailer
[Rails] Implementation of image enlargement function using lightbox2
Implement star rating function using Raty in Rails6
[Rails] Implementation of retweet function in SNS application
[Rails] I made a draft function using enum
How to easily create a pull-down in Rails
[For beginners] Procedure for creating a controller using rails
How to make a follow function in Rails
# 6 show, create implementation to build bulletin board API with authentication authorization in Rails 6
Build a bulletin board API with authentication authorization in Rails 6 # 5 controller, routes implementation
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
A memo to simply create a form using only HTML and CSS in Rails 6
Create a drag-and-drop markdown editor in Rails 6 (using Active Storage, SimpleMDE and Inline Attachment)
[rails] gem'payjp' implementation procedure
Create an EC site with Rails 5 ⑨ ~ Create a cart function ~
Implement user follow function in Rails (I use Ajax) ②
[Rails] Implementation of multi-layer category function using ancestry "Preparation"
[Rails] Implementation of multi-layer category function using ancestry "seed"
I want to define a function in Rails Console
Rails search function implementation
Implement user follow function in Rails (I use Ajax) ①
[Rails] Implementation of SNS authentication (Twitter, Facebook, Google) function
Build a bulletin board API with authentication and authorization with Rails # 18 ・ Implementation of final user controller
Build a bulletin board API with authentication authorization in Rails # 12 Association of user and post
[Rails] Implementation of multi-layer category function using ancestry "Creation form"
[Rails DM] Let's create a notification function when DM is sent!
Rails sorting function implementation (displayed in order of number of like)
[Rails] Implementation of tagging function using intermediate table (without Gem)
Create a tomcat project using Eclipse Pleiades All in One
[Apple login] Sign in with Apple implementation procedure (Ruby on Rails)
Implement user registration function and corporate registration function separately in Rails devise
Implement application function in Rails
Rails fuzzy search function implementation
[Rails] Implement User search function
Search function using [rails] ransack
SNS authentication using Rails google
Implement follow function in Rails
Japaneseize using i18n with Rails