備忘録です
はじめに
devise
をとりあえず入れとこうとなるかと思いますが、ライブラリとして重たいので、軽量で、最低限の認証機能を作れる sorcery を使ってみようと思います。
公式サイト
GEM: https://rubygems.org/gems/sorcery
GITHUB: https://github.com/Sorcery/sorcery
環境
$ rails -v
Rails 5.2.3
$ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin18]
導入
./Gemfile
...
+ gem 'sorcery'
$ bundle install
...
$ bundle exec rails generate sorcery:install
create config/initializers/sorcery.rb
generate model User --skip-migration
invoke active_record
create app/models/user.rb
insert app/models/user.rb
insert app/models/user.rb
create db/migrate/20190513001622_sorcery_core.rb
参考: https://github.com/Sorcery/sorcery#installation
補足
新しく作成されるファイル
./config/initializers/sorcery.rb
./db/migrate/[timestamp]_sorcery_core.rb
./app/models/user.rb
./config/initializers/sorcery.rb
# ...
Rails.application.config.sorcery.submodules = []
# Here you can configure each submodule's features.
Rails.application.config.sorcery.configure do |config|
# ...
# --- user config ---
config.user_config do |user|
# ...
user.stretches = 1 if Rails.env.test?
end
config.user_class = 'User'
end
./db/migrate/[timestamp]_sorcery_core.rb
class SorceryCore < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :email, :null => false
t.string :crypted_password
t.string :salt
t.timestamps :null => false
end
add_index :users, :email, unique: true
end
end
./app/models/user.rb
class User < ApplicationRecord
authenticates_with_sorcery!
end
db:migrate
$ bin/rails db:migrate
== 20190513001622 SorceryCore: migrating ======================================
-- create_table(:users)
-> 0.0107s
-- add_index(:users, :email, {:unique=>true})
-> 0.0051s
== 20190513001622 SorceryCore: migrated (0.0159s) =============================
コンソールからユーザーを作成
user = User.create(email: "hoge@example.com", password: "Password!123")