File: digest_auth.rb

package info (click to toggle)
ruby-httpx 1.7.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,816 kB
  • sloc: ruby: 12,209; makefile: 4
file content (66 lines) | stat: -rw-r--r-- 1,905 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
58
59
60
61
62
63
64
65
66
# frozen_string_literal: true

module HTTPX
  module Plugins
    #
    # This plugin adds helper methods to implement HTTP Digest Auth (https://datatracker.ietf.org/doc/html/rfc7616)
    #
    # https://gitlab.com/os85/httpx/wikis/Auth#digest-auth
    #
    module DigestAuth
      class << self
        def extra_options(options)
          options.merge(max_concurrent_requests: 1)
        end

        def load_dependencies(klass)
          require_relative "auth/digest"
          klass.plugin(:auth)
        end
      end

      # adds support for the following options:
      #
      # :digest :: instance of HTTPX::Plugins::Authentication::Digest, used to authenticate requests in the session.
      module OptionsMethods
        private

        def option_digest(value)
          raise TypeError, ":digest must be a #{Authentication::Digest}" unless value.is_a?(Authentication::Digest)

          value
        end
      end

      module InstanceMethods
        def digest_auth(user, password, hashed: false)
          with(digest: Authentication::Digest.new(user, password, hashed: hashed))
        end

        private

        def send_requests(*requests)
          requests.flat_map do |request|
            digest = request.options.digest

            next super(request) unless digest

            probe_response = wrap { super(request).first }

            return [probe_response] * requests.size unless probe_response.is_a?(Response)

            if probe_response.status == 401 && digest.can_authenticate?(probe_response.headers["www-authenticate"])
              request.transition(:idle)
              request.authorize(digest.authenticate(request, probe_response.headers["www-authenticate"]))
              super(request)
            else
              probe_response
            end
          end
        end
      end
    end

    register_plugin :digest_auth, DigestAuth
  end
end