コード例 #1
0
def wrap_object(obj, decorator):
    """
    Decorates the given object with the decorator function.

    If obj is a method, the method is decorated with the decorator function
    and returned. If obj is a class (i.e., a class based view), the methods
    in the class corresponding to HTTP methods will be decorated and the
    resultant class object will be returned.
    """
    actual_decorator = method_decorator(decorator)

    if inspect.isfunction(obj):
        wrapped_obj = actual_decorator(obj)
        update_wrapper(wrapped_obj, obj, assigned=available_attrs(obj))
    elif inspect.isclass(obj):
        for method_name in obj.http_method_names:
            if hasattr(obj, method_name):
                method = getattr(obj, method_name)
                wrapped_method = actual_decorator(method)
                update_wrapper(wrapped_method, method, assigned=available_attrs(method))
                setattr(obj, method_name, method)
        wrapped_obj = obj
    else:
        raise TypeError("received an object of type '{0}' expected 'function' or 'classobj'.".format(type(obj)))

    return wrapped_obj
コード例 #2
0
ファイル: duo_auth.py プロジェクト: nachiketmistry/duo_python
 def decorator(view_func):
     @wraps(view_func, assigned=available_attrs(view_func))
     def _wrapped_view(request, *args, **kwargs):
         if duo_authenticated(request):
             return view_func(request, *args, **kwargs)
         path = urlquote(request.get_full_path())
         return HttpResponseRedirect(
             '%s?%s=%s' % (
                 settings.DUO_LOGIN_URL, redirect_field_name, path))
     return wraps(
         view_func, assigned=available_attrs(view_func))(_wrapped_view)
コード例 #3
0
ファイル: decorators.py プロジェクト: Rudy24/modnoemesto
 def decorator(view_func):
     def _wrapped_view(request, *args, **kwargs):
         if request.META.get('REMOTE_ADDR') in settings.ALLOWED_SERVER_IPS:
             return view_func(request, *args, **kwargs)
         logger.debug('access denied for %s' % request.META.get('REMOTE_ADDR'))
         return HttpResponseNotFound()
     return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
コード例 #4
0
ファイル: workflow.py プロジェクト: artefactop/uppsell
 def decorator(func):
     @wraps(func, assigned=available_attrs(func))
     def inner(signal, key, transition, sender, model, state, **kwargs):
         if key == on_key and model.__class__ == on_model and on_transition in (transition, ALL) and on_state in (state, ALL):
                return func(signal, key, transition, sender, model, state)
     post_transition_signal.connect(inner)
     return inner
コード例 #5
0
    def wrapper(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def inner(request, *args, **kwargs):
            _kwargs = copy.copy(kwargs)
            # overwrite queryset if specified
            if queryset:
                _kwargs["queryset"] = queryset

            # get object from view
            if "date_field" in _kwargs:
                fn = get_object_from_date_based_view
            else:
                fn = get_object_from_list_detail_view
            if fn.validate(request, *args, **_kwargs):
                obj = fn(request, *args, **_kwargs)
            else:
                # required arguments is not passed
                obj = None

            if not request.user.has_perm(perm, obj=obj):
                if raise_exception:
                    raise PermissionDenied
                else:
                    return redirect_to_login(request, login_url)
            return view_func(request, *args, **_kwargs)

        return inner
コード例 #6
0
ファイル: cache.py プロジェクト: 007lva/mmddpp
 def _cache_controller(viewfunc):
     @wraps(viewfunc, assigned=available_attrs(viewfunc))
     def _cache_controlled(request, *args, **kw):
         response = viewfunc(request, *args, **kw)
         patch_cache_control(response, **kwargs)
         return response
     return _cache_controlled
コード例 #7
0
    def wrapper(view_method):
        @wraps(view_method, assigned=available_attrs(view_method))
        def inner(self, request=None, *args, **kwargs):
            if isinstance(self, HttpRequest):
                from permission.decorators.functionbase import \
                        permission_required as decorator
                # this is a functional view not classbased view.
                decorator = decorator(perm, queryset,
                                      login_url, raise_exception)
                decorator = decorator(view_method)
                if not request:
                    args = list(args)
                    args.insert(0, request)
                request = self
                return decorator(request, *args, **kwargs)
            else:
                from permission.decorators.classbase import \
                        get_object_from_classbased_instance
                # get object
                obj = get_object_from_classbased_instance(
                        self, queryset, request, *args, **kwargs
                    )

                if not request.user.has_perm(perm, obj=obj):
                    if raise_exception:
                        raise PermissionDenied
                    else:
                        return redirect_to_login(request, login_url)
                return view_method(self, request, *args, **kwargs)
        return inner
コード例 #8
0
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request):
                return view_func(request, *args, **kwargs)

            if request.is_ajax():
                return JsonResponse({
                    'status': 'no_auth',
                    'msg': '请先登录',
                })

            path = request.build_absolute_uri()
            # urlparse chokes on lazy objects in Python 3, force to str
            resolved_login_url = force_str(
                resolve_url(login_url or settings.LOGIN_URL))
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return _wrapped_view
コード例 #9
0
 def decorator(view_func):
     @wraps(view_func, assigned=available_attrs(view_func))
     def _wrapped_view(request, *args, **kwargs):
         return cache_page(timeout, key_prefix="_auth_{key}_".format(
             key=request.user.pk)
         )(view_func)(request, *args, **kwargs)
     return _wrapped_view
