Get valid user attempts that match the given request and credentials.
878
def get_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet:
    

    attempts = filter_user_attempts(request, credentials)

    if settings.AXES_COOLOFF_TIME is None:
        log.debug('AXES: Getting all access attempts from database because no AXES_COOLOFF_TIME is configured')
        return attempts

    threshold = get_cool_off_threshold(request.axes_attempt_time)
    log.debug('AXES: Getting access attempts that are newer than %s', threshold)
    return attempts.filter(attempt_time__gte=threshold)
235862
def _get_credentials(self, request):
        
        authorization = request.headers.get('Authorization')
        if not authorization:
            return None
        try:
            authmeth, authbytes = authorization.split(' ', 1)
        except ValueError:  # not enough values to unpack
            return None
        if authmeth.lower() != 'apikey':
            return None

        if six.PY2 or isinstance(authbytes, bytes):
            try:
                auth = authbytes.decode('utf-8')
            except UnicodeDecodeError:
                auth = authbytes.decode('latin-1')
        else:
            auth = authbytes

        try:
            username, api_key = auth.split(':', 1)
        except ValueError:  # not enough values to unpack
            return None
        return username, api_key
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
737934
def check_key(request):
    '''
        
    '''
    api_objs = list(Api.objects.filter(name=request.POST['api']))
    if not api_objs:
        return HttpResponseBadRequest('Must specify valid API')

    # check the signature
    if get_signature(request.POST, api_objs[0].signing_key) != request.POST['signature']:
        return HttpResponseBadRequest('bad signature')

    get_object_or_404(Key, key=request.POST['key'], status='A')

    return HttpResponse('OK')
1021366
def validate_authorization_request(self, uri, http_method='GET', body=None,
                                       headers=None):
        """"""
        request = Request(
            uri, http_method=http_method, body=body, headers=headers)

        request.scopes = utils.scope_to_list(request.scope)

        response_type_handler = self.response_types.get(
            request.response_type, self.default_response_type_handler)
        return response_type_handler.validate_authorization_request(request)
16962
def _validate_auths(self, path, obj, app):
        
        errs = []

        for k, v in six.iteritems(obj.authorizations or {}):
            if k not in app.raw.authorizations:
                errs.append('auth {0} not found in resource list'.format(k))

            if app.raw.authorizations[k].type in ('basicAuth', 'apiKey') and v != []:
                errs.append('auth {0} should be an empty list'.format(k))

        return path, obj.__class__.__name__, errs
59542
def getCredentials(self):
        """"""

        (username, password, public_key, private_key) = self.getCredentialValues()

        if public_key or private_key:
            return UserKeyCredential(username, public_key, private_key)

        if username or password:
            return UserPassCredential(username, password)

        return None
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
446031
def filter_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet:
    

    username = get_client_username(request, credentials)

    filter_kwargs = get_client_parameters(username, request.axes_ip_address, request.axes_user_agent)

    return AccessAttempt.objects.filter(**filter_kwargs)
553908
def callback(self, username, request):
        
        credentials = self._get_credentials(request)
        if credentials:
            username, api_key = credentials
            if self.check:
                return self.check(username, api_key, request)
880707
def get_auth_params_from_request(request):
    
    return (
        request.user.username,
        request.user.token.id,
        request.user.tenant_id,
        request.user.token.project.get('domain_id'),
        base.url_for(request, 'compute'),
        base.url_for(request, 'identity')
    )
1028598
def authenticate(self, request):
        
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b'token':
            return None

        if len(auth) == 1:
            msg = _('Invalid auth token header. No credentials provided.')
            raise AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid auth token.')
            raise AuthenticationFailed(msg)

        try:
            token = urlsafe_b64decode(auth[1])
        except ValueError:
            msg = _('Invalid auth token.')
            raise AuthenticationFailed(msg)

        return self.authenticate_credentials(token, request)
464016
def _validate_auth(self, path, obj, _):
        
        errs = []

        if obj.type == 'apiKey':
            if not obj.passAs:
                errs.append('need "passAs" for apiKey')
            if not obj.keyname:
                errs.append('need "keyname" for apiKey')

        elif obj.type == 'oauth2':
            if not obj.grantTypes:
                errs.append('need "grantTypes" for oauth2')

        return path, obj.__class__.__name__, errs
84314
def authenticate_user(self, request, user):
        
        return user.check_password(request.data.get('password')) or \
               self.check_user_token(request, user)
985258
def authenticate(api_key, api_url, **kwargs):
    """"""

    muddle = Muddle(**kwargs)

    # Login.
    muddle.authenticate(api_key, api_url)
    return muddle
311759
def _check_auth(self, username: str, password: str) -> bool:
        """"""
        try:
            return self.credentials[username] == password
        except KeyError:
            return False
334681
def get_user_matches(session, user_id, from_timestamp=None, limit=None):
    """"""
    return get_recent_matches(session, '{}{}/{}/Matches/games/matches/user/{}/0'.format(
        session.auth.base_url, PROFILE_URL, user_id, user_id), from_timestamp, limit)