module Roda::RodaPlugins::HttpAuth::InstanceMethods

Public Instance Methods

http_auth(opts={}, &authenticator) click to toggle source
# File lib/roda/plugins/http_auth.rb, line 22
def http_auth(opts={}, &authenticator)
  auth_opts = request.roda_class.opts[:http_auth].merge(opts)
  authenticator ||= auth_opts[:authenticator]

  raise "Must provide an authenticator block" if authenticator.nil?

  auth = Rack::Auth::Basic::Request.new(env)

  unless auth.provided? && auth_opts[:schemes].include?(auth.scheme)
    unauthorized(auth_opts)
  end

  credentials = if auth.basic?
                  auth.credentials
                elsif auth.scheme == 'bearer'
                  [env['HTTP_AUTHORIZATION'].split(' ', 2).last]
                else
                  http_auth = env['HTTP_AUTHORIZATION'].split(' ', 2)
                                                       .last

                  creds = !http_auth.include?('=') ? http_auth :
                            Rack::Auth::Digest::Params.parse(http_auth)

                  [auth.scheme, creds]
                end

  if authenticator.call(*credentials)
    env['REMOTE_USER'] = auth.username
  else
    unauthorized(auth_opts)
  end
end

Private Instance Methods

unauthorized(opts) click to toggle source
# File lib/roda/plugins/http_auth.rb, line 57
def unauthorized(opts)
  response.status = 401
  response.headers.merge!(opts[:unauthorized_headers].call(opts))

  request.block_result(instance_exec(request, &opts[:unauthorized]))
  request.halt response.finish
end