LoginSignup
0
0

More than 3 years have passed since last update.

アプリ作成の流れ④【パスワード認証機能】

Last updated at Posted at 2020-08-31

前回は

検索機能を実装しました。
https://qiita.com/ksyantaro/private/af201b653cf55ad6f31c

目次

  1. パスワード認証機能

パスワード認証機能

  • メールアドレスとパスワードの2つを入力してデータベースに保存されているユーザーと一致したらログインさせるといった機能。
  • SQLにおけるWHEREを指定してSELECT。
  • 入力されたメールアドレスに一致するユーザーを取得して、入力されたパスワードが合っているかを判定する。
  • パスワードはハッシュ化してデータベースに保存する。

gem 'devise'を使わずに実装していくこともできる

ただし、以下の記事からわかるように
- 自分で作ると脆弱性の可能性
- 車輪の再発明になる可能性
- 時間がかかる
といった問題点が出てきます。

【参考記事】
問題点
https://teratail.com/questions/66458
作り方
https://qiita.com/kodaii/items/13b73cc687ee3b7db051

deviseを使い、その仕組みを理解していくほうがいいのではないかという結論に至りました。

今回は'devise'で実装していく

'devise'によって、認証系の機能を簡単に実装することができる。

【参考記事】
deviseの使い方(rails6版)
https://qiita.com/cigalecigales/items/16ce0a9a7e79b9c3974e

deviseのインストール

Gemfile

  gem 'devise'

ターミナル

% bundle install

% rails g devise:install
とすると以下のような記述が出てくる。

Running via Spring preloader in process 48598
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================

Depending on your application's configuration some manual setup may be required:

  1. Ensure you have defined default url options in your environments files. Here
     is an example of default_url_options appropriate for a development environment
     in config/environments/development.rb:

       config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

     In production, :host should be set to the actual host of your application.

     * Required for all applications. *

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root to: "home#index"

     * Not required for API-only Applications *

  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:

       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>

     * Not required for API-only Applications *

  4. You can copy Devise views (for customization) to your app by running:

       rails g devise:views

     * Not required *

===============================================================================

デフォルトURLの指定

config/environments_development.rb
Rails.application.configure do

  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

end

rootパスの指定

自分の場合はすでに指定しているので大丈夫。

指定していない場合はconfig/routesにて
rootを指定しよう。

flashメッセージの追加

layouts/application.html.haml

  %body
    %p.notice
      = notice
    %p.alert
      = alert
    = yield

deviseのviewsを追加する

ターミナル
% rails g devise:views

Userモデルを作成・編集する

Userモデルの作成

ターミナル
% rails g devise user

nameカラムの追加

migrate/2020XXXXXXXXXX_devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :name,              null: false, default: ""
      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

   ~~~~~~~~~~~省略しています~~~~~~~~~~~

      t.timestamps null: false
    end

    add_index :users, :name,                unique: true
    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true

  end
end

models/user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  以下を追記しています!
  validates :name, presence: true, uniqueness: true

end

忘れずにrails db:migrateします!

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

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
  end
end

ビューの編集

deviseのビューがerbなので、hamlに変更。

ターミナル
% rails haml:erb2haml

nameの新規登録と編集ができるように

ログインはメールアドレスとパスワードでいけるようにします。

registrations/new.html.haml

  .field
    = f.label :name
    %br/
    = f.text_field :name, autofocus: true, autocomplete: "name"

これを追加します。
emailのものをコピーして少し編集するのがおすすめ。
email_fieldはtext_fieldにしましょう。

registrations/edit.html.haml

  .field
    = f.label :name
    %br/
    = f.text_field :name, autofocus: true, autocomplete: "name"
  - if devise_mapping.confirmable? && resource.pending_reconfirmation?
    %div
      Currently waiting confirmation for: #{resource.unconfirmed_name}

これを追加します。
emailのものをコピーして少し編集するのがおすすめ。
email_fieldはtext_fieldにしましょう。

ログイン時とログアウト時の表示の変更

layouts/application.html.haml

  %body
    %header
      %nav
        - if user_signed_in?
          %strong
            = link_to current_user.name, blog_path(current_user.id)
          = link_to 'プロフィール変更', edit_user_registration_path
          = link_to 'ログアウト', destroy_user_session_path, method: :delete
        - else
          = link_to 'サインアップ', new_user_registration_path
          = link_to 'ログイン', new_user_session_path
    %p.notice
      = notice
    %p.alert
      = alert
    = yield

まとめ

以上でdeviseを用いた
簡単なパスワード認証機能は実装できました。

次回はSNS認証の実装をしていきたいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0