コード例 #10
0
    def decorator(view_func):
        @functools.wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if data_loc == 'POST':
                value = request.POST.get(req_data_key)
            elif data_loc == 'GET':
                value = request.GET.get(req_data_key)
            else:
                value = kwargs.get(req_data_key)

            if not value:
                # Couldn't find requested req_data_key in POST/GET
                return view_func(request, *args, **kwargs)

            obj_kwargs = {field_data_key: value}
            obj = model.objects.get(**obj_kwargs)
            response = view_func(request, *args, **kwargs)
            audit.send(
                sender=model,
                instance=obj,
                relations=relations,
                user=request.user,
                force=force
            )
            return response
        return _wrapped_view
コード例 #11
0
ファイル: decorators.py プロジェクト: jbl2024/django-gluten
    def decorator(func):
        def inner(request, *args, **kwargs):
            if request.method not in methods:
                logger.warning(
                    'Method Not Allowed (%s): %s' % (
                        request.method, request.path),
                    extra={
                        'status_code': 405,
                        'request': request
                    }
                )
                return HttpResponseNotAllowed(methods)

            coerce_put_post(request)

            language = requested_language(request)
            if language is not None and language != request.LANGUAGE_CODE:
                activate_language(language)

            authorized = check_api_key_authentication(request)
            if not authorized:
                authorized = request.user.is_authenticated()
            if login_required and not authorized:
                return HttpResponse(status=401)

            return func(request, *args, **kwargs)
        return wraps(func, assigned=available_attrs(func))(inner)
コード例 #12
0
ファイル: decorators.py プロジェクト: ossobv/pstore
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            humanargs = ', '.join(list(args) +
                                  ['%s=%s' % (k, v)
                                   for k, v in kwargs.items()])
            address = str(request.META.get('REMOTE_ADDR', 'UNKNOWN_IP'))
            if request.user.is_anonymous():
                message = (u'Anonymous user on %s %s %s' %
                           (address, description, humanargs))
            else:
                username = request.user.username.replace(' ', '_')
                message = (u'User %s on %s %s %s' %
                           (username, address, description, humanargs))

            if mutates:
                # Use 'warning' as there is no 'notice' level. And encode
                # as UTF-8 because the automatic encoding would add a BOM
                # before the message. See:
                # http://serverfault.com/questions/407643/
                #       rsyslog-update-on-amazon-linux-suddenly-treats-
                #       info-level-messages-as-emerg
                logger.warning(message.encode('utf-8'))
            else:
                logger.info(message.encode('utf-8'))

            return func(request, *args, **kwargs)
        return inner
コード例 #13
0
ファイル: vary.py プロジェクト: SvetlanaM/EnabledCityPaloAlto
 def decorator(func):
     @wraps(func, assigned=available_attrs(func))
     def inner_func(*args, **kwargs):
         response = func(*args, **kwargs)
         patch_vary_headers(response, headers)
         return response
     return inner_func
コード例 #14
0
ファイル: http.py プロジェクト: mpetyx/mpetyx.com
    def decorator(func):
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)

        return wraps(func, assigned=available_attrs(func))(inner)
コード例 #15
0
ファイル: decorators.py プロジェクト: Seraf/numeter
 def decorator(func):
     @wraps(func, assigned=available_attrs(func))
     def inner(request, *args, **kwargs):
         if not request.user.is_authenticated():
             return redirect_to_login(request.get_full_path())
         return func(request, *args, **kwargs)
     return inner
コード例 #16
0
ファイル: decorators.py プロジェクト: anjala/nodewatcher
    def decorator(view_func):
        def _wrapped_view(request, node, *args, **kwargs):
            if request.method == "POST":
                # In POST request we require node to be the primary key
                node_obj = shortcuts.get_object_or_404(models.Node, pk=node)
            else:
                # In GET request we redirect if node is the primary key
                try:
                    node_obj = models.Node.objects.get(name=node)
                except models.Node.DoesNotExist:
                    # We try the primary key
                    try:
                        node_obj = models.Node.objects.get(pk=node)
                        if not node_obj.is_invalid():
                            # We redirect if node is not invalid/unknown and was accessed by the primary key
                            # This means permalink was probably used so we do not redirect permanently
                            return redirect_helper(view_func, node_obj, False, *args, **kwargs)
                    except models.Node.DoesNotExist:
                        if not be_robust:
                            raise http.Http404
                        try:
                            # Try IP and redirect if found, permanently as we do not use IPs in links anymore
                            node_obj = models.Node.objects.get(ip=node)
                            return redirect_helper(view_func, node_obj, True, *args, **kwargs)
                        except models.Node.DoesNotExist:
                            # We try saved names, this is our last resort
                            node_obj = shortcuts.get_object_or_404(models.NodeNames, name=node).node
                            assert node_obj is not None
                            # As we came here we have some old name otherwise we would already found the node before
                            # So we redirect (permanently) to the current name
                            return redirect_helper(view_func, node_obj, True, *args, **kwargs)
            return view_func(request, node_obj, *args, **kwargs)

        wrapped_view_func = wraps(view_func, assigned=decorators.available_attrs(view_func))(_wrapped_view)
        return wrapped_view_func
