def class_superuser_only(cls): if not isinstance(cls, type) or not issubclass(cls, View): raise ImproperlyConfigured('{} class must be subclass of View class' .format(cls.__name__)) check_login = method_decorator(login_required) check_is_superuser = method_decorator(superuser_only) cls.dispatch = check_login(check_is_superuser(cls.dispatch)) return cls
def decorator(cls): if (not isinstance(cls, type) or not issubclass(cls, View)): raise ImproperlyConfigured( "require_authenticated_permission must be applied to subclasses of View class.") check_auth = method_decorator(login_required) check_perm = method_decorator(permission_required(permission, raise_exception=True)) cls.dispatch = check_auth(check_perm(cls.dispatch)) return cls
def wrapper(cls): if not isinstance(cls, type) or not issubclass(cls, View): raise ImproperlyConfigured('{} class must be subclass of View class' .format(cls.__name__)) check_login = method_decorator(login_required) check_perms = method_decorator(permission_required(perms, raise_exception=True)) cls.dispatch = check_login(check_perms(cls.dispatch)) return cls
def __new__(cls, name, parents, attrs): post = attrs.pop('post') klass = super(APIMeta, cls).__new__(cls, name, parents, attrs) # order matters post = decorators.log_args(logger)(post) post = method_decorator(decorators.request_ip)(post) post = method_decorator(decorators.clean_post_args(klass.PostForm))(post) post = decorators.exception_response(klass.exc_response)(post) klass.post = post return klass
def cache_page(cls=None, **cache_kwargs): """ Apply the ``cache_page`` decorator to all the handlers in a class-based view that delegate to the ``dispatch`` method. Optional arguments ``timeout`` -- Cache timeout, in seconds.`` Usage (without timeout parameter): @cache_page class MyView (TemplateView): ... Usage (with 5 minute timeout): @cache_page(60*5) class MyView(TemplateView): ... Based on login required decorator: http://djangosnippets.org/snippets/2495/ """ if cls is not None: # Check that the View class is a class-based view. This can either be # done by checking inheritance from django.views.generic.View, or by # checking that the ViewClass has a ``dispatch`` method. if not hasattr(cls, 'dispatch'): raise TypeError(('View class is not valid: %r. Class-based views ' 'must have a dispatch method.') % cls) timeout = None if cache_kwargs.has_key('timeout'): timeout = cache_kwargs.pop('timeout') original = cls.dispatch if timeout: modified = method_decorator(cache_page(timeout, **cache_kwargs))(original) else: modified = method_decorator(cache_page(**cache_kwargs))(original) cls.dispatch = modified return cls else: # If ViewClass is None, then this was applied as a decorator with # parameters. An inner decorator will be used to capture the ViewClass, # and return the actual decorator method. def inner_decorator(inner_cls): return cache_page(inner_cls, **cache_kwargs) return inner_decorator
def class_access_required(cls): """Decorator for View subclasses to restrict by business unit. Class must declare a classmethod `get_business_unit` that returns the BusinessUnit object that applies to the query in question. Args: cls: Class to decorate. Returns: Decorated class. Raises: 403 Pemission Denied if current user does not have access. 404 if requested group doesn't exist. """ def access_required(function): def decorator(*args, **kwargs): # The request object is the first arg to a view request = args[0] user = request.user business_unit = cls.get_business_unit(**kwargs) if has_access(user, business_unit): return function(*args, **kwargs) else: raise PermissionDenied() return decorator access_decorator = method_decorator(access_required) cls.dispatch = access_decorator(cls.dispatch) return cls
def ClassDecorator(decorator, cls=None, *decorator_args, **decorator_kwargs): """ Apply the ``decorator`` to all the handlers in a class-based view that delegate to the ``dispatch`` method. """ if cls is not None: # Check that the View class is a class-based view. This can either be # done by checking inheritance from django.views.generic.View, or by # checking that the ViewClass has a ``dispatch`` method. if not hasattr(cls, 'dispatch'): raise TypeError(('View class is not valid: %r. Class-based views ' 'must have a dispatch method.') % cls) original = cls.dispatch modified = method_decorator(decorator(*decorator_args, **decorator_kwargs))(original) cls.dispatch = modified return cls else: # If ViewClass is None, then this was applied as a decorator with # parameters. An inner decorator will be used to capture the ViewClass, # and return the actual decorator method. def inner_decorator(inner_cls): return ClassDecorator(decorator, cls=inner_cls, *decorator_args, **decorator_kwargs) return inner_decorator
def class_login_required(cls): if not isinstance(cls, type) or not issubclass(cls, View): raise ImproperlyConfigured( 'class_login_required must be applied to subclasses of View class') decorator = method_decorator(login_required) cls.dispatch = decorator(cls.dispatch) return cls
def test_descriptors(self): def original_dec(wrapped): def _wrapped(arg): return wrapped(arg) return _wrapped method_dec = method_decorator(original_dec) class bound_wrapper(object): def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __call__(self, arg): return self.wrapped(arg) def __get__(self, instance, owner): return self class descriptor_wrapper(object): def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __get__(self, instance, owner): return bound_wrapper(self.wrapped.__get__(instance, owner)) class Test(object): @method_dec @descriptor_wrapper def method(self, arg): return arg self.assertEqual(Test().method(1), 1)
def _decorate(view_class): view_class.dispatch = method_decorator( decorator, *args, **kwargs )(view_class.dispatch) return view_class
def _dec(cls): assert (isinstance(cls, type) and issubclass(cls, View)), ( "Only subclasses of django.views.generic.View may use this decorator." ) _method_decorator = method_decorator(decorator) cls.dispatch = _method_decorator(cls.dispatch) return cls
def view_decorator(orig_dec): """ Convert the provided decorator to one that can be applied to a view class (ie. automatically decorates dispatch) """ # We're going to be applying a regular decorator to a method, so the first # step is to convert it to a method decorator. method_dec = method_decorator(orig_dec) # This is the decorator we're actually going to return. Since we're # returning a class decorator, it takes a single argument, the class # that it's decorating. It therefore returns this as well. def dec(cls): # We're about to change what cls.dispatch refers to, so we need to # keep a reference to the original dispatch around so that we can # call it later. orig_dispatch = cls.dispatch def _dispatch(self, *args, **kwargs): # Right - decorate the original dispatch method using our new, # method-ised version of the decorator we were passed in to start # with decorated = method_dec(orig_dispatch) # Finally, we can call the decorated dispatch() method. return decorated(self, *args, **kwargs) # Replace the original dispatch with our new dispatch function. We # kept a reference to the old dispatch method earlier, in a closure. cls.dispatch = _dispatch return cls return dec
def cache_factory(key_tpl, timeout): u""" Возвращает декоратор кэширования. @type key_tpl: unicode @param key_tpl: Шаблон ключа для размещения в кэше. @type timeout: integer @param timeout: Время кэширования в секундах. @rtype: callable @return: Декоратор кэширования. """ def decorator(func): @wraps(func) def wrapped(*args, **kwargs): def _params_to_hash(*a, **k): return reduce(lambda x, y: x + y, map(unicode, list(a) + k.values())) key_raw = key_tpl % _params_to_hash(*args, **kwargs) key = sha_constructor(key_raw.encode('utf-8')).hexdigest() value = cache.get(key) if value is None: value = func(*args, **kwargs) cache.set(key, value, timeout) return value return wrapped decorator = method_decorator(decorator) return decorator
def loginRequiredView(View): """ Check if the user is connected Decorator for class-based views """ View.dispatch = method_decorator(loginRequired)(View.dispatch) return View
def __new__(cls, *args, **kwargs): """Register the new handler for future models serializations. Apply decorators to methods. """ new_class = super(SpineAPIMeta, cls).__new__(cls, *args, **kwargs) #register regist(new_class) #inject get_api_url method if new_class.model: new_class.model.get_api_url = classmethod(model_get_api_url) new_class.model.api_url = property(model_api_url) #decorate for method, decorators in new_class.method_decorators.iteritems(): class_method = getattr(new_class, method, None) if class_method: for decorator in decorators: class_method = method_decorator(decorator)(class_method) setattr(new_class, method, class_method) return new_class
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
def ForbiddenUser(cls=None, **login_args): """ Apply the ``auth_required`` decorator to all the handlers in a class-based view that delegate to the ``dispatch`` method. Usage: @LoginRequired class MyListView (ListView): ... """ if cls is not None: # Check that the View class is a class-based view. This can either be # done by checking inheritance from django.views.generic.View, or by # checking that the ViewClass has a ``dispatch`` method. if not hasattr(cls, 'dispatch'): raise TypeError(('View class is not valid: %r. Class-based views ' 'must have a dispatch method.') % cls) original = cls.dispatch modified = method_decorator(forbidden_user(**login_args))(original) cls.dispatch = modified return cls else: # If ViewClass is None, then this was applied as a decorator with # parameters. An inner decorator will be used to capture the ViewClass, # and return the actual decorator method. def inner_decorator(inner_cls): return ForbiddenUser(inner_cls, **login_args) return inner_decorator
def make_view_mixin(class_name, decorator): mixin = type(class_name, (object, ), {}) def dispatch(self, *args, **kwargs): return super(mixin, self).dispatch(*args, **kwargs) mixin.dispatch = method_decorator(decorator)(dispatch) return mixin
def class_based_decorator(ClassBasedView): def view_func(function): def wrap(request, *args, **kwargs): request = validation_function(request, model_list) return function(request, *args, **kwargs) return wrap ClassBasedView.post = method_decorator(view_func)(ClassBasedView.post) return ClassBasedView
def klass_decorator(klass, name, resource): if resource is None: resource = "%s.%s" % (klass.__module__, klass.__name__) klass.dispatch = method_decorator( acl_register_view(name, resource) )(klass.dispatch) return klass
def require_AJAX(view): def ajaxOnly(function): def wrap(request, *args, **kwargs): if not request.is_ajax(): return HttpResponseForbidden() return function(request, *args, **kwargs) return wrap view.dispatch = method_decorator(ajaxOnly)(view.dispatch) return view
def decorator(original_class): if not issubclass(original_class, View): raise TypeError('%(class)s is not a view class' % { 'class': original_class }) original_class.dispatch = method_decorator( permission_required(*args, **kwargs) )(original_class.dispatch) return original_class
def cache_view(cls=None, **cache_kwargs): if cls is not None: timeout = cache_kwargs.pop('timeout', None) original = cls.dispatch args = (timeout,) if timeout else tuple() cls.dispatch = method_decorator(cache_page(*args, **cache_kwargs))(original) return cls else: def _decorator(inner_cls): return cache_view(inner_cls, **cache_kwargs) return _decorator
def class_based_decorator(ClassBasedView): def view_func(function): def wrap(request, *args, **kwargs): for func in function_list: try: request = func(request, api_version) except InvalidParameterException: raise return function(request, *args, **kwargs) return wrap ClassBasedView.post = method_decorator(view_func)(ClassBasedView.post) return ClassBasedView
def requires_login(obj): """ Decorator for views that ensures the user is currently logged in. Works both on class-based views and functions. """ if isfunction(obj): # func decorator f = obj return login_required(function=f) elif isclass(obj): # class decorator cls = obj decorator = method_decorator(login_required) cls.dispatch = decorator(cls.dispatch) return cls
def _inner(view_fn): if isinstance(view_fn, type): # Django class-based views if issubclass(view_fn, View): view_fn = method_decorator(_inner, 'dispatch')(view_fn) # HQ report classes if issubclass(view_fn, GenericReportView): CONDITIONALLY_LOCATION_SAFE_HQ_REPORTS[view_fn.slug] = conditional_function else: view_fn._conditionally_location_safe_function = conditional_function return view_fn
def _dispatch(self, request, *args, **kwargs): """ Grab relevant decorators from the request, convert them into method decorators using django's ``method_decorator`` functionality. Finally apply the decorators in reverse order (decorators are applied inside out) to the new dispatch view """ new_dispatch = orig_dispatch if request.pybb_permission_decorators is not None: for dec in reversed( request.pybb_permission_decorators.decorators): new_dispatch = method_decorator(dec())(new_dispatch) return new_dispatch(self, request, *args, **kwargs)
def _wrapped_view(self, request, *args, **kwargs): view_model = self.get_model() cache_latest = cache_last_modified(lambda x: view_model.latest_updated()) cbv_cache_latest = method_decorator(cache_latest) # The first decorator forces browser's cache revalidation. # The second one allows browser's cache revalidation. @method_decorator(never_cache) @cbv_cache_latest def decorated(self, request, *args, **kwargs): return view_func(self, request, *args, **kwargs) return decorated(self, request, *args, **kwargs)
def patched_decorator(dec, obj): """ Takes an argument-less decorator and an object which can be either a function or a class based view. If `obj` is a function, returns the function decorated with `dec`. If `obj` is a CBV, returns the class with its dispatch method decorated with `dec`. """ if isfunction(obj): return dec(obj) else: cls = obj cls.dispatch = method_decorator(dec)(cls.dispatch) return cls
def exception_logging(View): def exception_logger(dispatch_function): def wrapper(request, *args, **kwargs): try: return dispatch_function(request, *args, **kwargs) except Exception as e: error_log = ErrorLog() error_log.stacktrace = traceback.format_exc().replace('\n', '<br/>') error_log.message = e.message error_log.error_url = request.path_info error_log.save() raise e return wrapper View.dispatch = method_decorator(exception_logger)(View.dispatch) return View
from django.utils.encoding import force_text from django.utils.six.moves.urllib.parse import unquote from django.utils.translation import ugettext_lazy as _ from django.views.decorators.http import require_POST from ..api import add_content from ..conf import settings from ..models import Article, Title from .forms import ArticleCreateForm, ArticleForm try: from django.contrib.admin.utils import get_deleted_objects except ImportError: from django.contrib.admin.util import get_deleted_objects require_POST = method_decorator(require_POST) _thread_locals = local() class ArticleAdmin(PlaceholderAdminMixin, admin.ModelAdmin): change_list_template = 'admin/cms_articles/article_changelist.html' search_fields = ('=id', 'title_set__slug', 'title_set__title', 'title_set__description') list_display = ('__str__', 'order_date', 'preview_link') + tuple( 'lang_{}'.format(lang) for lang in get_language_list()) list_filter = [ 'tree', 'attributes', 'categories', 'template', 'changed_by' ] date_hierarchy = 'order_date' filter_horizontal = ['attributes', 'categories']
class ShopcarView(APIView): method_decorator(login_required) def get(self, request, format=None): """获取某个用户的购物车列表""" isMble = dmb.process_request(request) ruleitems = CartItem.objects.filter(user=request.user) content = {} content['mediaroot'] = settings.MEDIA_URL content['ruleitems'] = ruleitems if isMble: return render(request, 'shopcar/m_lists.html', content) else: return render(request, 'shopcar/lists.html', content) @method_decorator(csrf_exempt) def post(self, request): """ 创建、删除 创建需要参数:method:create, ruleid, num """ result = {} if request.method == 'POST': user = request.user if user.is_anonymous(): result['status'] = 'ERROR' result['msg'] = _('login required....') else: if 'method' in request.POST: method = request.POST['method'] ruleid = request.POST['ruleid'] try: rule = AdaptorRule.objects.get(id=ruleid) if method == 'delete': caritem = CartItem.objects.get(rule=rule, user=user) caritem.delete() result['status'] = 'ok' result['msg'] = _( 'Delete successfully....') #'删除成功...' else: # create quantity = request.POST['num'] car, create = CartItem.objects.get_or_create( rule=rule, user=user) car.quantity += int(quantity) car.save() result['status'] = 'ok' result['msg'] = _( 'Add successfully....') # '添加成功...' except AdaptorRule.DoesNotExist: result['status'] = 'error' result['msg'] = _('Not found....') #'未找到商品....' else: result['status'] = 'error' result['msg'] = _('Need method in post...') else: result['status'] = 'error' result['msg'] = _('Method error..') return HttpResponse(json.dumps(result), content_type='application/json')
def sensitive_post_parameters_m(*args): return method_decorator(sensitive_post_parameters(*args))
import jwt, re from django.conf import settings from django.contrib.auth.models import User from django.shortcuts import redirect from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_protect csrf_protected_method = method_decorator(csrf_protect) from django.shortcuts import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated def login_decorator(function): def wrapper(request, *args, **kwargs): username = request.user print(username) return function(request, *args, **kwargs) return Response(content) red = Redis() # red object is created token = red.get('token').decode("utf-8") print(token) return wrapper
request=request, id_token=id_token_hint, post_logout_redirect_uri=post_logout_redirect_uri, state=state, client=client, next_page=next_page ) return AuthServiceLogout.as_view(next_page=next_page)(request) # Protect the login view using Defender. Defender provides a method decorator # which we have to tweak to apply to the dispatch method of a view. # This is based on their own implementation of their middleware class: # https://github.com/kencochrane/django-defender/blob/master/defender/middleware.py#L24-L27 defender_decorator = watch_login() watch_login_method = method_decorator(defender_decorator) LoginView.dispatch = watch_login_method(LoginView.dispatch) registration_forms = ( ("userdata", forms.RegistrationForm), ("securityquestions", forms.SecurityQuestionFormSet), ) def show_security_questions(wizard): cleaned_data = wizard.get_cleaned_data_for_step( "userdata") or {"email": None} return cleaned_data["email"] is None class RegistrationWizard(LanguageMixin, NamedUrlSessionWizardView):
def view_decorator(*args): return method_decorator(args, name="dispatch")
def nodereps_only(f): return restricted_view(f, lambda u: u.IsNodeRep) def admins_only(f): return restricted_view(f, lambda u: u.IsAdmin) def admins_or_nodereps(f): return restricted_view(f, lambda u: u.IsAdmin or u.IsNodeRep) def authentication_required(f): return restricted_view(f, lambda u: u.IsLoggedIn) def privileged_only(f): return restricted_view( f, lambda u: u.IsAdmin or u.IsNodeRep or u.IsMastrAdmin or u. IsProjectLeader) def mastr_users_only(f): return restricted_view( f, lambda u: u.IsAdmin or u.IsMastrAdmin or u.IsProjectLeader or u. IsMastrStaff) mastr_users_only_method = method_decorator(mastr_users_only)
class AuthorCreateRestricted(AuthorCreate): post = method_decorator(login_required)(AuthorCreate.post)
from django.utils.decorators import method_decorator from django.views.decorators.debug import sensitive_post_parameters from rest_auth.registration.views import RegisterView as BaseRegisterView from rest_auth.registration.views import SocialConnectView, SocialLoginView from rest_framework.generics import RetrieveUpdateAPIView from rest_framework.permissions import AllowAny, IsAuthenticated from core.models import Profile from core.serializers import ( ProfileSerializer, CustomSocialLoginSerializer, UserSerializer, ) sensitive_param = method_decorator( sensitive_post_parameters("password"), name="dispatch" ) class UpdateProfile(RetrieveUpdateAPIView): """ API View for retrieving and updating user profile info like military service details, current employment, etc """ queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = (IsAuthenticated,) def get_object(self): """
def simple_decorator(View): View.dispatch = method_decorator(function_decorator)(View.dispatch) return View
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from django.shortcuts import reverse from django.utils.html import escape from django.utils.decorators import method_decorator from django.views.decorators.debug import sensitive_post_parameters from api.admin import admin_site from . import models sensitive_post_parameters_m = method_decorator(sensitive_post_parameters()) @admin.register(models.Role, site=admin_site) class RoleAdmin(UserAdmin): fieldsets = ( (None, { 'fields': ('password', 'last_login', 'link') }), (_('Permissions'), { 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions') }), ) readonly_fields = ('last_login', 'link') list_display = ('id', 'type', 'link', 'is_staff', 'is_superuser') list_filter = ('type', 'is_staff', 'is_superuser', 'groups') filter_horizontal = (
from django.utils.encoding import force_text from django.utils.html import escape from django.utils.translation import ugettext from django.utils.translation import ugettext_lazy as _ from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters from import_export.admin import ImportExportModelAdmin from rangefilter.filter import DateRangeFilter from campusromero_openedx_extensions.custom_registration_form.admin import \ CustomFormFieldsInline from student.admin import UserProfileInline # pylint: disable=import-error from .resources import UserResource csrf_protect_m = method_decorator(csrf_protect) # pylint: disable=invalid-name sensitive_post_parameters_m = method_decorator(sensitive_post_parameters()) # pylint: disable=invalid-name,line-too-long try: admin.site.unregister(User) except NotRegistered: pass class CustomUserAdmin(ImportExportModelAdmin): """ ImportExport model admin for UserResource """ resource_class = UserResource add_form_template = 'admin/auth/user/add_form.html' change_user_password_template = None
from django.utils.decorators import method_decorator, classonlymethod from django.utils.encoding import force_text, smart_text, smart_str from django.utils.functional import Promise from django.utils.http import urlencode from django.utils.itercompat import is_iterable from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext as _ from django.views.decorators.csrf import csrf_protect from django.views.generic import View from collections import OrderedDict from xadmin.util import static, json, vendor, sortkeypicker from xadmin.models import Log csrf_protect_m = method_decorator(csrf_protect) class IncorrectPluginArg(Exception): pass def get_content_type_for_model(obj): from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(obj, for_concrete_model=False) def filter_chain(filters, token, func, *args, **kwargs): if token == -1: return func() else:
from django.contrib.auth.forms import AdminPasswordChangeForm from django.contrib import messages from django.core.exceptions import PermissionDenied from django.http import HttpResponseRedirect, Http404 from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.html import escape from django.utils.decorators import method_decorator from django.utils.translation import ugettext, ugettext_lazy as _ from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters from .forms import CustomUserChangeForm, CustomUserCreationForm from .models import CustomUser csrf_protect_m = method_decorator(csrf_protect) sensitive_post_parameters_m = method_decorator(sensitive_post_parameters()) class CustomUserAdmin(admin.ModelAdmin): """ The default UserAdmin class, but with changes for our CustomUser where `first_name` and `last_name` are replaced by `full_name` and `short_name` """ add_form_template = 'admin/auth/user/add_form.html' change_user_password_template = None fieldsets = ( (None, { 'fields': ('username', 'password') }),
from rest_framework.generics import GenericAPIView, CreateAPIView from rest_framework.response import Response from rest_framework.permissions import AllowAny from rest_auth.models import TokenModel from rest_auth.utils import jwt_encode from rest_auth.app_settings import (TokenSerializer, JWTSerializer, create_token) from ...account.emails import send_account_create_confirmation_email from ...core.emails import get_email_base_context from ..serializers.auth import SignUpSerializer, PasswordResetConfirmSerializer sensitive_post_parameters_m = method_decorator( sensitive_post_parameters('password', 'password_confirm', 'new_password_1', 'new_password_2') ) class SignUpView(CreateAPIView): serializer_class = SignUpSerializer token_model = TokenModel @sensitive_post_parameters_m def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_response_data(self, user): if getattr(settings, 'REST_USE_JWT', False): data = { 'user': user,
from dj_rest_auth.app_settings import ( JWTSerializer, TokenSerializer, create_token, ) from dj_rest_auth.models import TokenModel from dj_rest_auth.registration.serializers import ( SocialAccountSerializer, SocialConnectSerializer, SocialLoginSerializer, VerifyEmailSerializer, ResendEmailVerificationSerializer ) from dj_rest_auth.utils import jwt_encode from dj_rest_auth.views import LoginView from .app_settings import RegisterSerializer, register_permission_classes sensitive_post_parameters_m = method_decorator( sensitive_post_parameters('password1', 'password2'), ) class RegisterView(CreateAPIView): serializer_class = RegisterSerializer permission_classes = register_permission_classes() token_model = TokenModel throttle_scope = 'dj_rest_auth' @sensitive_post_parameters_m def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_response_data(self, user): if allauth_settings.EMAIL_VERIFICATION == \
import abc from django.db import transaction from django.http import Http404, HttpResponseRedirect from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from sentry.models import OrganizationMember from sentry.web.decorators import signed_auth_required from sentry.web.frontend.base import BaseView signed_auth_required_m = method_decorator(signed_auth_required) class UnsubscribeBaseView(BaseView, metaclass=abc.ABCMeta): auth_required = False @never_cache @signed_auth_required_m @transaction.atomic def handle(self, request, **kwargs): if not getattr(request, "user_from_signed_request", False): raise Http404 instance = self.fetch_instance(**kwargs) if not OrganizationMember.objects.filter( user=request.user, organization=instance.organization ).exists(): raise Http404
request.method = 'PUT' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'DELETE' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments. def simple_dec(func): def wrapper(arg): return func("test:" + arg) return wraps(func)(wrapper) simple_dec_m = method_decorator(simple_dec) # For testing method_decorator, two decorators that add an attribute to the function def myattr_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr = True return wraps(func)(wrapper) myattr_dec_m = method_decorator(myattr_dec) def myattr2_dec(func):
from django.contrib.auth.decorators import login_required from django.contrib.gis.measure import D from django.db.models import Q from django.utils import timezone from django.utils.decorators import method_decorator from accounts.views import SignupEmailView, LoginView from contact.utils import get_location from feeds.post_feed import LocalFeed from feeds.views import FeedMixin from schedule.models import Show login_required_m = method_decorator(login_required) def shows(request, scope='any-distance', *args, **kwargs): kwargs['scope'] = scope if request.user.is_authenticated(): views = AUTH_VIEWS else: views = VIEWS return views.get(scope, views['any-distance'])(request, *args, **kwargs) class ShowViewAuth(FeedMixin): model = Show path_to_genre = 'info__venue__profile__genre__slug' template_name = 'feeds/shows_shows.html' feedType = 'shows' default_order = "upcoming"
from billing.signals import (transaction_was_successful, transaction_was_unsuccessful) from django.core.urlresolvers import reverse from billing.models import AmazonFPSResponse try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import urllib import time import datetime FPS_PROD_API_ENDPOINT = "fps.amazonaws.com" FPS_SANDBOX_API_ENDPOINT = "fps.sandbox.amazonaws.com" csrf_exempt_m = method_decorator(csrf_exempt) require_POST_m = method_decorator(require_POST) class AmazonFpsIntegration(Integration): """ Fields required: transactionAmount: Amount to be charged/authorized paymentReason: Description of the transaction paymentPage: Page to direct the user on completion/failure of transaction """ display_name = "Amazon Flexible Payment Service" template = "billing/amazon_fps.html" def __init__(self, options=None):
def method_login_and_permission(permission_name): return method_decorator(login_and_permission(permission_name), name="dispatch")
class KnowledgeQuantumAdmin(SortableAdmin): """ Administration for the KnowledgeQuantums. Has an inline for attachments. .. versionadded:: 0.1 """ inlines = [ AttachmentInline, ] list_display = ('__unicode__', 'title', 'media_content_type', 'media_content_id', 'weight') list_filter = ('unit', ) csrf_protect_m = method_decorator(csrf_protect) ensure_csrf_cookie_m = method_decorator(ensure_csrf_cookie) class QuestionAdmin(admin.ModelAdmin): """ Administration for questions inside nuggets. The URLs are extended to process extra stuff like videos and options. It has a get_state, _is_scheduled and _is_active method to obtain the current status of the last frame of the video. :context: title, object_id, original, is_popup, app_label, opts, has_absolute_url, content_type_id, add, change, options_json .. versionadded: 0.1
def simple_decorator(view_class): view_class.dispatch = method_decorator(function_decorator)( view_class.dispatch) return view_class
from .utils import ( complete_signup, get_login_redirect_url, get_next_redirect_url, logout_on_password_change, passthrough_next_redirect_url, perform_login, sync_user_email_addresses, url_str_to_user_pk, ) INTERNAL_RESET_URL_KEY = "set-password" INTERNAL_RESET_SESSION_KEY = "_password_reset_key" sensitive_post_parameters_m = method_decorator( sensitive_post_parameters("oldpassword", "password", "password1", "password2")) def _ajax_response(request, response, form=None, data=None): adapter = get_adapter(request) if adapter.is_ajax(request): if isinstance(response, HttpResponseRedirect) or isinstance( response, HttpResponsePermanentRedirect): redirect_to = response["Location"] else: redirect_to = None response = adapter.ajax_response(request, response, form=form, data=data,
from django.contrib import admin from django.contrib.admin import helpers from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.views.decorators import staff_member_required from django.utils.decorators import method_decorator from django.conf.urls import patterns, url from django.shortcuts import render_to_response, redirect from django.template import RequestContext from django.contrib import messages from dash.models import DashboardWorkspace, DashboardEntry, DashboardPlugin, DashboardSettings from dash.forms import BulkChangeDashboardPluginsForm from dash.constants import ACTION_CHOICE_REPLACE staff_member_required_m = method_decorator(staff_member_required) # ********************************************************* # ************************ Admin helpers ****************** # ********************************************************* def bulk_change_dashboard_plugins(modeladmin, request, queryset): """ Bulk change of dashboard plugins action additional view. Data is changed in ``DashboardPluginAdmin.bulk_change_dashboard_plugins`` method. """ opts = modeladmin.model._meta app_label = opts.app_label selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
from django.contrib.admin.options import IS_POPUP_VAR from django.utils.decorators import method_decorator from django.utils.translation import ugettext, ugettext_lazy as _ from django.views.decorators.debug import sensitive_post_parameters from django.views.decorators.http import require_POST from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.http import HttpResponseRedirect from django.utils.html import escape from django.contrib import messages from django.contrib.auth.forms import AdminPasswordChangeForm from cla_auth.models import AccessAttempt sensitive_post_parameters_m = method_decorator(sensitive_post_parameters()) require_POST_m = method_decorator(require_POST) class OneToOneUserAdmin(admin.ModelAdmin): change_password_form = AdminPasswordChangeForm change_user_password_template = None def username_display(self, one2one_model): return one2one_model.user.username username_display.short_description = "Username" username_display.admin_order_field = "user__username" def first_name_display(self, one2one_model): return one2one_model.user.first_name
def _inner(method): setattr(method, '_accepts', verbs) return method_decorator( require_http_methods([x.upper() for x in verbs]))(method)
from django.db import models from django.contrib.auth.decorators import permission_required from django.utils.decorators import method_decorator class ModulePermissions(models.Model): class Meta: managed = False default_permissions = [] permissions = [ ('can_view_module', 'Can see link in the NetDash navbar and access module.'), ] can_view_permission = permission_required("hostlookup_bluecat.can_view_module", raise_exception=True) can_view_permission_dispatch = method_decorator(can_view_permission, name='dispatch')
from profiles.models import (User) from profiles.serializers import (UserProfileSerializer) from .serializers import (JWTSerializer, UserProfileSerializer, jwt_response_payload_handler, jwt_payload_handler) from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_decode as uid_decoder from django.contrib.auth.__init__ import get_user_model UserModel = get_user_model() sensitive_post_parameters_m = method_decorator( sensitive_post_parameters('password', 'old_password', 'new_password1', 'new_password2')) class CustomLoginView(APIView): """ Base API View that various JWT interactions inherit from. """ permission_classes = () authentication_classes = () serializer_class = JSONWebTokenSerializer def get_serializer_context(self): """ Extra context provided to the serializer class. """
template_tags, login_user, logout_user, register_user from contrib.many_files.views import files from contrib.osm.views import map from contrib.django_exes.views import Login from contrib.django_exes.forms import AxesLoginForm from contrib.api_lead.views import UserViewSet, ItemListApiView, ItemDetailsApiView, api from contrib.form_wizard.views import ContactWizard, formset_view, form_messages, widget_form from contrib.notifications.views import get_notification from contrib.sort_filter.views import filter, get_country, get_pub from contrib.calculator.views import get_response from contrib.currencies.views import exchange_rate, convert_currencies from contrib.validators.views import validator from contrib.django_polymorphic.views import AminalsViewSet from rest_framework.authtoken.views import obtain_auth_token LoginView.dispatch = method_decorator(axes_dispatch)(LoginView.dispatch) LoginView.form_invalid = method_decorator(axes_form_invalid)( LoginView.form_invalid) admin.autodiscover() router = routers.DefaultRouter() router.register(r'users', UserViewSet) # router.register(r'items', ItemListApiView) from django.contrib import admin from django.utils.translation import gettext_lazy as _ admin.site.index_title = _('My Project') admin.site.site_header = _('My Site Administration') admin.site.site_title = _('Administration')