sorcery

sorcery https://github.com/Sorcery/sorcery/wiki

インストール

gem 'sorcery'
% bundle install

Userモデルの自動生成

% rails generate sorcery:install

# サブモジュールの指定
% rails generate sorcery:install remember_me reset_password

コアメソッド

# 変数passwordでcrypted_passwordの値にアクセスできる
require_login # This is a before action
login(email, password, remember_me = false)
auto_login(user) # Login without credentials
logout
logged_in? # Available in views
current_user # Available in views
redirect_back_or_to # Use when a user tries to access a page while logged out, is asked to login, and we want to return him back to the page he originally wanted
@user.external? # Users who signed up using Facebook, Twitter, etc.
@user.active_for_authentication? # Add this method to define behaviour that will prevent selected users from signing in
@user.valid_password?('secret') # Compares 'secret' with the actual user's password, returns true if they match
User.authenticates_with_sorcery!

パスワード以外の項目を更新するときパスワードの入力を省略する

validates :password, length: { minimum: 4}, if: -> { new_record? || changes[:crypted_password] }

ログイン時の注意点

ユーザーがログインする際にCSRFトークンがリセットされるが、それを行うform_authenticity_tokenメソッドがRails-APIに存在しない。 このメソッドがないと動作が保証されないので、自前で空メソッドを用意する必要がある。

class BaseController < ApplicationController

  private

  def form_authenticity_token; end
  # https://github.com/NoamB/sorcery/issues/724
  # https://qiita.com/okaeri_ryoma/items/0d01469f2265e5d51af1
end

has_secure_password

sorceryをインストールするだけでRailshas_secure_passwordメソッドが利用可能になる。

has_secure_passwordの機能

  • セキュアにハッシュ化したパスワードを、データベース内のpassword_digestという属性に保存できるようになる。
  • 2つのペアの仮想的な属性(passwordとpassword_confirmation)が使えるようになる。また、存在性と値が一致するかどうかのバリデーションも追加される。
  • authenticateメソッドが使えるようになる(引数の文字列がパスワードと一致するとUserオブジェクトを、間違っているとfalseを返すメソッド)。

has_secure_passwordはbcryptというハッシュ関数が必要だが、sorceryではデフォルトでbcryptを利用するようになっている。