LoginSignup
0
1

More than 1 year has passed since last update.

Railsの認証ソリューション deviseを使おう

Posted at

初めに

ちょっと前の記事でOpenID Connectを書いたは良いものの、そもそもdevise導入しなきゃな...
ということでdeviseの導入をやっていきます。ただ、OpenID Connectやるだけだったらdevise入れなくても大丈夫です。

deviseとは

Railsで最もメジャーな認証系のgemです。ログイン機能やパスワード変更など簡単に行えます。

環境

  • OS: Windows11 Pro 64bit
    • Version: 21H2
    • OS build: 22000.493
  • WSL2: Ubuntu 20.04.4 LTS
    • Ruby: 3.1.1p18
    • Rails: 7.0.2.2

deviseの導入

公式のGetting started見つつやっていきます。

インストール

まずは、Gemfileを編集してdeviseをインストールします。

$ vi Gemfile 
Gemfile
gem 'devise'
$ bundle install

$ rails generate devise:install
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
[以下略]

devise関連設定

deviseのインストール時に、設定内容が表示されます。指示通り設定していきます。

$ vi config/environments/development.rb
config/environments/development.rb
require "active_support/core_ext/integer/time"

Rails.application.configure do
  ...
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end

deviseが利用するメーラーの設定です。
今回は開発環境のみで動かすので、production.rbは特に変更しません。

$ vi config/routes.rb
config/routes.rb
Rails.application.routes.draw do
  ...
  root to: "home#index"
end

deviseがログイン画面作ってくれるので、ログイン後に遷移するroot_urlの設定追加します。

$ vi app/views/layouts/application.html.erb
app/views/layouts/application.html.erb
  <body>
    <p class="notice"><%= notice %></p> # 追加 
    <p class="alert"><%= alert %></p>   # 追加
    <%= yield %>
  </body>

deviseが送信するflashメッセージ出力するために上記の設定を、テンプレートに入れていきます。

$ rails g devise:views
      invoke  Devise::Generators::SharedViewsGenerator
      create    app/views/devise/shared
      create    app/views/devise/shared/_error_messages.html.erb
      create    app/views/devise/shared/_links.html.erb
      invoke  form_for
      create    app/views/devise/confirmations
      create    app/views/devise/confirmations/new.html.erb
      create    app/views/devise/passwords
      create    app/views/devise/passwords/edit.html.erb
      create    app/views/devise/passwords/new.html.erb
      create    app/views/devise/registrations
      create    app/views/devise/registrations/edit.html.erb
      create    app/views/devise/registrations/new.html.erb
      create    app/views/devise/sessions
      create    app/views/devise/sessions/new.html.erb
      create    app/views/devise/unlocks
      create    app/views/devise/unlocks/new.html.erb
      invoke  erb
      create    app/views/devise/mailer
      create    app/views/devise/mailer/confirmation_instructions.html.erb
      create    app/views/devise/mailer/email_changed.html.erb
      create    app/views/devise/mailer/password_change.html.erb
      create    app/views/devise/mailer/reset_password_instructions.html.erb
      create    app/views/devise/mailer/unlock_instructions.html.erb

「必須じゃないよ」とは書かれているものの、せっかくなのでdeviseのviewsファイルも作っていきます。

Userモデルの作成

ログインに使用するユーザ作っていきます。

$ rails generate devise User
      invoke  active_record
      create    db/migrate/20220223073610_devise_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
      insert    app/models/user.rb
       route  devise_for :users
$ rails db:migrate
== 20220223073610 DeviseCreateUsers: migrating ================================
-- create_table(:users)
   -> 0.0017s
-- add_index(:users, :email, {:unique=>true})
   -> 0.0008s
-- add_index(:users, :reset_password_token, {:unique=>true})
   -> 0.0007s
== 20220223073610 DeviseCreateUsers: migrated (0.0035s) =======================

ここまで実行すると、下記の画面が表示できるようになります。

image.png

image.png

今の状態だとsing_up/sing_in後のuser_url/root_url等の指定がないので、エラーになります。

Controllerの作成

user_url/root_url用のControllerがないのでコマンドを使って作成します。

$ bin/rails generate controller Home index
      create  app/controllers/home_controller.rb
       route  get 'home/index'
      invoke  erb
      create    app/views/home
      create    app/views/home/index.html.erb
      invoke  test_unit
      create    test/controllers/home_controller_test.rb
      invoke  helper
      create    app/helpers/home_helper.rb
      invoke    test_unit

$ bin/rails generate controller Users show
[略]

コントローラ名を間違えた場合は、destroyで消せます。

$ bin/rails destroy controller Home index

UsersController作成時にできるデフォルトのパスだと、users_show_urlとなってしまうので適切なパスを定義しなおします。

$ vi config/routes.rb
config/routes.rb
Rails.application.routes.draw do
  # get 'users/show' 削除
  get 'home/index'
  devise_for :users
  resources :users, only: [:show] # 追加
  # [略]
end

homeページはログインなしで入れてしまうので、ApplicationControllerを編集します。

$ vi app/controllers/application_controller.rb
application_controller.rb
class ApplicationController < ActionController::Base
  before_action :authenticate_user! # 追加
end

最後にログアウト用のリンクをHomeController用のViewに入れます。

$ vi app/views/home/index.html.erb
index.html.erb
<h1>Home#index</h1>
<p>Find me in app/views/home/index.html.erb</p>
<%= button_to 'Log out', destroy_user_session_path, method: :delete %>

動作確認

http://localhost:3000/users/sign_up
にアクセス。ユーザを作成する。

image.png
image.png

http://localhost:3000
にアクセス。ログアウトボタンを押す。リダイレクト作りこんでないので、更新ボタン押します。

image.png

ログイン画面から、ログイン。

image.png
image.png

終わりに

公式のGetting Startが少しわかりづらかったので、少し情報を付け足してみました。さらに使いこなすにはDeviseが作成したView/Controllerを編集する必要があるので、まだまだ覚えることはたくさんあります。

Devise使ったログインができるようになったので、OpenID Connectの記事も後で書きたいと思います。

0
1
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
1