コード例 #17
0
ファイル: decorators.py プロジェクト: kumarcv/openstack-nf
def require_perms(view_func, required):
    """ Enforces permission-based access controls.

    :param list required: A tuple of permission names, all of which the request
                          user must possess in order access the decorated view.

    Example usage::

        from horizon.decorators import require_perms


        @require_perms(['foo.admin', 'foo.member'])
        def my_view(request):
            ...

    Raises a :exc:`~horizon.exceptions.NotAuthorized` exception if the
    requirements are not met.
    """
    # We only need to check each permission once for a view, so we'll use a set
    current_perms = getattr(view_func, '_required_perms', set([]))
    view_func._required_perms = current_perms | set(required)

    @functools.wraps(view_func, assigned=available_attrs(view_func))
    def dec(request, *args, **kwargs):
        if request.user.is_authenticated():
            if request.user.has_perms(view_func._required_perms):
                return view_func(request, *args, **kwargs)
        raise NotAuthorized(_("You are not authorized to access %s")
                            % request.path)

    # If we don't have any permissions, just return the original view.
    if required:
        return dec
    else:
        return view_func
コード例 #18
0
ファイル: decorators.py プロジェクト: Seraf/numeter
 def decorator(func):
     @wraps(func, assigned=available_attrs(func))
     def inner(request, *args, **kwargs):
         if not request.user.is_superuser:
             raise Http404("User isn't superuser.")
         return func(request, *args, **kwargs)
     return inner
コード例 #19
0
ファイル: decorators.py プロジェクト: hgw/rhizome.org
 def decorator(view_func):
     def _wrapped_view(request, *args, **kwargs):
         if test_func(request.user):
             return view_func(request, *args, **kwargs)                
         path = urlquote(request.get_full_path())
         return HttpResponseRedirect('%s' % membershp_url)
     return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
コード例 #20
0
ファイル: __init__.py プロジェクト: dahool/CashAppEngine
def flood(view_func, seconds=30, template='flood.html'):
    """Flood protection mechanism
    """
    if not seconds:
        seconds = settings.FLOOD_TIMEOUT
    if not template:
        template = settings.FLOOD_TEMPLATE
    
    def _wrapped_view(request, *args, **kwargs):
        var = "flood-%s.%s" % (view_func.__module__,view_func.__name__)
        last_access = request.session.get(var, None)
        timeout = seconds
        if last_access:
            if request.user.is_authenticated():
                if request.user.is_superuser:
                    return view_func(request, *args, **kwargs)
                if request.user.groups.all():
                    flood_time = None
                    for g in request.user.groups.all():
                        if g.floodsettings.all():
                            if flood_time is None or g.floodsettings.get().timeout < flood_time:
                                flood_time = g.floodsettings.get().timeout
                    if flood_time:
                        timeout = flood_time
            if (last_access + timeout)>int(time.time()):
                path = request.path
                if request.GET:
                    path += "?%s" % urllib.urlencode(request.GET)
                return render_to_response(template, 
                                          {'path': path}, 
                                          context_instance=RequestContext(request))
        request.session[var] = int(time.time())
        return view_func(request, *args, **kwargs)
    return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
コード例 #21
0
 def decorator(view_func):
     @wraps(view_func, assigned=available_attrs(view_func))
     def _wrapped_view(request, *args, **kwargs):
         if not test_func(request, *args, **kwargs):
             return view_func(request, *args, **kwargs)
         return HttpResponseRedirect(url if not callable(url) else url())
     return _wrapped_view
コード例 #22
0
ファイル: auth.py プロジェクト: emory-libraries/OpenEmory
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            try:
                passes = test_func(request.user)
            except TypeError:
                # allow test functions access to view arguments,
                # but only pass if the function fails without them
                passes = test_func(request.user, *args, **kwargs)
                
            if passes:
                # if the test passes, return the view function normally
                return view_func(request, *args, **kwargs)

            elif not request.user.is_authenticated():
                # if the test fails and user is not authenticated
                code = 401
                text = 'Not Authorized'
            else:
                # test fails and user is already authenticated
                code = 403
                text = 'Permission Denied'

            # send a plain-text response to ajax requests
            if request.is_ajax():
                return HttpResponse(text, content_type='text/plain',
                                    status=code)
                
            tpl = get_template('%s.html' % code)
            return HttpResponse(tpl.render(RequestContext(request)),
                                status=code)
        return _wrapped_view
コード例 #23
0
ファイル: decorators.py プロジェクト: Izeni/ParselTONE
def checkable(view_func):
    def _wrapped_view(request, *args, **kwargs):
        # allows checks for the existence of this view to work
        if request.POST.get('check', False):
            return HttpResponse()
        return view_func(request, *args, **kwargs)
    return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
コード例 #24
0
ファイル: permissions.py プロジェクト: AndrewIsaac/mastr-ms
    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            return response

        return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
コード例 #25
0
ファイル: decorators.py プロジェクト: alexarsh/mehameme_dev
 def actual_decorator(view_func):
     @wraps(view_func, assigned=available_attrs(view_func))
     def _wrapped_view(request, *args, **kwargs):
         oauth_url, current_uri, redirect_uri = get_oauth_url(
             request, scope_list,
             extra_params=extra_params)
         try:
             # call get persistent graph and convert the
             # token with correct redirect uri
             get_persistent_graph(request, redirect_uri=current_uri)
             #Note we're not requiring a persistent graph here
             #You should require a persistent graph in the view when you start using this
             return view_func(request, *args, **kwargs)
         except open_facebook_exceptions.OpenFacebookException, e:
             permission_granted = test_permissions(
                 request, scope_list, current_uri)
             if permission_granted:
                 # an error if we already have permissions
                 # shouldn't have been caught
                 # raise to prevent bugs with error mapping to cause issues
                 raise
             else:
                 logger.info(
                     u'requesting access with redirect uri: %s, error was %s',
                     redirect_uri, e)
                 response = response_redirect(oauth_url, canvas=canvas)
                 return response
