DDG - Develop a Digital Garden

develop a digital garden

ActiveRecord でのユーザー認証

ActiveRecord でのユーザー認証

参考

http://masa-world.hateblo.jp/entry/2017/05/16/193544

まとめ

  • gemのbcyptをインストールする
  • パスワードを扱うModel にhas_secure_passwordを追記する
  • input要素のname属性をpasswordにする
  • データベースのパスワードを保存するカラムを、password_digestというカラム名にする
  • 入力されたパスワードとデータベースのパスワードが一致しているかは、authinticate()関数を使用する

Gemfileに bcrypt を追加する

 gem 'bcrypt'
code: shell
 bundle install --path=vendor/bundle
 rbenv rehash

has_secure_password API を追加する

 require 'sqlite3'
 require 'sinatra/activerecord'
 
 ActiveRecord::Base.configurations = YAML.load_file('db/db.yml')
 ActiveRecord::Base.establish_connection(:development)
 class User < ActiveRecord::Base
   has_secure_password # APIを追加する
 end

ログイン画面(haml)

 %form.ui.large.form{:action => "/signin/auth", :method => "post"}
   %input{:name => "email", :placeholder => "E-Mail address", :required => "", :type => "email"}/
   %input{:name => "password", :placeholder => "Password", :required => "", :type => "password"}/
   %button.ui.fluid.positive.button{:name => "signin", :type => "submit"}/Sign In

ユーザー登録処理

   if !User.create(name: params[:name], email: params[:email], password: params[:password])
      'Failed!'
    end

ユーザー認証処理

   user = User.find_by(email: params[:email])
    if !user || !user.authenticate(params[:password])
      'Failed!'
    else
      'Succeed!'
    end