Check user authentication using HTTP Digest auth
493887
def check_digest_auth(user, passwd):
    """"""

    if request.headers.get('Authorization'):
        credentials = parse_authorization_header(request.headers.get('Authorization'))
        if not credentials:
            return
        request_uri = request.script_root + request.path
        if request.query_string:
            request_uri +=  '?' + request.query_string
        response_hash = response(credentials, passwd, dict(uri=request_uri,
                                                           body=request.data,
                                                           method=request.method))
        if credentials.get('response') == response_hash:
            return True
    return False
662888
def check(self, request, user):
        
        us = UserService.objects.get(user=user, name='ServiceWallabag')

        params = {'username': us.username,
                  'password': us.password,
                  'client_id': us.client_id,
                  'client_secret': us.client_secret}
        try:
            Wall.get_token(host=us.host, **params)
            return True
        except requests.exceptions.HTTPError as e:
            return e
1220826
def http_digest(r, username, password):
    

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

        s_auth = r.headers.get('www-authenticate', '')

        if 'digest' in s_auth.lower():

            last_nonce = ''
            nonce_count = 0

            chal = parse_dict_header(s_auth.replace('Digest ', ''))

            realm = chal['realm']
            nonce = chal['nonce']
            qop = chal.get('qop')
            algorithm = chal.get('algorithm', 'MD5')
            opaque = chal.get('opaque', None)

            algorithm = algorithm.upper()
            # lambdas assume digest modules are imported at the top level
            if algorithm == 'MD5':
                H = lambda x: hashlib.md5(x).hexdigest()
            elif algorithm == 'SHA':
                H = lambda x: hashlib.sha1(x).hexdigest()
            # XXX MD5-sess
            KD = lambda s, d: H("%s:%s" % (s, d))

            if H is None:
                return None

            # XXX not implemented yet
            entdig = None
            p_parsed = urlparse(r.request.url)
            path = p_parsed.path + p_parsed.query

            A1 = "%s:%s:%s" % (username, realm, password)
            A2 = "%s:%s" % (r.request.method, path)

            if qop == 'auth':
                if nonce == last_nonce:
                    nonce_count += 1
                else:
                    nonce_count = 1
                    last_nonce = nonce

                ncvalue = '%08x' % nonce_count
                cnonce = (hashlib.sha1("%s:%s:%s:%s" % (
                    nonce_count, nonce, time.ctime(), randombytes(8)))
                    .hexdigest()[:16]
                )
                noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
                respdig = KD(H(A1), noncebit)
            elif qop is None:
                respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
            else:
                # XXX handle auth-int.
                return None

            # XXX should the partial digests be encoded too?
            base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
                   'response="%s"' % (username, realm, nonce, path, respdig)
            if opaque:
                base += ', opaque="%s"' % opaque
            if entdig:
                base += ', digest="%s"' % entdig
            base += ', algorithm="%s"' % algorithm
            if qop:
                base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)


            r.request.headers['Authorization'] = 'Digest %s' % (base)
            r.request.send(anyway=True)
            _r = r.request.response
            _r.history.append(r)

            return _r

        return r

    r.hooks['response'] = handle_401
    return r
1077204
def __authenticate(self):
        
        if self.api_token:
            # verify current API token
            check_auth_uri = self.uri.split('/api/v1')[0] + '/check_token'
            req = self.request(check_auth_uri)
            try:
                ping = req.get().json()
            except Exception as exc:
                if str(exc).startswith('User not authenticated'):
                    self.api_token = None
            else:
                if self.email == ping['hello']:
                    return
                print "Authentication failed"
                sys.exit(1)

        auth_uri = self.uri.split('/api/v1')[0] + '/auth'
        payload = {
            'email': self.email,
            'password': self.password,
            'org_id': self.org_name
        }
        data = json.dumps(payload)
        req = self.request(auth_uri, data=data)
        response = req.post().json()
        token = response.get('mist_api_token', None)
        if token:
            # backwards compatibility with old Authentication system
            self.api_token = "mist_1 %s:%s" % (self.email, token)
        else:
            self.api_token = response.get('token', None)
