7
7

More than 5 years have passed since last update.

bcryptの使い方メモ

Last updated at Posted at 2015-04-20

最終的なログイン機能の画像

71FA192B-8508-448A-BDB4-E19C366E8895.png

3DB02050-459C-4C1F-8B57-62F3044381A5.png

6A201EF8-3E86-4FC4-8D20-6D101DE9AB50.png

Modelの作成 user

rails g model user name:string password_digest:string
rake db:migrate

888D5AE2-6073-4DD5-81E2-CE3E3219C2F0.png

編集 users.rb

users.rb
class User < ActiveRecord::Base  
  has_secure_password  
end 

管理アカウントをコンソールから追加

rails c
User.create!(:name => "admin", :password => "password", :password_confirmation => "password")

554E4C9A-A2BF-428A-89C8-90722C6E94FE.png
*DB上にはpasswordカラムはないが
password_digestカラムにハッシュ化されたpasswordが入る

Controllerの作成 sessions

rails g controller sessions

Viewの作成 new.html.erb(ログインフォーム)

app/view/sesisons/new.html.erb
<h1>ログイン</h1>
<% if flash.alert %>
    <p class="alert"><%= flash.alert %></p>
<% end %>
<%= form_tag sessions_path do %>
    <div class="field"><%= label_tag :name, 'login name' %>
      <%= text_field_tag :name, params[:name] %>
    </div>
    <div class="field"><%= label_tag :password, 'password' %>
      <%= password_field_tag :password, params[:password] %>
    </div>
    <div class="actions"><%= submit_tag "ログイン" %>
    </div>
<% end %>

編集 routes.rb

routes.rb
Rails.application.routes.draw do
  root 'users#index'
  resources :sessions do
  end
end

編集 session_controller.rb (ログインに成功したらトップヘリダイレクト 失敗したらメッセージを表示)

app/controller/session_controller.rb

class SessionsController < ApplicationController
  def index
    render "new"
  end
  def create
    user = User.find_by_name params[:name]
    if user && user.authenticate(params[:password_digest])
      session[:user_id] = user.id
      redirect_to root_path
    else
      flash.now.alert = "ユーザー名かパスワードに誤りがあります"
      render "new"
    end
  end
  def destroy
    session[:user_id] = nil
    redirect_to root_path
  end
end

編集 application_controller.rb (ビューからログインユーザを参照できるようにする )

app/controller/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  helper_method :current_user
end

編集 application.html.erb(ログインフォームへのパスを追加)

application.html.erb
<% if current_user == nil %>
    <%= link_to "ログイン", sessions_path %>
<% else %>
    <%= link_to 'ログアウト', session_path(current_user.id), :confirm => 'ログアウトしますか?', :method => :delete %>
<% end %>
<%= yield %>
7
7
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
7
7