コード例 #26
0
 def decorator(view_func):
     @wraps(view_func, assigned=available_attrs(view_func))
     def _wrapped_view(request, *args, **kwargs):
         if request.is_ajax():
             return view_func(request, *args, **kwargs)
         return HttpResponseRedirect(redirect_url)
     return _wrapped_view
コード例 #27
0
ファイル: decorators.py プロジェクト: densho/ddr-local
def search_index(func):
    """Update active Elasticsearch index setting; alert if no active index.
    """

    @wraps(func, assigned=available_attrs(func))
    def inner(request, *args, **kwargs):
        s = " "
        d = " "
        try:
            storage_label, docstore_index_exists = set_docstore_index(request)
        except TransportError:
            storage_label = "e"
            docstore_index_exists = "e"
        if storage_label and (storage_label == "e"):
            s = "e"
        elif storage_label:
            s = "s"
        if docstore_index_exists and (docstore_index_exists == "e"):
            d = "e"
        elif docstore_index_exists:
            d = "d"
        key = "".join([s, d])
        error_messages = {
            "sd": (None),  # nothing to see here, move along
            "s ": ("No search index for %s. Search is disabled. Please reindex." % (storage_label)),
            " d": ("No storage devices mounted. Search is disabled."),
            "  ": ("No storage devices mounted and no search index. Search is disabled."),
            "ee": ("Cannot connect to Elasticsearch. Search is disabled."),
        }
        msg = error_messages[key]
        if msg:
            messages.warning(request, msg, extra_tags="bottom")
        return func(request, *args, **kwargs)

    return inner
コード例 #28
0
ファイル: decorators.py プロジェクト: donfanning/gunnery
 def decorator(view_func):
     @wraps(view_func, assigned=available_attrs(view_func))
     def _wrapped_view(request, *args, **kwargs):
         if not id_parameter:
             id_parameter_name = _auto_resolve_parameter_name(kwargs)
         else:
             id_parameter_name = id_parameter
         if not id_parameter_name in kwargs or _has_permissions(request.user, model, kwargs[id_parameter_name]):
             return view_func(request, *args, **kwargs)
         path = request.build_absolute_uri()
         # urlparse chokes on lazy objects in Python 3, force to str
         resolved_login_url = force_str(
             resolve_url(settings.LOGIN_URL))
         # If the login url is the same scheme and net location then just
         # use the path as the "next" url.
         login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
         current_scheme, current_netloc = urlparse(path)[:2]
         if ((not login_scheme or login_scheme == current_scheme) and
             (not login_netloc or login_netloc == current_netloc)):
             path = request.get_full_path()
         messages.error(request, 'Access forbidden')
         from django.contrib.auth.views import redirect_to_login
         return redirect_to_login(
             path, resolved_login_url, REDIRECT_FIELD_NAME)
     return _wrapped_view
コード例 #29
0
def render_DoOutputException(function):
    """
    View decorator that renders DoOutputException's message in django.
    If you want to catch and respond specific Exception types, see `render_specific_exception` decorator.
    If you want to catch and display all Exception types, see `render_all_exceptions` decorator

    >>> @render_DoOutputException
    ... def foobar()
    ... 	raise ValueError("lol.")

    """

    @wraps(function, assigned=available_attrs(function))
    def function_callable(request, *args, **kwargs):
        try:
            response = function(request, *args, **kwargs)
        except DoOutputException as e:
            logger.debug(
                "Exception response, because expected DoOutputException occurred. {err_str}".format(err_str=str(e))
            )
            return HttpResponse(str(e), status=500)
        # end try
        return response

    return function_callable
コード例 #30
0
ファイル: http.py プロジェクト: neogoku/nfv_api
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            # Compute values (if any) for the requested resource.
            def get_last_modified():
                if last_modified_func:
                    dt = last_modified_func(request, *args, **kwargs)
                    if dt:
                        return timegm(dt.utctimetuple())

            res_etag = etag_func(request, *args, **kwargs) if etag_func else None
            res_last_modified = get_last_modified()

            response = get_conditional_response(
                request,
                etag=res_etag,
                last_modified=res_last_modified,
            )

            if response is None:
                response = func(request, *args, **kwargs)

            # Set relevant headers on the response if they don't already exist.
            if res_last_modified and not response.has_header('Last-Modified'):
                response['Last-Modified'] = http_date(res_last_modified)
            if res_etag and not response.has_header('ETag'):
                response['ETag'] = quote_etag(res_etag)

            return response

        return inner
コード例 #31
0
def gzip_page_ajax(func):
    """
    Smarter version of django's gzip_page:
    - If settings.DEBUG not set, will always gzip
    - If settings.DEBUG set, will gzip only if request is an ajax request
    This allows you to use django-debug-toolbar in DEBUG mode (if you gzip a response then the debug toolbar middleware won't run)
    """
    gzipped_func = gzip_page(func)

    if not settings.DEBUG:
        return gzipped_func

    @wraps(func, assigned=available_attrs(func))
    def conditional_gzip_func(request, *args, **kwargs):
        if request.is_ajax():
            return gzipped_func(request, *args, **kwargs)
        return func(request, *args, **kwargs)

    return conditional_gzip_func
