Sha256: 6b09f01c54b570e0ef8aed60e5c528871c1528f6384c0d2bc91c738a80ef287d

Contents?: true

Size: 1.52 KB

Versions: 7

Compression:

Stored size: 1.52 KB

Contents

module Clearance
  # Middleware which allows signing in by passing as=USER_ID in a query
  # parameter. If `User#to_param` is overriden you may pass a block to
  # override the default user lookup behaviour
  #
  # Designed to eliminate time in integration tests wasted by visiting and
  # submitting the sign in form.
  #
  # Configuration:
  #
  #   # config/environments/test.rb
  #   MyRailsApp::Application.configure do
  #     # ...
  #     config.middleware.use Clearance::BackDoor
  #     # ...
  #   end
  #
  #   # or if `User#to_param` is overridden (to `username` for example):
  #
  #   # config/environments/test.rb
  #   MyRailsApp::Application.configure do
  #     # ...
  #     config.middleware.use Clearance::BackDoor do |username|
  #       User.find_by(username: username)
  #     end
  #     # ...
  #   end
  #
  # Usage:
  #
  #   visit new_feedback_path(as: user)
  class BackDoor
    def initialize(app, &block)
      @app = app
      @block = block
    end

    def call(env)
      sign_in_through_the_back_door(env)
      @app.call(env)
    end

    private

    # @api private
    def sign_in_through_the_back_door(env)
      params = Rack::Utils.parse_query(env["QUERY_STRING"])
      user_param = params["as"]

      if user_param.present?
        user = find_user(user_param)
        env[:clearance].sign_in(user)
      end
    end

    # @api private
    def find_user(user_param)
      if @block
        @block.call(user_param)
      else
        Clearance.configuration.user_model.find(user_param)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
clearance-1.16.1 lib/clearance/back_door.rb
clearance-1.16.0 lib/clearance/back_door.rb
clearance-1.15.1 lib/clearance/back_door.rb
clearance-1.15.0 lib/clearance/back_door.rb
clearance-1.14.2 lib/clearance/back_door.rb
clearance-1.14.1 lib/clearance/back_door.rb
clearance-1.14.0 lib/clearance/back_door.rb