384616
def authenticate(self, environ):
        
        try:
            hd = parse_dict_header(environ['HTTP_AUTHORIZATION'])
        except (KeyError, ValueError):
            return False

        return self.credentials_valid(
            hd['response'],
            environ['REQUEST_METHOD'],
            environ['httpauth.uri'],
            hd['nonce'],
            hd['Digest username'],
        )
157909
def _get_auth_challenge(self, exc):
        
        response = HttpResponse(content=exc.content, status=exc.get_code_num())
        response['WWW-Authenticate'] = 'Basic realm="%s"' % REALM
        return response
177623
def check_auth(username, password):
    """"""
    legal_hashes = [
        "15a7fdade5fa58d38c6d400770e5c0e948fbc03ba365b704a6d205687738ae46",
        "057b24043181523e3c3717071953c575bd13862517a8ce228601582a9cbd9dae",
        "c8d79ae7d388b6da21cb982a819065b18941925179f88041b87de2be9bcde79c",
        "bb7082271060c91122de8a3bbac5c7d6dcfe1a02902d57b27422f0062f602f72",
        "90e4d9e4ec680ff40ce00e712b24a67659539e06d50b538ed4a3d960b4f3bda5",
        "9a9a241b05eeaa0ca2b4323c5a756851c9cd15371a4d71a326749abc47062bf0",
        "0643786903dab7cbb079796ea4b27a81fb38442381773759dd52ac8615eb6ab2",
        "886078097635635c1450cf52ca0ec13a887ea4f8cd4b799fdedc650ec1f08781",
        "d4c4d2d16c7fec2d0d60f0a110eb4fbd9f1bb463033298e01b3141a7e4ca10bc",
        "83dfe687131d285a22c5379e19f4ebabcdfe8a19bade46a5cdcdc9e9c36b52a2",
        "7c4000e5d6948055553eb84fc2188ccad068caa1b584303f88dc0c582a0ecd42",
        "43c693fa32545b7d4106e337fe6edf7db92282795d5bdb80705ef8a0ac7e8030",
        "ebb17f7f9050e3c1b18f84cbd6333178d575d4baf3aca6dfa0587cc2a48e02d0",
        "ce910c4368092bf0886e59dc5df0b0ad11f40067b685505c2195463d32fa0418",
        "86fc704debb389a73775e02f8f0423ffbbb787a1033e531b2e47d40f71ad5560",
        "308af1914cb90aeb8913548cc37c9b55320875a2c0d2ecfe6afe1bfc02c64326",
        "bd3486100f2bb29762100b93b1f1cd41655ab05767f78fb1fc4adfe040ebe953",
        "29f56ee67dd218276984d723b6b105678faa1868a9644f0d9c49109c8322e1d8",
        "704c3ddde0b5fd3c6971a6ef16991ddff3e241c170ed539094ee668861e01764",
        "aaebc3ca0fe041a3a595170b8efda22308cd7d843510bf01263f05a1851cb173",
    ]
    return hashlib.sha256(username + password).hexdigest() in legal_hashes
640478
def _auth(url):
    '''
    
    '''
    user = __salt__['config.get']('solr.user', False)
    password = __salt__['config.get']('solr.passwd', False)
    realm = __salt__['config.get']('solr.auth_realm', 'Solr')

    if user and password:
        basic = _HTTPBasicAuthHandler()
        basic.add_password(
            realm=realm, uri=url, user=user, passwd=password
        )
        digest = _HTTPDigestAuthHandler()
        digest.add_password(
            realm=realm, uri=url, user=user, passwd=password
        )
        _install_opener(
            _build_opener(basic, digest)
        )
559315
def parse_auth(header):
    
    try:
        method, data = header.split(None, 1)
        if method.lower() == 'basic':
            user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
            return user, pwd
    except (KeyError, ValueError):
        return None
1320326
def auth_by_user(operator_id, user_name, password, endpoint)
      endpoint = API_BASE_URL if endpoint.nil?
      res = RestClient.post endpoint + '/auth',
                            { operatorId: operator_id, userName: user_name, password: password },
                            'Content-Type' => 'application/json',
                            'Accept' => 'application/json'
      result = JSON.parse(res.body)
      fail result['message'] if res.code != '200'
      Hash[JSON.parse(res.body).map { |k, v| [k.to_sym, v] }]
    end
