module Roda::RodaPlugins::BasicAuth::RequestMethods

Public Instance Methods

basic_auth(opts={}, &authenticator) click to toggle source
# File lib/roda/plugins/basic_auth.rb, line 25
def basic_auth(opts={}, &authenticator)
  auth_opts = roda_class.opts[:basic_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[:unauthorized].call(self) if auth_opts[:unauthorized]
    halt [401, auth_opts[:unauthorized_headers].call(auth_opts), []]
  end

  unless auth.basic?
    halt [400, auth_opts[:bad_request_headers].call(auth_opts), []]
  end

  if authenticator.call(*auth.credentials)
    env['REMOTE_USER'] = auth.username
  else
    auth_opts[:unauthorized].call(self) if auth_opts[:unauthorized]
    halt [401, auth_opts[:unauthorized_headers].call(auth_opts), []]
  end
end