sorceryを使ってユーザー登録、ログイン機能の作成

Gemfileに

gem 'sorcery'を追加

budnel installをする

 

次にrails g sorcery:installを行う。

user.rb usersテーブルを作成するためのマイグレーションファイルができるのでrake db:migrateでusersテーブルを作成する

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

t.timestamps null: false
end

add_index :users, :email, unique: true
end
end
 
バリデーション
class User < ApplicationRecord
authenticates_with_sorcery!

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] }

validates :email, uniqueness: true
end
 バリデーションはsorceryの実装方法のままにする。
 uniqueness: true 一意であり重複していないかを検証する
 
routes.rbでルーティングを設定する
Rails.application.routes.draw do
root :to => 'users#index'
resources :users
end
 
rails g controller usersでコントローラーを作成
プライベートメソッドを作成しストロングパラメータという仕組みを利用して
入力された内容が安全かを確認する。
newアクション、createアクションを追加する
class UsersController < ApplicationController
def new
@user = User.new
end

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

private

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

次にビューを作成

form_withは情報を送信するためのヘルパーメソッド

form_withにlocal: trueをつけることでHTMLとフォームを送信できる

local: tureをつけないとajaxになる

<%= form_with model: @user, local: true do |f|%>
 
<%= f.label :email%>
<%= f.text_field :email%>
 
<%= f.label :password%>
<%= f.password_field :password%>
 
<%= f.label :password_confirmation%>
<%= f.password_field :password_confirmation%>

<%= f.submit %>
<% end %>

これでユーザー登録機能は一応完成です。

 

次にログイン機能の作成

rails g controller UserSessions new create destroy

user_sessions.rbにcreateアクションを追加

class UserSessionsController < ApplicationController
def new; end

def create
@user = login(params[:email], params[:password])

if @user
redirect_to root_path
else
render :new
end
end

def destroy
logout
redirect_to root_path
end
end

次にルーティングを設定

ルーティングもsorceryのwikiのまま設定する

get 'login' => 'user_sessions#new', :as => :login
post 'login' => 'user_sessions#create'
post 'logout' => 'user_sessions#destroy', :as => :logout

ログインフォームの作成

<h1>ログイン</h1>
<%= form_with url:login_path, method: :post do |f|%>
 
<%= f.label :email %>
<%= f.text_field :email %>
 
<%= f.label :password %>
<%= f.password_field :password%>

<%= f.submit %>
<% end %>

これでsorceryを使ってユーザー登録、ログイン機能の実装は完了です。