Takes the given response and tries digest-auth, if needed.
354431
def handle_401(self, r, **kwargs):
        """"""

        if self.pos is not None:
            # Rewind the file position indicator of the body to where
            # it was to resend the request.
            r.request.body.seek(self.pos)
        num_401_calls = getattr(self, 'num_401_calls', 1)
        s_auth = r.headers.get('www-authenticate', '')

        if 'digest' in s_auth.lower() and num_401_calls < 2:

            setattr(self, 'num_401_calls', num_401_calls + 1)
            pat = re.compile(r'digest ', flags=re.IGNORECASE)
            self.chal = parse_dict_header(pat.sub('', s_auth, count=1))

            # Consume content and release the original connection
            # to allow our new request to reuse the same one.
            r.content
            r.raw.release_conn()
            prep = r.request.copy()
            extract_cookies_to_jar(prep._cookies, r.request, r.raw)
            prep.prepare_cookies(prep._cookies)

            prep.headers['Authorization'] = self.build_digest_header(
                prep.method, prep.url)
            _r = r.connection.send(prep, **kwargs)
            _r.history.append(r)
            _r.request = prep

            return _r

        setattr(self, 'num_401_calls', 1)
        return r
1030039
def handle_401(self, response, repo, **kwargs):
        """"""
        if response.status_code != requests.codes.unauthorized:
            return response

        auth_info = response.headers.get('www-authenticate', '')

        if 'bearer' not in auth_info.lower():
            return response

        self._token_cache[repo] = self._get_token(auth_info, repo)

        # Consume content and release the original connection
        # to allow our new request to reuse the same one.
        # This pattern was inspired by the source code of requests.auth.HTTPDigestAuth
        response.content
        response.close()
        retry_request = response.request.copy()
        extract_cookies_to_jar(retry_request._cookies, response.request, response.raw)
        retry_request.prepare_cookies(retry_request._cookies)

        self._set_header(retry_request, repo)
        retry_response = response.connection.send(retry_request, **kwargs)
        retry_response.history.append(response)
        retry_response.request = retry_request

        return retry_response
944108
function parseDigest(digest) {
    if (!digest)
        return false;
    // protect against missing data
    var needed_parts = {"nonce": 1, "nc": 1, "cnonce": 1, "qop": 1,
        "username": 1, "uri": 1, "response": 1};
    var data = {};

    digest.replace(/(\w+)=(?:(?:")([^"]+)"|([^\s,]+))/g, function(m, m1, m2, m3) {
        data[m1] = m2 ? m2 : m3;
        delete needed_parts[m1];
        return m;
    });

    return Object.keys(needed_parts).length ? false : data;
}
430904
def after_request(response)
      @response = HTTParty::Response.new(self, response, -> { HTTParty::Parser.new(response.body, Jiralicious::Session.format).parse }, body: response.body)
    end
1137869
def parse_response(self, response):
        """"""
        try:
            for header in response.getheader("set-cookie").split(", "):
                # filter 'expire' information
                if not header.startswith("D"):
                    continue
                cookie = header.split(";", 1)[0]
                cookieKey, cookieValue = cookie.split("=", 1)
                self._cookies[cookieKey] = cookieValue
        finally:
            return Transport.parse_response(self, response)
149061
def _handle_response(response):
        
        if not response.ok:
            raise NeverBounceAPIError(response)
        if response.headers.get('Content-Type') == 'application/octet-stream':
            return response.iter_lines()

        try:
            resp = response.json()
        except ValueError:
             raise InvalidResponseError('Failed to handle the response content-type {}.'.format(
                 response.headers.get('Content-Type'))
             )
        if 'success' in resp and not resp['success']:
            if 'msg' in resp and resp['msg'] == 'Authentication failed':
                raise AccessTokenExpired
            else:
                raise NeverBounceAPIError(response)
        return resp
920239
def unauthorized(self, response):
        ''''''
        realm = current_app.config.get('HTTP_OAUTH_REALM', 'uData')
        challenge = 'Bearer realm="{0}"'.format(realm)

        response.headers['WWW-Authenticate'] = challenge
        return response
816408
def _password_digest(username, password):
    
    if not isinstance(password, string_type):
        raise TypeError("password must be an "
                        "instance of %s" % (string_type.__name__,))
    if len(password) == 0:
        raise ValueError("password can't be empty")
    if not isinstance(username, string_type):
        raise TypeError("password must be an "
                        "instance of  %s" % (string_type.__name__,))

    md5hash = hashlib.md5()
    data = "%s:mongo:%s" % (username, password)
    md5hash.update(data.encode('utf-8'))
    return _unicode(md5hash.hexdigest())
1094672
def digest_auth(user, password)
      builder.insert(0, Faraday::Request::DigestAuth, user, password)
    end
