お手軽にログイン機能を実装できるdeviseの使い方
deviseというgemのお話
Twitterとの連携もまとめて書いてある良記事見つけた
環境
Ruby 2.5.1
Rails 5.2.0
code:bash
rails new device_app
cd devise_app
gemの追加
code:Gemfile
gem 'devise'
code:bash
bundle install
関連ファイルの作成
code:bash
rails g devise:install
signup ~ editに関するHTMLファイルの作成(カスタマイズするのであれば実行)
code:bash
rails g devise:views
=> # 以下作成されるファイルたち
app/views/devise/shared/_links.html.erb (リンク用パーシャル)
app/views/devise/confirmations/new.html.erb (認証メールの再送信画面)
app/views/devise/passwords/edit.html.erb (パスワード変更画面)
app/views/devise/passwords/new.html.erb (パスワードを忘れた際、メールを送る画面)
app/views/devise/registrations/edit.html.erb (ユーザー情報変更画面)
app/views/devise/registrations/new.html.erb (ユーザー登録画面)
app/views/devise/sessions/new.html.erb (ログイン画面)
app/views/devise/unlocks/new.html.erb (ロック解除メール再送信画面)
app/views/devise/mailer/confirmation_instructions.html.erb (メール用アカウント認証文)
app/views/devise/mailer/password_change.html.erb (メール用パスワード変更完了文)
app/views/devise/mailer/reset_password_instructions.html.erb (メール用パスワードリセット文)
app/views/devise/mailer/unlock_instructions.html.erb (メール用ロック解除文)
Userモデルの作成
code:bash
rails g devise user
マイグレーション
*マイグレーションする前に使用するモジュールがあれば各ファイルを編集しよう(追記あり)
code:bash
rails db:migrate
http://freesworder.net/wp-content/uploads/2017/07/devise2.png
gemをインストールして3回コマンド打つだけでログイン機能ができちゃうって革命的rhiroe.icon
デフォルトで格納されるパラメータはid、email、created_at、updated_atのみ
passwordは仮想属性に格納されている(セキュアなpasswordというやつ)
他必要があれば$ rails g migrationで追加
複数モデルに適用する場合は別途面倒な設定が必要らしいけど基本的にログインに使うモデルは1つだよね
終了。
追記
table:deviseモジュール
機能 概要
database_authenticatable サインイン時にユーザーの正当性を検証するためにパスワードを暗号化してDBに登録します。認証方法としてはPOSTリクエストかHTTP Basic認証が使えます。
registerable 登録処理を通してユーザーをサインアップします。また、ユーザーに自身のアカウントを編集したり削除することを許可します。
recoverable パスワードをリセットし、それを通知します。
rememberable 保存されたcookieから、ユーザーを記憶するためのトークンを生成・削除します。
trackable サインイン回数や、サインイン時間、IPアドレスを記録します。
validatable Emailやパスワードのバリデーションを提供します。独自に定義したバリデーションを追加することもできます。
confirmable メールに記載されているURLをクリックして本登録を完了する、といったよくある登録方式を提供します。また、サインイン中にアカウントが認証済みかどうかを検証します。
lockable 一定回数サインインを失敗するとアカウントをロックします。ロック解除にはメールによる解除か、一定時間経つと解除するといった方法があります。
timeoutable 一定時間活動していないアカウントのセッションを破棄します。
omniauthable intridea/omniauthをサポートします。TwitterやFacebookなどの認証を追加したい場合はこれを使用します。
使用する、しないモジュールがあれば各ファイルを編集する
code:app/models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :timeoutable, :omniauthable, omniauth_providers: :twitter # 必要に応じて追加したり削除したりする
end
code:db/migrate/20161112121754_devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration5.0 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.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
confirmableモジュールを有効にし、メール認証を行う場合
実際にメールが届くよう各ファイルを設定
code:config/initializers/devise.rb
Devise.setup do |config|
(省略)...
# mail setting
config.mailer_sender = "メールアドレス"
end
code:config/environments/development.rb
Rails.application.configure do
# default url
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# mail setting
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => "メールアドレス",
:password => "メールパスワード", # gmailの場合アプリパスワードがここに入る
:authentication => :plain,
:enable_starttls_auto => true
}
end
あと他にも一定時間無操作でセッション終了とかログイン後のリダイレクト先の変更とかあるけど
そんなに難しくないし書くの面倒だから最初に貼ったリンク先参考にして〜