コード例 #32
0
    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:
                logger.debug(
                    "Got new token from session %s. Returning to view.",
                    request.session.session_key[:5])
                return view_func(request, token, *args, **kwargs)

            # prompt the user to login for a new token
            logger.debug("Redirecting session %s to SSO.",
                         request.session.session_key[:5])
            from esi.views import sso_redirect
            return sso_redirect(request, scopes=scopes)

        return _wrapped_view
コード例 #33
0
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            charge = kwargs.get('charge', None)
            if charge is not None:
                obj = get_object_or_404(Charge, processor_key=charge)
            else:
                obj = kwargs.get('organization', None)
            redirect_url = fail_provider_weak(request, organization=obj,
                    roledescription=roledescription)
            if redirect_url:
                return redirect_or_denied(request, redirect_url,
                    redirect_field_name=redirect_field_name,
                    descr=_("%(auth)s is neither a manager of"\
" %(organization)s nor a manager of one of %(organization)s providers.") % {
    'auth': request.user,
    'organization': kwargs.get('charge', kwargs.get('organization', None))})
            return view_func(request, *args, **kwargs)
        return _wrapped_view
コード例 #34
0
ファイル: views.py プロジェクト: brunousml/inbox
def with_deposit(func):
    @wraps(func, assigned=available_attrs(func))
    def wrapper(request, deposit_id, *args, **kwargs):

        deposits = frontdesk.models.Deposit.objects.order_by('-created')[:999]
        if deposit_id:
            detailed_deposit = get_object_or_404(
                frontdesk.models.Deposit, pk=deposit_id)
        else:
            detailed_deposit = frontdesk.models.Deposit.objects.order_by(
                '-created').first()

        context = {'deposits': deposits, 'detailed_deposit': detailed_deposit}

        kwargs['context'] = context

        return func(request, deposit_id, *args, **kwargs)

    return wrapper
コード例 #35
0
ファイル: decorator.py プロジェクト: papayazm/zulip
 def decorator(view_func):
     # type: (Callable[..., HttpResponse]) -> Callable[..., HttpResponse]
     @wraps(view_func, assigned=available_attrs(view_func))
     def _wrapped_view(request, *args, **kwargs):
         # type: (HttpRequest, *Any, **Any) -> HttpResponse
         if test_func(request):
             return view_func(request, *args, **kwargs)
         path = request.build_absolute_uri()
         resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
         # If the login url is the same scheme and net location then just
         # use the path as the "next" url.
         login_scheme, login_netloc = urllib.parse.urlparse(resolved_login_url)[:2]
         current_scheme, current_netloc = urllib.parse.urlparse(path)[:2]
         if ((not login_scheme or login_scheme == current_scheme) and
                 (not login_netloc or login_netloc == current_netloc)):
             path = request.get_full_path()
         return redirect_to_login(
             path, resolved_login_url, redirect_field_name)
     return _wrapped_view
