9
10

More than 5 years have passed since last update.

Rails sorceryでメールを送らずにユーザ作成する

Posted at

Goal

  • sorceryはemailアクティベーション機能やパスワードリセット機能などをサポートしていて、これを有効にすれば会員登録時などに必要なメールを自動で送信することができる
  • 今回はテスト用だったりイレギュラー要件で、本番環境にユーザを作成しつつアクティベーションメールの送信はスキップさせる
  • サービスは通常通り稼働させたいので、config/initializers/sorcery.rbはさわらず、rails consoleセッションにのみメールスキップの設定を反映させたい

Background

sorceryでは以下のような設定で、emailアクティベーション機能やパスワードリセット機能を有効にでき、その際にユーザに送信する必要のあるメール処理をUserSupportMailerクラスに担当させている.

config/initializers/sorcery.rb
Rails.application.config.sorcery.submodules = [:user_activation, :reset_password]
Rails.application.config.sorcery.configure do |config|
  # (省略)
  config.user_config do |user|
    # (省略)
    user.user_activation_mailer = ::UserSupportMailer
    user.reset_password_mailer = ::UserSupportMailer
    # (省略)
  end
  # (省略)

Rails.application.config.sorcery.configureブロックの直下の設定(config.session_timeout, config.user_classなど)はコントローラ層に対しての設定になり、以下のように設定値をたどることができる.

Rails.application.config.sorcery.session_timeout
  # => 25200

Rails.application.config.sorcery.configureブロック内にネストしているuser_configブロックはモデル層に対しての設定となる(username_attribute_names, password_attribute_name, ...). これらの設定はsorceryのユーザクラスに指定したクラスのクラスメソッドとして参照できるようになる.

User.sorcery_config.class
  # => Sorcery::Model::Config
User.sorcery_config.username_attribute_names
  # => [:email]

Manual

rails console -e productionしてからの手順

## 
## sorceryの各種自動メール送信機能をストップする
## - アクティベーション時のメール
## - パスワードリセット時のメール
## - ロック解除時のメール
## 
User.sorcery_config.activation_mailer_disabled     = true
User.sorcery_config.reset_password_mailer_disabled = true
User.sorcery_config.unlock_token_mailer_disabled   = true

user = User.create!({email: 'metheglin@example.com', password: 'test_password'})
  # user_activationを有効にしていればユーザモデル(User)のcreate時にメールが送信されるが、
  # activation_mailer_disabled = trueにより自動ではメール送信されなくなる
user.update!({activation_state: 'active', activation_token: nil})
  # activation_stateはpendingで登録されるので、ユーザをログイン可能にしたければactiveに変更する

Environment

sorcery (0.9.1)
rails (4.1.9)
9
10
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
9
10