MENU

rails6でdeviseを使ってユーザー機能を実装してみた

本記事は「メディアサイトを作る」の作業の一環です

spreadthec0ntents.com

やったこと

  • deviseを使ってユーザーの作成、ログイン、ログアウトなどの機能が実装できる。

やったこと一覧

  • deviseのインストールと設定
  • userクラスの設定とテーブル作成
  • dotenvのインストールと設定
  • basic認証の追加
  • サインイン後に飛ばすページを設定する

やったこと詳細

Gemfileに以下を記述してインストール

gem 'devise'

deviseのインストール

$ rails generate devise:install

デフォルトURLの指定

 メール機能を使わない場合もいるのか?

# config/environments/development.rb

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # (省略)...

  # mailer setting
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  # config.action_mailer.default_url_options = { host: 'localhost:3000' }
end

userモデルの作成

 使う機能は以下の通り。

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :timeoutable, :trackable
end

 使う機能に必要なカラムも追加するのでuserのmigrationの:trackableの部分はコメントインしておく。

userのmigrationの設定

 デフォルトのmigrationに以下を追加。

      t.string :name
      t.text :profile

 テーブル作成。

$ rake db:migrate

devise関連のviewを作成

 後に見た目とかをカスタマイズしたいので。

$ rails g devise:views

routesの設定

 とりあえずサインインのページをrootにする。後で変えるけどね。

  devise_scope :user do
    root 'devise/sessions#new'
  end

f:id:spreadthec0ntents:20210515100545p:plain
表示はできた。

basic認証の導入

 本サイトは管理者だけがユーザー機能を使える仕様なので、basic認証を導入する。

環境変数は.envで管理する
  • gemの追加
gem 'dotenv-rails'
  • インストール
$ bundle install
  • .gitignoreにコミットしないファイルとして.envを追加
.env
  • .envに環境変数を書く
    .envのファイルを作って以下を記述。それぞれはbasic認証で使用するコンビネーション。
BASIC_AUTH_USER='hoge'
BASIC_AUTH_PASSWORD='fuga'
basic認証の導入
  • application_controller.rbにbasic認証用のメソッドを作る。
class ApplicationController < ActionController::Base
  before_action :basic_auth
  protect_from_forgery with: :exception

  private

  def basic_auth
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV["BASIC_AUTH_USER"] && password == ENV["BASIC_AUTH_PASSWORD"]
    end
  end
end

f:id:spreadthec0ntents:20210515101620p:plain
basic認証完成。

サインイン後に飛ばすページを設定する

 以上の処理を実装後にサインアップしても、サインイン済み状態でサインインページ飛ばされるので無限ループが発生する。
 これでは困るのでサインインしてなかったらサインインのページに飛ばすようにし、rootは違うページにする。

サインしてなかったらサインインページに飛ばす
class ApplicationController < ActionController::Base
  before_action :basic_auth
  protect_from_forgery with: :exception

  private

  def basic_auth
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV["BASIC_AUTH_USER"] && password == ENV["BASIC_AUTH_PASSWORD"]
    end
  end

  def sign_in_required
      redirect_to new_user_session_url unless user_signed_in?
  end
end
articles_controllerを作成する(今後使うやつ)

 上で作ったメソッドをbefore_actionに入れる。

class ArticlesController < ApplicationController
  before_action :sign_in_required, only: [:show]

  def show
  end
end

 あとshowのviewも作っておく。

root_pathの変更

 とりあえず今はこれ。

Rails.application.routes.draw do
  devise_for :users
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root 'articles#show'
end

 これでサインしてたらshowのページ、してなかったらサインインページに行く。

参考

qiita.com

qiita.com

qiita.com