1223523
def _do_digest(data, func):
    """"""
    func = FuncReg.get(func)
    hash = FuncReg.hash_from_func(func)
    if not hash:
        raise ValueError("no available hash function for hash", func)
    hash.update(data)
    return bytes(hash.digest())
157406
async function authenticate(scopes) {
  return new Promise((resolve, reject) => {
    // grab the url that will be used for authorization
    const authorizeUrl = oauth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: scopes.join(' '),
    });
    const server = http
      .createServer(async (req, res) => {
        try {
          if (req.url.indexOf('/oauth2callback') > -1) {
            const qs = new url.URL(req.url, 'http://localhost:3000')
              .searchParams;
            res.end('Authentication successful! Please return to the console.');
            server.destroy();
            const {tokens} = await oauth2Client.getToken(qs.get('code'));
            oauth2Client.credentials = tokens;
            resolve(oauth2Client);
          }
        } catch (e) {
          reject(e);
        }
      })
      .listen(3000, () => {
        // open the browser to the authorize url to start the workflow
        opn(authorizeUrl, {wait: false}).then(cp => cp.unref());
      });
    destroyer(server);
  });
}
631624
function(handler, realm, cbauth) {
        var req = handler.httpRequest;
        this.init(realm, req);

        var username = this.digestParts["username"];
        // No username was given
        if (!username)
            return this.requireAuth(realm, "No digest authentication headers were found", cbauth);

        var self = this;
        this.getDigestHash(realm, username, function(err, hash) {
            // If this was false, the user account didn't exist
            if (err || !hash)
                return self.requireAuth(realm, err || "The supplied username was not on file", cbauth);

            if (typeof hash != "string") {
                handler.handleError(new Exc.jsDAV_Exception(
                    "The returned value from getDigestHash must be a string or null"));
                return cbauth(null, false);
            }

            // If this was false, the password or part of the hash was incorrect.
            self.validateA1(handler, hash, function(isValid) {
                if (!isValid)
                    return self.requireAuth(realm, "Incorrect username", cbauth);

                self.currentUser = username;
                cbauth(null, true);
            });
        });
    }
697814
function(realm, req) {
        this.realm = realm;
        this.opaque = Util.createHash(this.realm);
        this.digest = getDigest(req);
        this.digestParts = parseDigest(this.digest);
    }
1091781
public void sendChallenge(UserRealm realm,
                              HttpRequest request,
                              HttpResponse response,
                              boolean stale)
        throws IOException
    {
        response.setField(HttpFields.__WwwAuthenticate,
			    "Digest realm=\""+realm.getName()+
			    "\", domain=\""+
			    response.getHttpContext().getContextPath() +
			    "\", nonce=\""+newNonce(request)+
			    "\", algorithm=MD5, qop=\"auth\"" + (useStale?(" stale="+stale):"")
                          );
        
        response.sendError(HttpResponse.__401_Unauthorized);
    }
113446
def handle_401(self, response, **kwargs):
        """"""

        log.debug("handle_401(): Handling: 401")
        if _negotiate_value(response) is not None:
            _r = self.authenticate_user(response, **kwargs)
            log.debug("handle_401(): returning {0}".format(_r))
            return _r
        else:
            log.debug("handle_401(): Kerberos is not supported")
            log.debug("handle_401(): returning {0}".format(response))
            return response
368958
def process(self, request, response, environ):
        
        try:
            data = self.site_adapter.authenticate(request, environ,
                                                  self.scope_handler.scopes,
                                                  self.client)
            data = AuthorizeMixin.sanitize_return_value(data)
        except UserNotAuthenticated:
            raise OAuthInvalidError(error="invalid_client",
                                    explanation=self.OWNER_NOT_AUTHENTICATED)

        if isinstance(data, Response):
            return data

        token_data = self.create_token(
            client_id=self.client.identifier,
            data=data[0],
            grant_type=ResourceOwnerGrant.grant_type,
            scopes=self.scope_handler.scopes,
            user_id=data[1])

        if self.scope_handler.send_back:
            token_data["scope"] = encode_scopes(self.scope_handler.scopes)

        json_success_response(data=token_data, response=response)

        return response
330111
def handle_401(self, response, exc=None):
        """"""
        if response.status_code == 401:
            s_auth = response.headers.get('www-authenticate', '')
            if 'digest' not in s_auth.lower():
                return
            request = response.request
            if not request.headers.get('authorization'):
                self.options = parse_dict_header(s_auth.replace('Digest ', ''))
                authorization = self.encode(request.method, request.url)
                params = request.inp_params.copy()
                headers = params.pop('headers', [])
                headers.append(('authorization', authorization))
                params['headers'] = headers
                response.request_again = request_again(request.method,
                                                       request.url,
                                                       params)