コード例 #36
0
def xframe_options_deny(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'DENY' as long as the response doesn't already have that
    header set.

    e.g.

    @xframe_options_deny
    def some_view(request):
        ...
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options') is None:
            resp['X-Frame-Options'] = 'DENY'
        return resp

    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
コード例 #37
0
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def wrapper(user, *args, **kwargs):
            if not user.is_authenticated:
                return False

            permissions = _django_permissions_by_action[action]

            if not user.has_perms(permissions):
                # Fail fast if the user does not have permissions
                # in Django to perform the action.
                return False

            permissions_enabled = get_cms_setting('PERMISSION')

            if not user.is_superuser and permissions_enabled:
                return func(user, *args, **kwargs)
            return True
        return wrapper
コード例 #38
0
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)  # authenticated
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme)
                    and (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(path, resolved_login_url,
                                     redirect_field_name)

        return _wrapped_view
コード例 #39
0
ファイル: decorators.py プロジェクト: mjhshin/repunch_web
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request):
                if SESSION.get_store(request.session) and\
                    SESSION.get_store(request.session).active:
                    # may not want to import parse.session here due
                    # to cyclic imports
                    timezone.activate(SESSION.get_store_timezone(\
                        request.session))
                    try:
                        return view_func(request, *args, **kwargs)
                    except KeyError:
                        return logout(request, "manage_login")
                else:
                    return logout(request, "manage_login")

            # if http_response is provided and content_type is json
            # and request.is_ajax then this request if from comet.js
            if request.is_ajax() and http_response and\
                content_type == "application/json":
                # no need to update session- if it got here then the session is empty
                #request.session.clear()
                #request.session.update(SessionStore(request.session.session_key))
                return HttpResponse(json.dumps(http_response),
                                    content_type=content_type)

            path = request.build_absolute_uri()
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse.urlparse(
                login_url or settings.LOGIN_URL)[:2]
            current_scheme, current_netloc = urlparse.urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme)
                    and (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            # no need to update session- if it got here then the session is empty
            #request.session.clear()
            #request.session.update(SessionStore(request.session.session_key))
            return redirect_to_login(path, login_url, redirect_field_name)

        return _wrapped_view
コード例 #40
0
ファイル: security.py プロジェクト: weblate/eventoL
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            activity_id = kwargs['activity_id']
            user = request.user
            activity = get_object_or_404(Activity, pk=activity_id)
            event_slug = kwargs['event_slug']

            if any([
                    activity.status == "2",  # Accepted
                    not settings.PRIVATE_ACTIVITIES,
                    activity.owner.user == user,
                    user.is_authenticated() and is_reviewer(user, event_slug=event_slug)
            ]):
                return view_func(request, *args, **kwargs)
            else:
                raise PermissionDenied("Only organizers and collaborators are authorized "
                                       "to access the activities list.")
        return _wrapped_view
コード例 #41
0
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            '''
            Wrapped function for decorator
            '''
            if request.user is None:
                url = request.build_absolute_uri(GlobalConfig.LOGIN_URL.get())
                if GlobalConfig.REDIRECT_TO_HTTPS.getBool() is True:
                    url = url.replace('http://', 'https://')
                logger.debug('No user found, redirecting to {0}'.format(url))
                return HttpResponseRedirect(url)

            if admin is True or admin == 'admin':
                if request.user.isStaff() is False or (admin == 'admin' and request.user.is_admin is False):
                    return HttpResponseForbidden(_('Forbidden'))

            return view_func(request, *args, **kwargs)
        return _wrapped_view
コード例 #42
0
def require_trade_pwd(view_func):
    '''
    装饰器, 进行交易密码校验
    '''
    @wraps(view_func, assigned=available_attrs(view_func))
    def _wrapped_view(self, request, *args, **kwargs):
        try:
            # logging.getLogger('django').error('trade request POST %s header %s'%(request.POST, request.META))
            no_need_trade_pwd = False
            #为了获取验证码
            if request.path == reverse('deposit-new') and \
                    (len(request.POST.get('card_no', '')) != 10 or
                     request.POST.get('mode') == 'vcode_for_qpay'):
                no_need_trade_pwd = True
            #为了绑卡进行的绑卡充值
            if _is_just_bind_card(request):
                no_need_trade_pwd = True
            if not _is_version_satisfied(request):
                no_need_trade_pwd = True
            # logging.getLogger('django').error('trade request no_need_trade_pwd %s'%no_need_trade_pwd)
            if no_need_trade_pwd:
                return view_func(self, request, *args, **kwargs)

            # logging.getLogger('django').error('trade request user %s pwd %s %s'%(request.user.id, request.POST.get('trade_pwd'), len(request.POST.get('trade_pwd'))))
            # check_result = trade_pwd_check(request.user.id, request.POST.get('trade_pwd', ''))
            check_result = trade_pwd_check(request.user.id,
                                           self.params.get('trade_pwd', ''))
            if check_result.get('ret_code') == 0:
                return view_func(self, request, *args, **kwargs)
            else:
                return HttpResponse(json.dumps(check_result),
                                    content_type="application/json")
        except ValueError:
            logger.exception('trade request POST %s header %s' %
                             (request.POST, request.META))
            return HttpResponse(json.dumps({
                'ret_code': 40002,
                'message': '交易密码错误'
            }),
                                content_type="application/json")

    return _wrapped_view
コード例 #43
0
    def __call__(self, function, *args, **kwargs):
        """
        Decorator used to test if a user has rights to access an instance
        """

        # Pass function attributes to the wrapper
        @wraps(function, assigned=available_attrs(function))
        def _wrapped_view(request, *args, **kwargs):

            # Each wrapped view must take an alphanumeric uid as parameter.
            uid = kwargs.get('uid')

            # The user is set in the request.
            user = request.user

            # Fetches the object that will be checked for permissions.
            instance = self.type.objects.get_all(uid=uid).first()
            #instance = instance or self.type.objects.show_deleted(uid=uid).first()

            # Check for access to the object.
            allow_access = auth.check_obj_access(
                user=user,
                instance=instance,
                request=request,
                access=self.access,
                login_required=self.login_required,
                role=self.role)
            # Access check did not pass, redirect.
            if not allow_access:

                # If there is a redirect url build with the uid.
                if self.url and uid:
                    target = reverse(self.url, kwargs=dict(uid=uid))
                else:
                    target = reverse('project_list')

                return redirect(target)

            # Return the wrapped function.
            return function(request, *args, **kwargs)

        return _wrapped_view
コード例 #44
0
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            # ensure session installed in database
            if not request.session.exists(request.session.session_key):
                request.session.create()

            # clean up callback redirect, pass token if new requested
            try:
                model = CallbackRedirect.objects.get(
                    session_key=request.session.session_key)
                tokens = AccessToken.objects.filter(pk=model.token.pk)
                model.delete()
                if new:
                    return view_func(request, tokens, *args, **kwargs)
            except (CallbackRedirect.DoesNotExist, AttributeError):
                pass

            if not new:
                # ensure user logged in to check existing tokens
                if not request.user.is_authenticated:
                    from django.contrib.auth.views import redirect_to_login
                    return redirect_to_login(request.get_full_path())

                # collect tokens in db, check if still valid, return if any
                for t in AccessToken.objects.filter(
                        user__pk=request.user.pk).filter(
                            scopes__name__in=scopes):
                    try:
                        t.token
                    except TokenError:
                        t.delete()
                tokens = AccessToken.objects.filter(
                    user__pk=request.user.pk).filter(scopes__name__in=scopes)
                if tokens.exists():
                    return view_func(request, tokens, *args, **kwargs)

            # trigger creation of new token via sso
            from eve_sso.views import sso_redirect
            return sso_redirect(request, scopes=scopes)

        return _wrapped_view
コード例 #45
0
def has_change_permissions(func):
    """
    Check if the user has the required permission to execute an action
    Inspired in user_passes_test from django.contrib.auth.decorators
    """
    @wraps(func, assigned=available_attrs(func))
    def decorator(modeladmin, request, queryset):
        can_change = True
        for obj in queryset:
            if not obj.has_permission(request.user, 'change'):
                can_change = False
                break
        if request.user.is_superuser or can_change:
            return func(modeladmin, request, queryset)
        else:
            msg = "You don't have enought rights to perform this action!"
            modeladmin.message_user(request, msg, messages.ERROR)
            return None  #raise PermissionDenied()

    return decorator
コード例 #46
0
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *view_args, **view_kwargs):
            cache_enabled = request.GET.get('cache_enabled', True)
            if cache_enabled and hasattr(
                    settings,
                    'QR_CODE_CACHE_ALIAS') and settings.QR_CODE_CACHE_ALIAS:
                # We found a cache alias for storing the generate qr code and cache is enabled, use it to cache the
                # page.
                timeout = settings.CACHES[
                    settings.QR_CODE_CACHE_ALIAS]['TIMEOUT']
                response = cache_page(
                    timeout, cache=settings.QR_CODE_CACHE_ALIAS)(view_func)(
                        request, *view_args, **view_kwargs)
            else:
                # No cache alias for storing the generated qr code, call the view as is.
                response = (view_func)(request, *view_args, **view_kwargs)
            return response

        return _wrapped_view
