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