module Web
  class Agent
    class PasswordManager
      def initialize
        @db=Hash.new
      end

      def get(agent)
        return unless agent.rsp
        agent.req.header.delete 'authorization'
        text=agent.rsp.header['www-authenticate']
        if text
          if text=~/basic\s+realm\s*=\s*["']?([^"']+)["']?/i    #'
            realm = $1
            pass = @db[[agent.uri.scheme,agent.uri.host,agent.uri.port,realm]]
            if pass
              agent.req.header.add 'authorization', "Basic " + ["#{pass.username}:#{pass.password}"].pack('m').chomp
            end
          else
            raise "authenticate error"
          end
        end
      end

      def set(agent, username, password)
        text=agent.rsp.header['www-authenticate']
        if text
          if text=~/basic\s+realm\s*=\s*["']?([^"']+)["']?/i    #'
            realm = $1
            @db[[agent.uri.scheme,agent.uri.host,agent.uri.port,realm]] = Password.new(agent.uri.scheme,agent.uri.host,agent.uri.port,realm,username,password)
          else
            raise "authenticate error"
          end
        end
      end

      def clear
        @db.clear
      end

      class Password
        def initialize(scheme, host, port, realm, username, password)
          @scheme   = scheme
          @host     = host
          @port     = port
          @realm    = realm
          @username = username
          @password = password
        end
        attr_accessor :scheme, :host, :port, :realm, :username, :password
      end # Password
    end # PasswordManager
  end # Agent
end # Web
