Decorator to require API authentication using OAuth token.

    :param allow_anonymous: Allow access without OAuth token
        (default: ``False``).
962613
def require_api_auth(allow_anonymous=False):
    
    def wrapper(f):
        """Wrap function with oauth require decorator."""
        f_oauth_required = oauth2.require_oauth()(f)

        @wraps(f)
        def decorated(*args, **kwargs):
            """Require OAuth 2.0 Authentication."""
            if not hasattr(current_user, 'login_via_oauth2'):
                if not current_user.is_authenticated:
                    if allow_anonymous:
                        return f(*args, **kwargs)
                    abort(401)
                if current_app.config['ACCOUNTS_JWT_ENABLE']:
                    # Verify the token
                    current_oauth2server.jwt_veryfication_factory(
                        request.headers)
                # fully logged in with normal session
                return f(*args, **kwargs)
            else:
                # otherwise, try oauth2
                return f_oauth_required(*args, **kwargs)
        return decorated
    return wrapper
988741
def _auth_required(method, validator):
    
    @gen.coroutine
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        token = _get_token(self.request)
        valid_token = yield validator(token)
        if not valid_token:
            message = 'Invalid token: {}'.format(token)
            logging.warning(message)
            raise HTTPError(401, message)
        result = method(self, *args, **kwargs)

        if isinstance(result, Future):
            result = yield result

        raise gen.Return(result)

    return wrapper
95271
def auth_required(self, view):
        

        @functools.wraps(view)
        def decorated(*args, **kwargs):
            log.info("Trying to get access to protected resource: '%s'", view.__name__)
            if request.method == 'POST':
                token = request.form['token']
                if self.development or self.authenticated(token):
                    return view(*args, **kwargs)
                else:
                    log.warning("User has not been authorized to get access to resource: %s", view.__name__)
            else:
                log.warning("Bad request type! Expected 'POST', actual '%s'", request.method)

            return abort(403)

        return decorated
998111
def token_required(scopes='', new=False):
    

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):

            # if we're coming back from SSO for a new token, return it
            token = _check_callback(request)
            if token and new:
                logger.debug("Got new token from {0} session {1}. Returning to view.".format(request.user, request.session.session_key[:5]))
                return view_func(request, token, *args, **kwargs)

            # if we're selecting a token, return it
            if request.method == 'POST':
                if request.POST.get("_add", False):
                    logger.debug("{0} has selected to add new token. Redirecting to SSO.".format(request.user))
                    # user has selected to add a new token
                    from esi.views import sso_redirect
                    return sso_redirect(request, scopes=scopes)

                token_pk = request.POST.get('_token', None)
                if token_pk:
                    logger.debug("{0} has selected token {1}".format(request.user, token_pk))
                    try:
                        token = Token.objects.get(pk=token_pk)
                        # ensure token belongs to this user and has required scopes
                        if ((token.user and token.user == request.user) or not token.user) and Token.objects.filter(
                                pk=token_pk).require_scopes(scopes).require_valid().exists():
                            logger.debug("Selected token fulfills requirements of view. Returning.")
                            return view_func(request, token, *args, **kwargs)
                    except Token.DoesNotExist:
                        logger.debug("Token {0} not found.".format(token_pk))
                        pass

            if not new:
                # present the user with token choices
                tokens = Token.objects.filter(user__pk=request.user.pk).require_scopes(scopes).require_valid()
                if tokens.exists():
                    logger.debug("Returning list of available tokens for {0}.".format(request.user))
                    from esi.views import select_token
                    return select_token(request, scopes=scopes, new=new)
                else:
                    logger.debug("No tokens found for {0} session {1} with scopes {2}".format(request.user, request.session.session_key[:5], scopes))

            # prompt the user to add a new token
            logger.debug("Redirecting {0} session {1} to SSO.".format(request.user, request.session.session_key[:5]))
            from esi.views import sso_redirect
            return sso_redirect(request, scopes=scopes)

        return _wrapped_view

    return decorator
107309
def should_require_authentication(self, url):
        
        return (not self.routes # require auth for all URLs
                or any(route.match(url) for route in self.routes))
706684
def require_oauth(self, realm=None, require_resource_owner=True,
            require_verifier=False, require_realm=False):
        """"""

        def decorator(f):
            @wraps(f)
            def verify_request(*args, **kwargs):
                """Verify OAuth params before running view function f"""
                try:
                    if request.form:
                        body = request.form.to_dict()
                    else:
                        body = request.data.decode("utf-8")
                    verify_result = self.verify_request(request.url.decode("utf-8"),
                            http_method=request.method.decode("utf-8"),
                            body=body,
                            headers=request.headers,
                            require_resource_owner=require_resource_owner,
                            require_verifier=require_verifier,
                            require_realm=require_realm or bool(realm),
                            required_realm=realm)
                    valid, oauth_request = verify_result
                    if valid:
                        request.oauth = self.collect_request_parameters(request)

                        # Request tokens are only valid when a verifier is too
                        token = {}
                        if require_verifier:
                            token[u'request_token'] = request.oauth.resource_owner_key
                        else:
                            token[u'access_token'] = request.oauth.resource_owner_key

                        # All nonce/timestamp pairs must be stored to prevent
                        # replay attacks, they may be connected to a specific
                        # client and token to decrease collision probability.
                        self.save_timestamp_and_nonce(request.oauth.client_key,
                                request.oauth.timestamp, request.oauth.nonce,
                                **token)

                        # By this point, the request is fully authorized
                        return f(*args, **kwargs)
                    else:
                        # Unauthorized requests should not diclose their cause
                        raise Unauthorized()

                except ValueError as err:
                    # Caused by missing of or badly formatted parameters
                    raise BadRequest(err.message)

            return verify_request
        return decorator