コード例 #47
0
def handle_exception(view_func):
    """Performs handling and serializing exception.
    """

    @functools.wraps(view_func, assigned=available_attrs(view_func))
    def dec(request, *args, **kwargs):

        try:
            response = view_func(request, *args, **kwargs)

        except Exception as e:
            if settings.DEBUG:
                raise e
            response = JSONResponse({'error': 'Unexpected Error. '
                                     'Please contact Administrator.'})
            response.status_code = 500

        return response

    return dec
コード例 #48
0
def catch_glance_exception(func):
    """
    The glance client sometimes throws ``Exception`` classed exceptions for
    HTTP communication issues. Catch those, and rethrow them as
    ``glance_client.ClientConnectionErrors`` so that we can do something
    useful with them.
    """
    # TODO(johnp): Remove this once Bug 952618 is fixed in the glance client.
    @functools.wraps(func, assigned=available_attrs(func))
    def inner_func(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as exc:
            exc_message = str(exc)
            if ('Unknown error occurred' in exc_message
                    or 'Internal Server error' in exc_message):
                raise glance_exception.ClientConnectionError(exc_message)
            raise

    return inner_func
コード例 #49
0
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            redirect_url = login_url or settings.LOGIN_URL
            if is_authenticated(request):
                redirect_url = fail_active(request)
                if not redirect_url:
                    return view_func(request, *args, **kwargs)
                # User is logged in but her email has not been verified yet.
                http_accepts = get_accept_list(request)
                if 'text/html' in http_accepts:
                    messages.info(request, _(
                        "You should now secure and activate your account following the instructions"\
" we just emailed you. Thank you."))
                auth_logout(request)
            return redirect_or_denied(request,
                                      redirect_url,
                                      redirect_field_name=redirect_field_name)

        return _wrapped_view
コード例 #50
0
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                # Raise our warning.
                warning.send(sender=require_http_methods,
                             flag=WRONG_METHOD,
                             message=u'%s not allowed' % request.method,
                             values=[request_method_list])
                logger.warning('Method Not Allowed (%s): %s',
                               request.method,
                               request.path,
                               extra={
                                   'status_code': 405,
                                   'request': request
                               })
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)

        return inner
