deviceを使用したログイン機能

deviseを利用したログイン機能について

まずはgemfileに追加しましょう

```
gem 'devise'
```
bundle installを実行するのは忘れず行う
```
bundle install
```
その後下記の順に行っていく
```
rails g devise:install

rails g devise User
```
deviseで認証するため生成されたmigrationファイル確認しnameとintroductionを追加

```_devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration[6.1]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      # t.integer  :sign_in_count, default: 0, null: false
      # t.datetime :current_sign_in_at
      # t.datetime :last_sign_in_at
      # t.string   :current_sign_in_ip
      # t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      #ここから追加
      t.string :name
      t.text :introduction
      #ここまで
      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

```

rails db:migrateを忘れず行う


ルートの設定
routes
```config/routes.rb
Rails.application.routes.draw do
  devise_for :users

end
```
modelのuser.rbを確認する

```app/models/user.rb

devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :validatable

```

application_controller.rbを確認し追加

```controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  private

  def after_sign_in_path_for(resource)
    user_path(resource)
  end

  def after_sign_out_path_for(resource)
    root_path
  end

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:email])
  end
end
```
rails g devise:viewsを行い
viewファイルを確認する

ホーム画面に新規登録機能とログイン機能
```app/views/homes/top.html.erb

div class="container">
  <div class="row">
    <div class='mx-auto col-11 col-sm-10 col-lg-8 col-xl-6'>
      <h1>welcome to <i class="fas fa-book"></i><strong>Bookers</strong>  !!</h1>
      <p>In  <i class="fas fa-book"></i><strong>Bookers</strong>, </p>
      <p>you can share and exchange  your opinions , inpressions , and emotions</p>
      <p> about various books!</p>
      <div class="btn-wrapper col-10 mx-auto">
        <div class="row">
          <%= link_to 'Log in',new_user_session_path, class: "btn btn-info btn-sm btn-block mb-3 sign_in" %>
        </div>
        <div class="row">
          <%= link_to 'Sign Up',new_user_registration_path, class: "btn btn-success btn-sm btn-block sign_up" %>
        </div>
      </div>
    </div>
  </div>
</div>
```
   
ユーザーの新規登録するためのviewファイル

```/devise/registrations/new.html.erb
<div class='container'>
  <div class='row'>
    <div class="col-sm-12 col-md-8 col-lg-5 px-5 px-sm-0">
      <h2>Sign up</h2>
      <%= form_with model: @user, url: user_registration_path, id: 'new_user', class: 'new_user', local: true do |f| %>
        <%= render "devise/shared/error_messages", resource: resource %>

       #ここから追加
        <div class="field">
          <%= f.label :name %><br />
          <%= f.text_field :name, autofocus: true, class: "name" %>
        </div>
　　　　#ここまで

        <div class="field">
          <%= f.label :email %><br />
          <%= f.email_field :email, autofocus: true, class: "email" %>
        </div>
        <div class="field">
          <%= f.label :password %>
          <% if @minimum_password_length %>
          <em>(<%= @minimum_password_length %> characters minimum)</em>
          <% end %><br />
          <%= f.password_field :password, autocomplete: "off", class: "password" %>
        </div>
        <div class="field">
          <%= f.label :password_confirmation %><br />
          <%= f.password_field :password_confirmation, autocomplete: "off", class: "password_confirm" %>
        </div>
        <div class="actions">
          <%= f.submit "Sign up" ,class: 'btn btn-sm btn-success' %>
        </div>
      <% end %>
      <%= render "devise/shared/links" %>
    </div>
  </div>
</div>

```
ユーザーのログイン画面のviewファイルの確認を行う

```app/views/devise/sessions/new.html.erb
<div class='container'>
  <div class='row'>
    <div class="col-sm-12 col-md-8 col-lg-5 px-5 px-sm-0">
      <h2>Log in</h2>
      <%= form_with model: @user, url: session_path(resource_name), local: true do |f| %>
        <div class="field">
          <%= f.label :name %><br />
          <%= f.text_field :name, autofocus: true, class: "name" %>
        </div>
        <div class="field">
          <%= f.label :password %><br />
          <%= f.password_field :password, autocomplete: "off", class: "password" %>
        </div>
        <% if devise_mapping.rememberable? -%>
          <div class="field">
            <%= f.check_box :remember_me %>
            <%= f.label :remember_me %>
          </div>
        <% end -%>
        <div class="actions">
          <%= f.submit "Log in" ,class: 'btn btn-sm btn-primary'%>
        </div>
      <% end %>
      <%= render "devise/shared/links" %>
    </div>
  </div>
</div>

```

課題3を作成した際に必要になる部分で確認しとく部分を入れてみました