Module: Roda::RodaPlugins::HttpAuth::RequestMethods

Defined in:
lib/roda/plugins/http_auth.rb

Instance Method Summary collapse

Instance Method Details

#_extract_credentialsObject



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/roda/plugins/http_auth.rb', line 59

def _extract_credentials
  authorization = env['HTTP_AUTHORIZATION'].split(' ', 2).last
  parts = authorization.split(',')

  return parts.first if parts.one? && !parts.first.include?('=')

  key_values = parts.map {|p| p.strip.split(/\=\"?/) }
                    .map {|k, v| [k, v.chomp('"').gsub(/\\\"/, '"')] }

  Hash[key_values]
end

#http_auth(opts = {}, &authenticator) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/roda/plugins/http_auth.rb', line 26

def http_auth(opts={}, &authenticator)
  auth_opts = roda_class.opts[:http_auth].merge(opts)
  authenticator ||= auth_opts[:authenticator]

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

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

    unless auth.provided? && auth_opts[:schemes].include?(auth.scheme)
      auth_opts[:unauthorized].call(self) if auth_opts[:unauthorized]
      halt [401, auth_opts[:unauthorized_headers].call(auth_opts), []]
    end

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

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