コード例 #51
0
ファイル: decorator.py プロジェクト: zippyy/zulip
    def decorator(view_func: ViewFuncT) -> ViewFuncT:
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request: HttpRequest, *args: Any,
                          **kwargs: Any) -> HttpResponse:
            if test_func(request):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urllib.parse.urlparse(
                resolved_login_url)[:2]
            current_scheme, current_netloc = urllib.parse.urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme)
                    and (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            return redirect_to_login(path, resolved_login_url,
                                     redirect_field_name)

        return _wrapped_view  # type: ignore # https://github.com/python/mypy/issues/1927
コード例 #52
0
def user_can_change_page(func):
    @wraps(func, assigned=available_attrs(func))
    def wrapper(user, page, site=None):
        can_change = func(user, page, site=site)

        if can_change:
            active_request = get_active_moderation_request(
                page, get_request_language())

            # If there is an active moderation request, the only user
            # who can edit the content is the original content author after
            # his moderation request has been rejected by any of the moderators.
            # The reason for this that content author should be able to
            # resubmit the changes for another review as a part of the same
            # moderation request.
            if active_request and not active_request.user_can_resubmit(user):
                return False
        return can_change

    return wrapper
コード例 #53
0
    def wrap(fun):
        @wraps(fun, assigned=available_attrs(fun))
        def inner(task_id, *args, **kwargs):
            try:
                return fun(task_id, *args, **kwargs)
            except Exception as e:
                logger.exception(e)
                logger.error('Mgmt Task %s failed', task_id)
                raise e
            finally:
                if update_user_tasks:
                    try:
                        obj = get_vms_object(kwargs)
                    except ObjectDoesNotExist:
                        # noinspection PyProtectedMember
                        _UserTasksModel._tasks_del(task_id)
                    else:
                        obj.tasks_del(task_id)

        return inner
コード例 #54
0
    def decorator(view_fn):
        def _wrapped_view(request, *args, **kwargs):
            if redirect_func(request.user):
                # We must call reverse at the view level, else the threadlocal
                # locale prefixing doesn't take effect.
                redirect_url = redirect_url_func() or reverse('account_login')

                # Redirect back here afterwards?
                if redirect_field:
                    path = urlquote(request.get_full_path())
                    redirect_url = '%s?%s=%s' % (
                        redirect_url, redirect_field, path)

                return HttpResponseRedirect(redirect_url)

            if deny_func and deny_func(request.user):
                return HttpResponseForbidden()

            return view_fn(request, *args, **kwargs)
        return wraps(view_fn, assigned=available_attrs(view_fn))(_wrapped_view)
コード例 #55
0
ファイル: decorators.py プロジェクト: szuprefix/py-xyz-wechat
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            context = get_weixin_login_context(request)
            if context is not None:
                code = request.GET.get("code")
                user = auth.authenticate(code=code, context=context)
                if user and not isinstance(user, AnonymousUser):
                    setattr(user, 'login_type', '%s%s' % (getattr(user, 'login_type', None), context.get('login_type')))
                    auth.login(request, user)
                    return view_func(request, *args, **kwargs)
                else:
                    return HttpResponseForbidden()
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            api = helper.MpApi()
            login_url = api.OAuthUrl(request.build_absolute_uri(request.META.get('TENANT_REQUEST_URI')))
            return HttpResponseRedirect(login_url)

        return _wrapped_view
コード例 #56
0
def require_valid_user(view_func, invalid_user_message=None):
    if invalid_user_message is None:
        invalid_user_message = "The user you've selected appears to be invalid. \
         Please return to <a href='/questionnaire/'>the index</a> and select a different user."

    @wraps(view_func, assigned=available_attrs(view_func))
    def _wrapped(request, *args, **kwargs):
        if request.COOKIES.get('userId') is not None:
            try:
                (patientId, serverId) = get_login_info(request)
                smart = utils.getFhirClient(serverId)
                patient.Patient.read(patientId, smart.server)
            except Exception:
                context = {'error_text': invalid_user_message}
                return render(request, 'error.html', context)
            return view_func(request, *args, **kwargs)
        else:
            return redirect("questionnaire.views.index")

    return _wrapped
コード例 #57
0
def xframe_allow_whitelisted(view_func):
    """
    Modifies a view function so that its response has the X-Frame-Options HTTP header
    set to 'DENY' if the request HTTP referrer is not from a whitelisted hostname.
    """

    def wrapped_view(request, *args, **kwargs):
        """ Modify the response with the correct X-Frame-Options. """
        resp = view_func(request, *args, **kwargs)
        x_frame_option = 'DENY'
        if settings.FEATURES['ENABLE_THIRD_PARTY_AUTH']:
            referer = request.META.get('HTTP_REFERER')
            if referer is not None:
                parsed_url = urlparse(referer)
                hostname = parsed_url.hostname
                if LTIProviderConfig.objects.current_set().filter(lti_hostname=hostname, enabled=True).exists():
                    x_frame_option = 'ALLOW'
        resp['X-Frame-Options'] = x_frame_option
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
コード例 #58
0
 def decorator(view_func):
     @wraps(view_func, assigned=available_attrs(view_func))
     def _wrapped_view(request, *args, **kwargs):
         res = view_func(request, *args, **kwargs)
         log = Log()
         log.name        = request.GET.get('user')
         log.ipv4        = request.META['REMOTE_ADDR']
         log.uri         = request.META['PATH_INFO']
         log.get_args    = request.GET
         log.post_args   = request.POST
         res._container = simplejson.loads(res._container)
         if res._container.has_key('res'):
             log.res = res._container['res']
         if res._container.has_key('error'):
             log.error = res._container['error']
         if res._container.has_key('data'):
             log.error = res._container['data']
         log.save()
         return res
     return _wrapped_view
コード例 #59
0
def never_cache(view_func):
    """Adds HTTP headers to the response to block caching

    Decorator that adds headers to a response so that it will
    never be cached.

    Expanded version of django.views.decorators.cache.never_cache that
    adds additional headers that follow the recommendations from:
    http://securityevaluators.com/knowledge/case_studies/caching/
    """
    @wraps(view_func, assigned=available_attrs(view_func))
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        if response.status_code not in (301, 302):
            response['Cache-Control'] = 'no-cache,no-store'
            response['Pragma'] = 'no-cache'
            response['Expires'] = 'Tue, 01 Jan 1980 1:00:00 GMT'
        return response

    return _wrapped_view_func
コード例 #60
0
 def actual_decorator(view_func):
     @wraps(view_func, assigned=available_attrs(view_func))
     def _wrapped_view(request, *args, **kwargs):
         oauth_url, redirect_uri = get_oauth_url(request,
                                                 scope_list,
                                                 extra_params=extra_params)
         try:
             #call get persistent graph and convert the token with correct redirect uri
             get_persistent_graph(request, redirect_uri=redirect_uri)
             return view_func(request, *args, **kwargs)
         except open_facebook_exceptions.OpenFacebookException, e:
             if test_permissions(request, scope_list, redirect_uri):
                 #an error if we already have permissions shouldn't have been caught
                 #raise to prevent bugs with error mapping to cause issues
                 raise
             else:
                 logger.info('requesting access with redirect uri: %s',
                             redirect_uri)
                 response = HttpResponseRedirect(oauth_url)
                 return response