- 追加された行はこの色です。
- 削除された行はこの色です。
#author("2018-03-09T16:07:50+09:00","default:wikiwriter","wikiwriter")
&tag(Devise/最もシンプルな認証機能);
*目次 [#pa418ddf]
#contents
*関連ページ [#la52c80f]
-[[Devise]]
*参考情報 [#l97408fd]
*Userモデルの生成 [#we170e46]
*概要 [#f0db1c67]
-基本的な認証機能を実装する。
-電子メールとパスワードで登録。
-確認メールの送信なし。
*使用準備[#we170e46]
-deviseをインストールする
bundle exec rails g devise:install
-Userモデルを生成する
$ bundle exec rails g devise User
bundle exec rails g devise user
-migration実行
bundle exec rake db:migrate
-デフォルトのUserモデルの内容
#pre{{
class User < ActiveRecord::Base
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
}}
-デフォルトのマイグレーションファイルの内容
#pre{{
class DeviseCreateUsers < ActiveRecord::Migration
class DeviseCreateUsers < ActiveRecord::Migration[5.1]
def change
create_table(:users) do |t|
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
}}
*ビューの編集 [#a4859cdf]
-application.html.rbを編集
#pre{{
<div class="row">
<% if user_signed_in? %>
<strong><%= current_user.id %></strong> /
<%= link_to("ログアウト", destroy_user_session_path, method: :delete) %>
<% else %>
<%= link_to("登録", new_user_registration_path) %> /
<%= link_to("ログイン", new_user_session_path) %>
<% end %>
}}
-migration実行
bundle exec rake db:migrate
-ログインしていないときは「登録 / ログイン」。ログインしているときは「ID / ログアウト」が表示される。
#ref(list.png)
*処理の流れ [#s6458e18]
**登録処理 [#a194c415]
-メールアドレスとパスワードを入力し「Sign up」を押すと即座に登録される。既存のメールアドレスを入力するとログイン画面に遷移する。
#ref(regist.png)
**ログイン処理 [#b94949d7]
-登録済みユーザーの場合はログインできる。
#ref(login.png)