LoginSignup
7
3

More than 1 year has passed since last update.

真:Sorceryで複数モデルを扱う

Last updated at Posted at 2021-09-02

ユーザと管理者で Model をわけたいと考えて以下の記事を参考にしました。

current_userをオーバーライドしても、loginなどは適切に動きません。

ログを見ると config で指定していた user_classでログイン処理が走ります。

ソースコードを追っかけてみると・・・

sorcery-0.16.1/lib/sorcery/controller.rb

module Sorcery
  module Controller

    module InstanceMethods

      # Takes credentials and returns a user on successful authentication.
      # Runs hooks after login or failed login.
      def login(*credentials)
        @current_user = nil

        user_class.authenticate(*credentials) do |user, failure_reason|
          if failure_reason
            after_failed_login!(credentials)

            yield(user, failure_reason) if block_given?

            # FIXME: Does using `break` or `return nil` change functionality?
            # rubocop:disable Lint/NonLocalExitFromIterator
            return
            # rubocop:enable Lint/NonLocalExitFromIterator
          end

          old_session = session.dup.to_hash
          reset_sorcery_session
          old_session.each_pair do |k, v|
            session[k.to_sym] = v
          end
          form_authenticity_token

          auto_login(user, credentials[2])
          after_login!(user, credentials)

          block_given? ? yield(current_user, nil) : current_user
        end
      end

      # attempts to auto-login from the sources defined (session, basic_auth, cookie, etc.)
      # returns the logged in user if found, nil if not
      def current_user
        unless defined?(@current_user)
          @current_user = login_from_session || login_from_other_sources || nil
        end
        @current_user
      end


      protected

      def user_class
        @user_class ||= Config.user_class.to_s.constantize
      rescue NameError
        raise ArgumentError, 'You have incorrectly defined user_class or have forgotten to define it in intitializer file (config.user_class = \'User\').'
      end
    end
  end
end


ということで下記のように user_class メソッドをオーバーライドしてあげると動作します。

custom_controller.rb
  def user_class
    @user_class ||= Admin.to_s.constantize
  end
7
3
2

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
7
3