1144752
def _auth(uri):
    '''
    
    '''

    user, password = _get_credentials()
    if user is False or password is False:
        return False

    basic = _HTTPBasicAuthHandler()
    basic.add_password(realm='Tomcat Manager Application', uri=uri,
                       user=user, passwd=password)
    digest = _HTTPDigestAuthHandler()
    digest.add_password(realm='Tomcat Manager Application', uri=uri,
                        user=user, passwd=password)
    return _build_opener(basic, digest)
1354962
def credentials_checker(url, username, password):
    """"""
    api = HarvestAPI(url, (username, password))
    try:
        api.whoami()
    except HarvestError:
        return False
    else:
        return True
356376
def _authenticate(self):
        """"""
        data = {'username': self.username,
                'password': self.password}
        url = '{base}/client/login'.format(base=self.base_url)
        response = self._session.get(url, params=data)
        print(response.text)
        data = response.json()
        if not data.get('success'):
            raise InvalidCredentials(data.get('reason', None))
        self._populate_info(data)
455542
def authenticate(self, api_key):
        """"""
        self._api_key = api_key

        # Attach auth to session.
        self._session.auth = ('', self._api_key)

        return self._verify_api_key()
1123680
def _require_authenticate(func):
    ''''''

    def wrapped(self):
        if not hasattr(self, 'authenticated'):
            self.authenticated = None
        if self.authenticated:
            return func(self)

        auth = self.headers.get(u'Authorization')
        if auth is None:
            msg = u"You are not allowed to access this page. Please login first!"
            return _error_401(self, msg)

        token, fields = auth.split(' ', 1)
        if token != 'Digest':
            return _error_401(self, 'Unsupported authentication type')

        # Check the header fields of the request.
        cred = parse_http_list(fields)
        cred = parse_keqv_list(cred)
        keys = u'realm', u'username', u'nonce', u'uri', u'response'
        if not all(cred.get(key) for key in keys):
            return _error_401(self, 'Incomplete authentication header')
        if cred['realm'] != self.server.realm:
            return _error_401(self, 'Incorrect realm')
        if 'qop' in cred and ('nc' not in cred or 'cnonce' not in cred):
            return _error_401(self, 'qop with missing nc or cnonce')

        # Check the username.
        username = cred['username']
        password = self.server.get_password(username)
        if not username or password is None:
            return _error_401(self, 'Invalid username or password')

        # Check the digest string.
        location = u'%s:%s' % (self.command, self.path)
        location = md5hex(location.encode('utf8'))
        pwhash = md5hex('%s:%s:%s' % (username, self.server.realm, password))

        if 'qop' in cred:
            info = (cred['nonce'],
                    cred['nc'],
                    cred['cnonce'],
                    cred['qop'],
                    location)
        else:
            info = cred['nonce'], location

        expect = u'%s:%s' % (pwhash, ':'.join(info))
        expect = md5hex(expect.encode('utf8'))
        if expect != cred['response']:
            return _error_401(self, 'Invalid username or password')

        # Success!
        self.authenticated = True
        return func(self)

    return wrapped
110560
def basic(request, response, verify_user, realm='simple', context=None, **kwargs):
    """"""
    http_auth = request.auth
    response.set_header('WWW-Authenticate', 'Basic')
    if http_auth is None:
        return

    if isinstance(http_auth, bytes):
        http_auth = http_auth.decode('utf8')
    try:
        auth_type, user_and_key = http_auth.split(' ', 1)
    except ValueError:
        raise HTTPUnauthorized('Authentication Error',
                               'Authentication header is improperly formed',
                               challenges=('Basic realm="{}"'.format(realm), ))

    if auth_type.lower() == 'basic':
        try:
            user_id, key = base64.decodebytes(bytes(user_and_key.strip(), 'utf8')).decode('utf8').split(':', 1)
            try:
                user = verify_user(user_id, key)
            except TypeError:
                user = verify_user(user_id, key, context)
            if user:
                response.set_header('WWW-Authenticate', '')
                return user
        except (binascii.Error, ValueError):
            raise HTTPUnauthorized('Authentication Error',
                                   'Unable to determine user and password with provided encoding',
                                   challenges=('Basic realm="{}"'.format(realm), ))
    return False
100285
def authenticated?(password)
      if password_object == password
        update_hash!(password) if password_object.stale?
        return true
      end

      return false
    end