306405
def requires_api_auth(fn):
    """"""
    def wrapper(self, *args, **kwargs):
        self.auth_context = HAPI.auth_context_hapi
        return fn(self, *args, **kwargs)
    return wrapper
1217129
def api_auth(func):
    
    @wraps(func)
    def _decorator(request, *args, **kwargs):
        authentication = APIAuthentication(request)
        if authentication.authenticate():
            return func(request, *args, **kwargs)
        raise Http404
    return _decorator
469647
def auth_required(secret_key_func):
    
    def actual_decorator(obj):

        def test_func(request, *args, **kwargs):
            secret_key = secret_key_func(request, *args, **kwargs)
            return validate_signature(request, secret_key) or request.user.is_authenticated()

        decorator = request_passes_test(test_func)
        return wrap_object(obj, decorator)

    return actual_decorator
762283
def required(self, func):
        
        @wraps(func)
        def decorated(*args, **kwargs):
            """
            Actual wrapper to run the auth checks.
            """
            is_valid, user = self.authenticate()
            if not is_valid:
                return self.auth_failed()
            kwargs['user'] = user
            return func(*args, **kwargs)
        return decorated
1067693
def oauth_required(f):
        
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if 'oauth_user_uri' not in session or session['oauth_user_uri'] is None:
                return redirect(url_for('.r_oauth_login', next=request.url))
            return f(*args,**kwargs)
        return decorated_function
277955
def ssl_required(allow_non_ssl=False):
    
    def wrapper(view_func):
        def _checkssl(request, *args, **kwargs):
            # allow_non_ssl=True lets non-https requests to come
            # through to this view (and hence not redirect)
            if hasattr(settings, 'SSL_ENABLED') and settings.SSL_ENABLED \
                    and not request.is_secure() and not allow_non_ssl:
                return HttpResponseRedirect(
                    request.build_absolute_uri().replace('http://', 'https://'))
            return view_func(request, *args, **kwargs)

        return _checkssl
    return wrapper
910688
def requires_auth(func):
    """"""
    @wraps(func)
    def auth_wrapper(self, *args, **kwargs):
        auth = False
        if hasattr(self, '_session'):
            auth = (self._session.auth or
                    self._session.headers.get('Authorization'))

        if auth:
            return func(self, *args, **kwargs)
        else:
            from .models import GitHubError
            # Mock a 401 response
            r = generate_fake_error_response(
                '{"message": "Requires authentication"}'
            )
            raise GitHubError(r)
    return auth_wrapper
1329452
def requires_auth(f):
    

    @wraps(f)
    def requires_auth_decorator(*args, **kwargs):

        try:
            authenticate_http_request()
        except PyMacaronException as e:
            return e.http_reply()

        return f(*args, **kwargs)

    return requires_auth_decorator
1110145
def add_auth(f):
    """"""

    def add_auth_decorator(*args, **kwargs):
        token = get_user_token()
        if 'headers' not in kwargs:
            kwargs['headers'] = {}
        kwargs['headers']['Authorization'] = "Bearer %s" % token
        return f(*args, **kwargs)

    return add_auth_decorator
258921
def requires_auth(f):
    
    @wraps(f)

    def decorated(self, *args, **kwargs):
        

        # Fetch auth options from args
        auth_options = {}
        nipap_args = {}

        # validate function arguments
        if len(args) == 1:
            nipap_args = args[0]
        else:
            self.logger.debug("Malformed request: got %d parameters" % len(args))
            raise Fault(1000, ("NIPAP API functions take exactly 1 argument (%d given)") % len(args))

        if type(nipap_args) != dict:
            self.logger.debug("Function argument is not struct")
            raise Fault(1000, ("Function argument must be XML-RPC struct/Python dict (Python %s given)." %
                type(nipap_args).__name__ ))

        # fetch auth options
        try:
            auth_options = nipap_args['auth']
            if type(auth_options) is not dict:
                raise ValueError()
        except (KeyError, ValueError):
            self.logger.debug("Missing/invalid authentication options in request.")
            raise Fault(1000, ("Missing/invalid authentication options in request."))

        # fetch authoritative source
        try:
            auth_source = auth_options['authoritative_source']
        except KeyError:
            self.logger.debug("Missing authoritative source in auth options.")
            raise Fault(1000, ("Missing authoritative source in auth options."))

        if not request.authorization:
            return authenticate()

        # init AuthFacory()
        af = AuthFactory()
        auth = af.get_auth(request.authorization.username,
                request.authorization.password, auth_source, auth_options or {})

        # authenticated?
        if not auth.authenticate():
            self.logger.debug("Incorrect username or password.")
            raise Fault(1510, ("Incorrect username or password."))

        # Replace auth options in API call arguments with auth object
        new_args = dict(args[0])
        new_args['auth'] = auth

        return f(self, *(new_args,), **kwargs)

    return decorated
14874
def require_auth(view_func):
    
    from horizon.exceptions import NotAuthenticated

    @functools.wraps(view_func, assigned=available_attrs(view_func))
    def dec(request, *args, **kwargs):
        if request.user.is_authenticated:
            return view_func(request, *args, **kwargs)
        raise NotAuthenticated(_("Please log in to continue."))
    return dec