Request decorator. Forces authentication.
498914
def required(self, fn):
        """"""
        @functools.wraps(fn)
        def decorated(*args, **kwargs):
            if (not self._check_auth()
               # Don't try to force authentication if the request is part
               # of the authentication process - otherwise we end up in a
               # loop.
               and request.blueprint != self.blueprint.name):
                return redirect(url_for("%s.login" % self.blueprint.name,
                                        next=request.url))
            return fn(*args, **kwargs)
        return decorated
78543
def get_request_mock():
    """"""
    from django.test.client import RequestFactory
    from django.core.handlers.base import BaseHandler
    factory = RequestFactory()

    request = factory.get('/')
    
    class FakeUser():
        is_authenticated = False
        is_staff = False

    request.user = FakeUser()
    request.session = {}

    return request
476815
def authenticationRequest():
    """"""
    a = TpPd(pd=0x5)
    b = MessageType(mesType=0x12)  # 00010010
    c = CiphKeySeqNrAndSpareHalfOctets()
    d = AuthenticationParameterRAND()
    packet = a / b / c / d
    return packet
1104694
def auth_basic(check, realm="private", text="Access denied"):
    '''  '''
    def decorator(func):
        def wrapper(*a, **ka):
            user, password = request.auth or (None, None)
            if user is None or not check(user, password):
                err = HTTPError(401, text)
                err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                return err
            return func(*a, **ka)
        return wrapper
    return decorator
884633
def requires_authentication(func):
        
        def _auth(self, *args, **kwargs):
            if not self._authenticated:
                raise NotAuthenticatedException('Function {} requires'
                                                .format(func.__name__)
                                                + ' authentication')
            else:
                return func(self, *args, **kwargs)
        return _auth
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)
1130411
def authenticate(self, request):
        
        authenticators = self._meta.authenticators

        if request.method == 'OPTIONS' and ADREST_ALLOW_OPTIONS:
            self.auth = AnonimousAuthenticator(self)
            return True

        error_message = "Authorization required."
        for authenticator in authenticators:
            auth = authenticator(self)
            try:
                if not auth.authenticate(request):
                    raise AssertionError(error_message)

                self.auth = auth
                auth.configure(request)
                return True
            except AssertionError, e:
                error_message = str(e)

        raise HttpError(error_message, status=status.HTTP_401_UNAUTHORIZED)
108230
def key_required(group=None, perm=None, keytype=None):
    
    def decorator(f):
        def wrapper(request, *args, **kwargs):
            try:
                validate_key( request, group, perm, keytype )
                return f(request, *args, **kwargs)
            except AccessUnauthorized:
                return HttpResponse401( request )
            except AccessForbidden:
                return HttpResponse403( request )
        return wrapper 
    return decorator
544988
def requires_basic_auth(func):
    
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        if hasattr(self, '_session') and self._session.auth:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires username/password authentication"}'
            )
            raise GitHubError(r)
    return auth_wrapper
578054
def requires_auth(func):
    
    @six.wraps(func)
    def wrapper(self, *args, **kwargs):
        if self.token_expired:
            self.authenticate()
        return func(self, *args, **kwargs)
    return wrapper
1264756
def require_auth(request: Request, exceptions: bool=True) -> User:
    
    if not request.user or not request.user.is_authenticated:
        if exceptions:
            raise NotAuthenticated()
        return None
    return request.user
156081
def httpauth_login_required(func):
    

    def wrapper(request, *args, **kwargs):
        user = None
        # get the Basic username and password from the request.
        auth_string = request.META.get('HTTP_AUTHORIZATION', None)

        if auth_string:
            (authmeth, auth) = auth_string.split(" ", 1)
            auth = auth.strip().decode('base64')
            (username, password) = auth.split(':', 1)

            # print username, password
            user = authenticate(username=username, password=password)

        if not user or not user.is_active:
            return HttpResponse(unauthorized_json_response(),
                                content_type="application/json", status=401)
        login(request, user)
        return func(request, *args, **kwargs)

    return update_wrapper(wrapper, func)
43601
def response_hook(self, r, **kwargs):
        """"""
        if r.status_code == 401:
            # Handle server auth.
            www_authenticate = r.headers.get('www-authenticate', '').lower()
            auth_type = _auth_type_from_header(www_authenticate)

            if auth_type is not None:
                return self.retry_using_http_NTLM_auth(
                    'www-authenticate',
                    'Authorization',
                    r,
                    auth_type,
                    kwargs
                )
        elif r.status_code == 407:
            # If we didn't have server auth, do proxy auth.
            proxy_authenticate = r.headers.get(
                'proxy-authenticate', ''
            ).lower()
            auth_type = _auth_type_from_header(proxy_authenticate)
            if auth_type is not None:
                return self.retry_using_http_NTLM_auth(
                    'proxy-authenticate',
                    'Proxy-authorization',
                    r,
                    auth_type,
                    kwargs
                )

        return r
953580
def user_to_request(handler):
    ''''''
    @wraps(handler)
    async def decorator(*args):
        request = _get_request(args)
        request[cfg.REQUEST_USER_KEY] = await get_cur_user(request)
        return await handler(*args)
    return decorator
351442
def _require_auth(fnc):
    """"""
    @wraps(fnc)
    @_assure_identity
    def _wrapped(*args, **kwargs):
        if not identity.authenticated:
            msg = "Authentication required before calling '%s'." % fnc.__name__
            raise exc.NotAuthenticated(msg)
        return fnc(*args, **kwargs)
    return _wrapped
269469
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None):
    
    def wrapper(fn):
        @wraps(fn)
        def decorated(*args, **kwargs):
            if current_user.is_authenticated:
                if request.is_json:
                    abort(HTTPStatus.FORBIDDEN)
                else:
                    if msg:
                        flash(msg, category)
                    return redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT',
                                    override=redirect_url)
            return fn(*args, **kwargs)
        return decorated

    if decorator_args and callable(decorator_args[0]):
        return wrapper(decorator_args[0])
    return wrapper
172645
def authenticate(self, request, url_auth_token=None):
        
        try:
            return self.parse_token(url_auth_token)
        except TypeError:
            backend = "%s.%s" % (self.__module__, self.__class__.__name__)
            logger.exception("TypeError in %s, here's the traceback before "
                             "Django swallows it:", backend)
            raise