Esempio n. 1
0
 def decorator(funcOrModel):
     if type(funcOrModel) is DjangoModel:
         funcOrModel._express_dispatcher = require_http_methods(args)(
             funcOrModel._express_dispatcher)
     else:
         funcOrModel._methods = args  # this will be used later upon autodiscover() for creating service dispatcher (per url).
     return funcOrModel
Esempio n. 2
0
    def decorator(func):
        # Register the function.
        register_func(AjaxFunc(func, url, method))

        # Decorate func.
        func = require_http_methods([method])(func)

        @wraps(func)
        def wrapper(request, **kwargs):
            if not request.is_ajax():
                return HttpResponseBadRequest("Invalid requester")

            # Pass request params to the view as keyword arguments.
            # The first argument is skipped since it is the request.
            request_data = request.GET if method == 'GET' else request.POST
            for param in params:
                try:
                    kwargs[param] = request_data[param]
                except KeyError:
                    return HttpResponseBadRequest()

            try:
                result = func(request, **kwargs)
            except AjaxError as ae:
                return ae.render()

            if isinstance(result, HttpResponse):
                return result
            else:
                return HttpResponse(
                    json.dumps(result),
                    status=200,
                    content_type='application/json',
                )
        return wrapper
Esempio n. 3
0
    def decorator(func):
        # Decorate func.
        func = require_http_methods([method])(func)

        @wraps(func)
        def wrapper(request, **kwargs):
            #if not request.is_ajax():
            #    return HttpResponseBadRequest("Invalid requester")

            # Pass request params to the view as keyword arguments.
            # The first argument is skipped since it is the request.
            request_data = request.GET if method == 'GET' else request.POST
            for i, param in enumerate(params):
                try:
                    kwargs[param] = request_data[param]
                except KeyError:
                    if i < defaults_start:
                        return HttpResponseBadRequest()
                    kwargs[param] = defaults[i - defaults_start]

            try:
                result = func(request, **kwargs)
            except AjaxError as ae:
                return ae.render()

            if isinstance(result, (HttpResponse, StreamingHttpResponse)):
                return result
            else:
                return HttpResponse(
                    json.dumps(result),
                    status=200,
                    content_type='application/json',
                )
        return wrapper
Esempio n. 4
0
        def __init__(self, obj):
            super(Wrapper, self).__init__(obj)

            if isinstance(obj, types.ClassType):
                obj = obj()

            permitted_methods = {}

            for method in methods:
                if hasattr(obj, method):
                    fnc = getattr(obj, method)
                    if not isinstance(fnc, types.FunctionType):
                        fnc = partial(fnc, obj)
                    permitted_methods[method.upper()] = fnc

                else:
                    # in case we have decorated function instead of class..
                    if callable(obj):
                        permitted_methods[method.upper()] = obj

            require_http_methods_decorator = http.require_http_methods(
                request_method_list=permitted_methods.keys())
            for key, val in permitted_methods.items():
                setattr(self, key.lower(), val)

            self.permitted_methods = permitted_methods.keys()

            self.inner = reduce(lambda fnc, dec: dec(fnc),
                                (require_http_methods_decorator, ) +
                                decorators, self.inner)
Esempio n. 5
0
        def __init__(self, obj):
            super(Wrapper, self).__init__(obj)

            if isinstance(obj, types.ClassType):
                obj = obj()

            permitted_methods = {}

            for method in ('get','post', 'option', 'put', 'delete', 'head'):
                if hasattr(obj, method):
                    fnc = getattr(obj, method)
                    if not isinstance(fnc, types.FunctionType):
                        fnc = partial(fnc, obj)
                    permitted_methods[method.upper()] = fnc

                else:
                    # in case we have decorated function instead of class..
                    if callable(obj):
                        permitted_methods[method.upper()] = obj

            require_http_methods_decorator = http.require_http_methods(request_method_list=permitted_methods.keys())
            for key, val in  permitted_methods.items():
                setattr(self, key.lower(), val)

            self.permitted_methods = permitted_methods.keys()

            self.inner = reduce(lambda fnc, dec: dec(fnc), (require_http_methods_decorator,)+decorators, self.inner )
Esempio n. 6
0
class HookView(View):
    @method_decorator(csrf_exempt)
    @method_decorator(require_http_methods(['POST']))
    def dispatch(self, *args, **kwargs):
        if self.request.method == 'POST' \
          and self.request.META.get('CONTENT_TYPE') == 'application/json':
            try:
                event = '_%s' % self.request.META.get('HTTP_X_GITHUB_EVENT')

                if hasattr(self, event):
                    getattr(self, event)(get_object_or_404(
                        Repository, pk=self.kwargs['repo_id']),
                                         json.loads(self.request.body))
            except Exception:
                logger.exception(
                    self.request.META.get('X-GitHub-Delivery', None))
            return HttpResponse('OK')
        return HttpResponseNotFound()

    def _push(self, repo, payload):
        match = re.match(r"refs/heads/(?P<branch>.*)", payload['ref'])
        git_branch = match.groupdict()['branch']

        if payload['created'] or payload['deleted']:
            update_branch.delay(
                repo.id, git_branch, payload['head_commit']['id']
                if payload['head_commit'] else None)

        if 'commits' in payload and len(payload['commits']):
            log_commits.delay(repo.id, git_branch,
                              payload['head_commit']['id'], payload['commits'])

    def _pull_request(self, repo, payload):
        update_pull.delay(repo.id, payload['action'], payload['pull_request'])
Esempio n. 7
0
        def __init__(self, obj):
            super(Wrapper, self).__init__(obj)

            if isinstance(obj, types.ClassType):
                obj = obj()

            def get_function(obj, name):
                if hasattr(obj, name):
                    fnc = getattr(obj, name)
                    if not isinstance(fnc, types.FunctionType): # we heave instance method
                        fnc = partial(fnc, obj)
                    return fnc

            if callable(obj):
                permitted_methods = dict((method.upper(), obj) for method in _HTTP_METHODS )
                require_http_methods_decorators = ()
            else:
                permitted_methods = dict(filter(None, ((method.upper(), get_function(obj,method)) for method in _HTTP_METHODS )))
                require_http_methods_decorators = http.require_http_methods(request_method_list=permitted_methods.keys()),


            for key, val in  permitted_methods.items():
                setattr(self, key.lower(), val)
            
            self.permitted_methods = permitted_methods.keys()

            # decorate inner function
            self.inner = reduce(lambda fnc, dec: dec(fnc), require_http_methods_decorators+decorators, self.inner )
Esempio n. 8
0
class Index(View):
    # 私有缓存控制 1,请求方法限制,缓存并缓存时间
    get_decorators = [
        cache_control(private=True),
        require_http_methods([
            'GET',
        ]),
        cache_page(60 * 15)
    ]

    # @method_decorator(patch_cache_control())
    @method_decorator(get_decorators)
    def get(self, request):
        # django-redis 锁/支持分布式
        # ----- 有问题 -----
        # with cache.lock("my_key"):
        #     name = cache.get('my_key')
        #     # 获取多个缓存结果
        #     # cache.get_many(['a', 'b', 'c'])
        #     # 删除缓存
        #     # cache.delete('xxx')
        #     # cache.delete_many(['a', 'b', 'c'])
        #     # 清除所有缓存
        #     # cache.clear()
        #     # # 重新设置过期时间
        #     cache.touch('my_key', 60 * 15)
        #     # # 缓存增 1
        #     # cache.incr(key, delta=1, version=None)
        #     # # 缓存减 1
        #     # cache.decr(key, delta=1, version=None)

        logger = logging.getLogger(__name__)
        logger.info('Something went send!')

        context = {"key": "asdfo23jhj45k2l", "msg": "你好", "name": "xxx"}
        return render(request, "index.html", context)

    @method_decorator(vary_on_cookie)  # 私有缓存控制 2
    @method_decorator(cache_page(60 * 15))
    @method_decorator(require_http_methods(['POST']))
    def post(self, request):
        response = HttpResponse()
        name = cache.get('my_key')
        response.write("<h2>{name}</h2>".format(name=name))
        patch_cache_control(response, private=True)  # 私有缓存控制 2

        return response
Esempio n. 9
0
 def wrapper(func):
     return \
         wraps(func)(
             require_http_methods(methods)(
                 cookie_fix(
                     valid_astakos_user_required(
                         transaction_method(
                             handles_project_errors(func))))))
Esempio n. 10
0
def hijack_require_http_methods(fn):
    """
    Wrapper for "require_http_methods" decorator. POST required by default, GET can optionally be allowed
    """
    required_methods = ['POST']
    if hijack_settings.HIJACK_ALLOW_GET_REQUESTS:
        required_methods.append('GET')
    return require_http_methods(required_methods)(fn)
Esempio n. 11
0
def simple_handler_view(handler_class):
    handler = handler_class()
    methods_decorator = require_http_methods(list(handler.allowed_methods))

    def output_view(request, *args, **kwargs):
        return handler.handle_request(request, *args, **kwargs)

    return methods_decorator(csrf_exempt(json_view(output_view)))
Esempio n. 12
0
 def wrapper(func):
     return \
         wraps(func)(
             require_http_methods(methods)(
                 cookie_fix(
                     valid_astakos_user_required(
                         transaction_method(
                             handles_project_errors(func))))))
Esempio n. 13
0
class PostLogoutView(views.LogoutView):
    """only with Post request user can log out,
    this add more security."""
    next_page = reverse_lazy('logout_post')

    @method_decorator(require_http_methods([
        "POST",
    ]))
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)
Esempio n. 14
0
def hijack_require_http_methods(fn):
    """
    Wrap the ``require_http_methods`` decorator.

    POST required by default, GET can optionally be allowed.
    """
    required_methods = ["POST"]
    if hijack_settings.HIJACK_ALLOW_GET_REQUESTS:
        required_methods.append("GET")
    return require_http_methods(required_methods)(fn)
    def urlpatterns(cls):
        res = []
        for pattern, methods in cls._urlpatterns.items():

            def view(_methods, request, *args, **kwargs):
                return _methods[request.method]['view'](request, *args, **kwargs)

            view = require_http_methods(methods.keys())(partial(view, methods))
            res.append(url(pattern, view))
        return res
Esempio n. 16
0
    def decorator(api_func):

        wrapped_func = check_authentication(func=api_func)
        if need_token:
            wrapped_func = check_token(func=wrapped_func)
        wrapped_func = pack_response(func=wrapped_func)
        wrapped_func = prepare_request_data(func=wrapped_func)
        wrapped_func = api_view(http_method_names=REQUEST_METHOD_LIST)(func=wrapped_func)
        wrapped_func = require_http_methods(request_method_list=REQUEST_METHOD_LIST)(func=wrapped_func)

        return wrapped_func
Esempio n. 17
0
class GradeIndexView(TemplateView):
  template_name = 'judge/grade_index.html'

  def get_context_data(self, *args, **kwargs):
    context = super(GradeIndexView, self).get_context_data(*args, **kwargs)
    context['graded_list'] = user_time_filter(self.request.user, Status.objects.filter(status_type='GRADED'))
    return context

  @method_decorator(require_http_methods(["GET", "HEAD"]))
  @method_decorator(login_required)
  def dispatch(self, *args, **kwargs):
    return super(GradeIndexView, self).dispatch(*args, **kwargs)
Esempio n. 18
0
class LinkView(ListView):
  """
  The view that gets all of the links and passes it to the template
  'judge/link_list.html'.

  This view only accepts GET and HEAD method.  It does not require
  login.
  """
  model = Link

  @method_decorator(require_http_methods(["GET", "HEAD"]))
  def dispatch(self, *args, **kwargs):
    return super(LinkView, self).dispatch(*args, **kwargs)
Esempio n. 19
0
class BaseNamespaceView(TemplateView):
  """
  We need this base because we need to process the root namespace as
  special case.

  The view only accepts GET and HEAD method.  It requires login.
  """
  template_name = 'judge/namespace.html'

  @method_decorator(require_http_methods(["GET", "HEAD"]))
  @method_decorator(login_required)
  def dispatch(self, *args, **kwargs):
    return super(BaseNamespaceView, self).dispatch(*args, **kwargs)
Esempio n. 20
0
    def decorator(func):
        # Decorate func.
        func = require_http_methods([method])(func)

        @wraps(func)
        def wrapper(request, event_slug, **kwargs):
            #if not request.is_ajax():
            #    return HttpResponseBadRequest("Invalid requester")

            # Prevent access if checkout is not active.
            event = get_object_or_404(Event, slug=event_slug)
            if not staff_override and not event.checkout_active:
                raise Http404()

            if not ignore_session:
                # Ensure the request hasn't changed Event.
                session_event = request.session.get("event")
                if session_event is not None and session_event != event.pk:
                    return AjaxError(
                        RET_CONFLICT, _("Event changed. Please refresh the page and re-login.")).render()

            # Pass request params to the view as keyword arguments.
            # The first argument is skipped since it is the request.
            request_data = request.GET if method == 'GET' else request.POST
            for i, param in enumerate(params):
                try:
                    if i == 0 and param == "event":
                        # Supply event from function arguments.
                        kwargs[param] = event
                    else:
                        # Default: Supply argument value from request data.
                        kwargs[param] = request_data[param]
                except KeyError:
                    if i < defaults_start:
                        return HttpResponseBadRequest()
                    kwargs[param] = defaults[i - defaults_start]

            try:
                result = func(request, **kwargs)
            except AjaxError as ae:
                return ae.render()

            if isinstance(result, (HttpResponse, StreamingHttpResponse)):
                return result
            else:
                return HttpResponse(
                    json.dumps(result),
                    status=200,
                    content_type='application/json',
                )
        return wrapper
Esempio n. 21
0
class GradeView(TemplateView):
  template_name = 'judge/grade.html'

  def get_context_data(self, *args, **kwargs):
    context = super(GradeView, self).get_context_data(*args, **kwargs)
    context['status_grade'] = get_object_or_404(Status, id=context['params']['pk'])
    gd = Status.objects.filter(status_type='GRADED', groups=self.request.user.groups.all())
    context['namespace_problem'] = get_grade_detail(self.request.user, [n for g in gd for n in g.namespaces.all()])
    return context

  @method_decorator(require_http_methods(["GET", "HEAD"]))
  @method_decorator(login_required)
  def dispatch(self, *args, **kwargs):
    return super(GradeView, self).dispatch(*args, **kwargs)
Esempio n. 22
0
class SubmitFormView(TemplateView):
  template_name='submit.html'

  def get_context_data(self, *args, **kwargs):
    context = super(SubmitFormView, self).get_context_data(*args, **kwargs)
    context['problem'] = get_problem(self.request.user, context['params']['pid'])
    if not context['problem'].submittable:
      raise Http404
    return context
  
  @method_decorator(require_http_methods(["GET", "HEAD"]))
  @method_decorator(login_required)
  def dispatch(self, *args, **kwargs):
    return super(SubmitFormView, self).dispatch(*args, **kwargs)
Esempio n. 23
0
class StatusView(ListView):
  """
  The view to pass the data of the status of the user to template
  'judge/status_list.html'.

  It will only get the status that is activated on the user.
  """
  def get_queryset(self):
    return user_time_filter(self.request.user, Status.objects)

  @method_decorator(require_http_methods(["GET", "HEAD"]))
  @method_decorator(login_required)
  def dispatch(self, *args, **kwargs):
    return super(StatusView, self).dispatch(*args, **kwargs)
Esempio n. 24
0
class AnnouncementView(ListView):
  """
  The view that gets all of the announcements and passes it to the
  template 'judge/announcement_list.html'.

  This view only accepts GET and HEAD method.  It also requires login.
  """
  model = Announcement
  paginate_by = 5 

  @method_decorator(require_http_methods(["GET", "HEAD"]))
  @method_decorator(login_required)
  def dispatch(self, *args, **kwargs):
    return super(AnnouncementView, self).dispatch(*args, **kwargs)
Esempio n. 25
0
    def decorator(func):
        func = csrf_exempt(func)
        func = require_http_methods(methods)(func)

        @wraps(func)
        def decorated_func(request, appname, *args, **kwargs):
            request = WeChatInfo.patch_request(request, appname)
            response = func(request, *args, **kwargs)
            return auto_response(response)

        pattern = url(r"^(?P<appname>[-_a-zA-Z\d]+)/" + route,
                      decorated_func,
                      name=name or func.__name__)
        url_patterns.append(pattern)
        return decorated_func
Esempio n. 26
0
class ProblemView(DetailView):
  """
  The view to pass the data of the problem to template
  'judge/problem_detail.html'.
  """
  model = Problem

  def get_context_data(self, *args, **kwargs):
    context = super(ProblemView, self).get_context_data(*args, **kwargs)
    if not problem_permitted(self.request.user, context['object']):
      raise Http404
    return context 

  @method_decorator(require_http_methods(["GET", "HEAD"]))
  @method_decorator(login_required)
  def dispatch(self, *args, **kwargs):
    return super(ProblemView, self).dispatch(*args, **kwargs)
Esempio n. 27
0
File: api.py Progetto: aryla/kirppu
    def decorator(func):
        # Get argspec before any decoration.
        (args, _, _, defaults) = inspect.getargspec(func)

        # Register the function.
        name = func.func_name
        AJAX_FUNCTIONS[name] = AjaxFunc(func, url, method)

        # Decorate func.
        func = require_http_methods([method])(func)

        @wraps(func)
        def wrapper(request, **kwargs):
            if not request.is_ajax():
                return HttpResponseBadRequest("Invalid requester")

            # Pass request params to the view as keyword arguments.
            # The first argument is skipped since it is the request.
            request_data = request.GET if method == 'GET' else request.POST
            for arg in args[1:]:
                try:
                    kwargs[arg] = request_data[arg]
                except KeyError:
                    return HttpResponseBadRequest()

            try:
                # Check session counter and clerk.
                if counter:
                    get_counter(request)
                if clerk:
                    get_clerk(request)

                result = func(request, **kwargs)
            except AjaxError as ae:
                return ae.render()

            if isinstance(result, HttpResponse):
                return result
            else:
                return HttpResponse(
                    json.dumps(result),
                    status=200,
                    content_type='application/json',
                )
        return wrapper
Esempio n. 28
0
class SubmitView(View):
  def post(self, request, *args, **kwargs):
    if request.POST['submit_method']=='textarea':
      submission = Submission(
        problem=get_problem(request.user, request.POST['pid']),
        user=request.user,
        code=request.POST['code']
      )
    elif request.POST['submit_method']=='file':
      pass # TODO support upload source by file
    submission.full_clean()
    submission.save()
    return redirect('problem', pk=request.POST['pid'])

  @method_decorator(require_http_methods(["POST"]))
  @method_decorator(login_required)
  def dispatch(self, *args, **kwargs):
    return super(SubmitView, self).dispatch(*args, **kwargs)
Esempio n. 29
0
    def wechat_view(self, view, methods=None):
        """通过wechat_view装饰的view
        request变为``wechat_django.requests.WeChatHttpRequest``实例
        request中将带有``wechat_django.models.WeChatInfo``类型的wechat属性
        """
        methods = methods or ("GET", )

        @wraps(view)
        def decorated_view(request, appname, *args, **kwargs):
            # 只允许queryset内的appname访问本站点
            try:
                app = self.app_queryset.get_by_name(appname)
            except WeChatApp.DoesNotExist:
                return response.HttpResponseNotFound()

            request = patch_request(request, appname, _app=app)
            resp = view(request, *args, **kwargs)
            return auto_response(resp)

        rv = csrf_exempt(decorated_view)
        rv = require_http_methods(methods)(rv)

        return rv
Esempio n. 30
0
from django.conf.urls import patterns, include, url
from django.views.decorators.http import require_http_methods

from api.views.auth import AuthView
from api.views.log import LogView
from api.views.stats import StatsView
from api.views.teams import TeamsView


urlpatterns = patterns('',
	url(r'auth/$', require_http_methods(['OPTIONS', 'POST'])(AuthView.as_view())),
	url(r'log/$', require_http_methods(['OPTIONS', 'GET', 'PUT', 'DELETE'])(LogView.as_view())),
	url(r'teams/$', require_http_methods(['OPTIONS', 'GET', 'PUT', 'DELETE'])(TeamsView.as_view())),
	url(r'stats/$', require_http_methods(['OPTIONS', 'GET'])(StatsView.as_view())),
)

"""
POST /auth/
	password
	200: token, role
	400: error

GET /teams/
	200: list of {id, name, players}
	403

PUT /teams/
	name, players
	200: id
	400: error
	403
Esempio n. 31
0
from functools import wraps

from django.core.handlers.wsgi import WSGIRequest as Request
from django.views.decorators.http import require_http_methods
from pure_pagination import Paginator
from django.http import JsonResponse
from django.http.request import QueryDict

from building.serializers import model_serializer
from building.status import result_content, HTTP_200_OK
from building.utils import is_int, is_float, is_date
# from user.service import get_role_permission

require_GET = require_http_methods(["GET"])
require_PUT = require_http_methods(["PUT"])
require_POST = require_http_methods(["POST"])
require_DELETE = require_http_methods(["DELETE"])


def get_request(args):
    """
    获取request
    :param args:
    :return:
    """
    request = None
    if isinstance(args[0], Request):
        request = args[0]
    elif isinstance(args[1], Request):
        request = args[1]
Esempio n. 32
0
            yaml = get_yaml_from_mercurial(package.vcs_address,
                                           package.vcs_subdir)
        elif package.vcs_type == VCS_GIT:
            yaml = get_yaml_from_git(package.vcs_address, package.vcs_subdir)

        default = yaml['default']
        map(lambda x: yaml['default'].setdefault(x, ''), default_fields)

        if package.name != default['name']:
            raise PackageNameInconsistentError()

        package.name = default['name']
        package.version = default['version']
        package.build = default['build']
        package.release = default['release']
        package.summary = default['summary']

        package.recent_changes = yaml['.']['recent_changes']

        package.save()
        return HttpResponse('Package %s refreshed sucessfully' % package.name)
    except Package.DoesNotExist:
        return HttpResponse('NOTEXIST')

list_view = PackageTableView.as_view()
detail_view = PackageDetailView.as_view()
create_view = login_required(PackageCreateView.as_view())
comment_create_view = require_http_methods(['POST'])(
    login_required(CommentCreateView.as_view()))
comment_list_view = CommentListView.as_view()
Esempio n. 33
0
def require_http_method(method):
    return require_http_methods([method])
Esempio n. 34
0
def compose(*functions):
    # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs))
    functions = list(reversed(functions))

    def _inner(*args, **kwargs):
        result = functions[0](*args, **kwargs)
        for f in functions[1:]:
            result = f(result)
        return result
    return _inner


full_decorator = compose(
    # django.views.decorators.http
    require_http_methods(["GET"]),
    require_GET,
    require_POST,
    require_safe,
    condition(lambda r: None, lambda r: None),

    # django.views.decorators.vary
    vary_on_headers('Accept-language'),
    vary_on_cookie,

    # django.views.decorators.cache
    cache_page(60 * 15),
    cache_control(private=True),
    never_cache,

    # django.contrib.auth.decorators
Esempio n. 35
0
File: views.py Progetto: Rousong/xfz
    raise RuntimeError("请配置UEditor的配置文件的路径!")

# 如果配置了七牛的配置信息
if UEDITOR_UPLOAD_TO_QINIU:
    try:
        UEDITOR_QINIU_ACCESS_KEY = settings.UEDITOR_QINIU_ACCESS_KEY
        UEDITOR_QINIU_SECRET_KEY = settings.UEDITOR_QINIU_SECRET_KEY
        UEDITOR_QINIU_BUCKET_NAME = settings.UEDITOR_QINIU_BUCKET_NAME
        UEDITOR_QINIU_DOMAIN = settings.UEDITOR_QINIU_DOMAIN
    except Exception as e:
        option = e.args[0]
        raise RuntimeError('请在app.config中配置%s!' % option)


@method_decorator(
    [csrf_exempt, require_http_methods(['GET', 'POST'])], name='dispatch')
class UploadView(View):
    def __init__(self):
        super(UploadView, self).__init__()

    def _random_filename(self, rawfilename):
        """
        随机的文件名,保证文件名称不会冲突
        """
        letters = string.ascii_letters
        random_filename = str(time.time()) + "".join(random.sample(letters, 5))
        filename = hashlib.md5(random_filename.encode('utf-8')).hexdigest()
        subffix = os.path.splitext(rawfilename)[-1]
        return filename + subffix

    def _json_result(self, state='', url='', title='', original=''):
Esempio n. 36
0
from django.utils.encoding import force_text
from django.utils.http import urlsafe_base64_decode
from django.views.decorators.http import require_http_methods
from django.views.generic import CreateView
from django.views.generic.edit import FormView
from django.contrib.auth.views import LoginView, PasswordChangeView, PasswordChangeDoneView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.contrib.auth import views
from django.utils.decorators import method_decorator
from django.urls import reverse_lazy
from user.forms import CustomUserCreationForm, CustomAuthenticationForm, SendEmailVerification
from user.models import EmailUser


@method_decorator(require_http_methods(["POST", ]), name='dispatch')
class PostLogoutView(views.LogoutView):
    """only with Post request user can log out,
    this add up to security."""
    next_page = reverse_lazy('user:logout_done')

    # @method_decorator(require_http_methods(["POST", ]))
    # def dispatch(self, request, *args, **kwargs):
    #     return super().dispatch(request, *args, **kwargs)


class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    # todo: make a active your email account template
    success_url = reverse_lazy('user:login')
    template_name = 'registration/signup.html'
Esempio n. 37
0
 def _inner(method):
     setattr(method, '_accepts', verbs)
     return method_decorator(
         require_http_methods([x.upper() for x in verbs])
     )(method)
Esempio n. 38
0
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from PirsiPy import settings
from blog.entries_views import EntriesListView, EntryDetailView, EntryCreateView
from django.contrib.auth.views import logout, login
from django.views.decorators.http import require_http_methods
from blog.error_views import error, LOGIN_ERROR, LOGIN_REQUIRED

admin.autodiscover()

# по данному адресу можно только отправлять данные форме авторизации
login_post_only = require_http_methods(['POST'])(login)

urlpatterns = patterns('',

    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', EntriesListView.as_view()), #главная
    url(r'^page(?P<page>\d+)/$', EntriesListView.as_view(), name='entries_list'), #главная
    url(r'^entry/(?P<slug>[\w-]+)/$', EntryDetailView.as_view(), name='entry'), #страницы записей
    url(r'^add/$',EntryCreateView.as_view()), #добавление записи
    #авторизация
    url(r'^login/$',login_post_only),
    url(r'^logout/$',logout, {'next_page':'/'}),
    url(r'^login_error/$', error, {'error_text':LOGIN_ERROR}),
    url(r'^login_required/$', error, {'error_text':LOGIN_REQUIRED}),
    #авторизация через соц сети
    url('', include('social.apps.django_app.urls', namespace='social'))
)+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\
 + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\
Esempio n. 39
0
from django.views.generic.base import View, TemplateResponseMixin
from django.views.generic.edit import FormView, BaseCreateView, BaseUpdateView
from django.contrib.auth import login, logout, authenticate, REDIRECT_FIELD_NAME
from django.http import HttpResponseRedirect
from django.conf import settings
from django.views.decorators.http import require_POST, require_http_methods
from django.shortcuts import render

from main.class_decorators import login_required, csrf_protect, never_cache, unauthorized_only
from users.forms import AuthForm, RegisterUserForm, ProfileForm
from users.models import Profile
from referrals.models import Referrer
from users.utils import get_prev_url, get_redirect_url

require_GET_POST = require_http_methods(['GET', 'POST'])

if not hasattr(settings, 'REDIRECT_FIELD_NAME'):
    setattr(settings, 'REDIRECT_FIELD_NAME', REDIRECT_FIELD_NAME)

class AuthMixin(object):
    
    redirect_field_name = settings.REDIRECT_FIELD_NAME
    
    def get_redirect_url(self):
        return get_redirect_url(self.request, self.redirect_field_name)
    
    def get_success_url(self):
        return self.success_url or self.get_redirect_url()
    
    def get_context_data(self, **kwargs):
        data = {
Esempio n. 40
0
        jre = JsonResponse(data)

    return jre

# /user/logout  退出登录
def logout(request):
    '''用户退出登录'''
    request.session.flush() #删掉用户的登录信息
    return redirect('/')


'''
    用户注册模块
'''
# /user/register/   返回注册页面 、 完成注册功能
require_http_methods(['GET',"POST"])
def register(request):
    '''显示注册页面,用户注册功能'''
    if request.method == "GET" :
        return render(request,'df_user/register.html')
    else :
        '''实现用户信息的注册
            1 接收用户的注册信息
            2 保存到数据库
            3 跳转到登录页面
        '''
        # 1 接收用户注册信息
        username = request.POST.get('user_name')
        password = request.POST.get('pwd')
        email = request.POST.get('email')
        # 2 保存进数据库
Esempio n. 41
0
def _api_post(func):
    @functools.wraps(func)
    def inner(request, *args, **kwargs):
        if not request.is_ajax():
            return json_error_response("Request was not ajax")

        try:
            kwargs["body"] = json.loads(request.body)
        except ValueError:
            return json_error_response("Request data was not JSON")

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

api_post = lambda func: staticmethod(_api_post(require_http_methods(["POST"])(func)))

def _api_get(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        return func(*args, **kwargs)
    return inner

api_get = lambda func: staticmethod(_api_get(require_http_methods(["GET"])(func)))

class JsonSerialize(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, "to_dict"):
            return obj.to_dict()

        if isinstance(obj, datetime.datetime):
Esempio n. 42
0
import logging
from functools import wraps

from django.views.decorators.http import require_http_methods
from django.http import Http404
from django.core.exceptions import PermissionDenied
from django.utils.decorators import  available_attrs
from django.contrib.contenttypes.models import ContentType

from core.apps.accounts.models import User

require_PUT = require_http_methods (['PUT'])
require_DELETE = require_http_methods (['DELETE'])


logger = logging.getLogger('django.request')

def require_request_attributes(attrs):
    """
    Decorator that check if a teacher can delete a course .  Usage::

        @require_request_attributes(['attr1', 'attr2', 'attr3'], type)
        def my_view(request, id):
            # 
            # ...

    Note that request methods should be in uppercase.
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
Esempio n. 43
0
def route_by_method(**mapping):
    def view(request, *args, **kwargs):
        return mapping[request.method](request, *args, **kwargs)
    return require_http_methods(mapping.keys())(view)
Esempio n. 44
0
from django.http import HttpResponse, HttpRequest
from django.utils.functional import allow_lazy, lazy, memoize
from django.views.decorators.http import require_http_methods, require_GET, require_POST
from django.views.decorators.vary import vary_on_headers, vary_on_cookie
from django.views.decorators.cache import cache_page, never_cache, cache_control
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
from django.contrib.admin.views.decorators import staff_member_required

def fully_decorated(request):
    """Expected __doc__"""
    return HttpResponse('<html><body>dummy</body></html>')
fully_decorated.anything = "Expected __dict__"

# django.views.decorators.http
fully_decorated = require_http_methods(["GET"])(fully_decorated)
fully_decorated = require_GET(fully_decorated)
fully_decorated = require_POST(fully_decorated)

# django.views.decorators.vary
fully_decorated = vary_on_headers('Accept-language')(fully_decorated)
fully_decorated = vary_on_cookie(fully_decorated)

# django.views.decorators.cache
fully_decorated = cache_page(60*15)(fully_decorated)
fully_decorated = cache_control(private=True)(fully_decorated)
fully_decorated = never_cache(fully_decorated)

# django.contrib.auth.decorators
# Apply user_passes_test twice to check #9474
fully_decorated = user_passes_test(lambda u:True)(fully_decorated)
Esempio n. 45
0
def client_post(view):
	return csrf_exempt(require_http_methods(['POST'])(view))
Esempio n. 46
0
def require_http_method(method):
    return require_http_methods([method])
Esempio n. 47
0
def client_get(view):
	return csrf_exempt(require_http_methods(['GET'])(view))
Esempio n. 48
0

class BlogDetail(DetailView):
    model = Post

    def get_context_data(self, **kwargs):
        context = super(BlogDetail, self).get_context_data(**kwargs)
        context['locale'] = context['object'].locale
        return context

    def get_queryset(self):
        return Post.objects.published().filter(
            locale=self.kwargs['locale'],
        )

blog_detail = require_http_methods(['GET', 'HEAD'])(BlogDetail.as_view())


class BlogDetailPreview(BlogDetail):
    def get_queryset(self):
        return Post.objects.all()


blog_detail_preview = never_cache(
    staff_member_required(
        require_http_methods(['GET', 'HEAD'])(
            BlogDetailPreview.as_view(),
        )
    )
)
Esempio n. 49
0
    :returns: The result of invoking ``function`` if the user is logged in;
              otherwise 401 Unauthorized.
    :rtype: ``django.http.HttpResponse``
    """
    @wraps(function)
    def wrapper(request, *args, **kwargs):
        if request.user.is_authenticated():
            return function(request, *args, **kwargs)
        else:
            return HttpResponse(status=401)

    return wrapper


# Django only provides GET and POST decorators.
require_DELETE = require_http_methods(["DELETE"])
require_DELETE.__doc__ = """A view decorator that only allows DELETE requests.

Returns 405 Method Not Allowed for any other method.
"""


def slug_url(model, required=True, pk_key="pk", slug_key="slug"):
    """A decorator for Django views with "slug" URLs.

    A slug URL includes a primary key and slug (e.g. ``/objects/1-name/``).
    These are used to retrieve a model instance of the given type (``model``),
    which is passed to the view.

    If ``required`` is ``True`` and no matching model is found, 404 Not Found is
    return. If ``slug`` is incorrect, a permanent redirect to the correct URL.
Esempio n. 50
0
import os
import base64
import time
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from base64 import b64decode
from django.conf import settings
from django.http import FileResponse, Http404, HttpResponse, HttpResponseRedirect

# Create your views here.


require_http_methods(['GET'])
def index(request):
    return render(request, 'index.html')


require_http_methods(['GET', 'POST'])
def handle_pdf_file(request):
    if request.method == 'POST':
        pdf64 = request.POST['encoded']
        split_data = pdf64.split(',')[1]
        # decoded from base64 
        bytese = b64decode(split_data, validate=True)
        if bytese[0:4] != b'%PDF':
            raise ValueError('Missing the PDF file signature')
        # taking current time
        currenttime = str(int(time.time()))
        filepath = settings.MEDIA_ROOT
        # create currenttime  as file name in media folder
        completeName = os.path.join(filepath, currenttime+'.pdf')
Esempio n. 51
0
	)

from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login, logout as auth_logout
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
# Create your views hee.

@require_http_methods(['GET'])
def index(request):
	if request.method == "GET":
		if "next" in request.GET:
			request.session["next"] = request.GET["next"]
		return render(request, "users/index.html")

@method_decorator([login_required, require_http_methods(['GET'])])
def welcome(request):
	if request.method == "GET":
		logout(request)
		return redirect(settings.LOGIN_URL)

class CreateUser(View):
	template_name = "user_form.html"
	form_class = UserCreateForm
	success_url = "users:login"

	def get(self, request):
		form = self.form_class()
		context = self.get_context(form)
		return render(request, self.template_name, context)
Esempio n. 52
0
def compose(*functions):
    # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs))
    functions = list(reversed(functions))

    def _inner(*args, **kwargs):
        result = functions[0](*args, **kwargs)
        for f in functions[1:]:
            result = f(result)
        return result

    return _inner


full_decorator = compose(
    # django.views.decorators.http
    require_http_methods(["GET"]),
    require_GET,
    require_POST,
    require_safe,
    condition(lambda r: None, lambda r: None),

    # django.views.decorators.vary
    vary_on_headers('Accept-language'),
    vary_on_cookie,

    # django.views.decorators.cache
    cache_page(60 * 15),
    cache_control(private=True),
    never_cache,

    # django.contrib.auth.decorators
Esempio n. 53
0
    def decorated(request, *args, **kwargs):
        return view(request, *args, **kwargs)
    return decorated


@view_config(route_name='index.dashboard', request_method='GET', renderer='index.html')
def dashboard(request):
    return {'method': 'GET'}


# request method restrictions using django decorators (for testing Rhetoric's "decorator" option)

@view_config(route_name='index.dashboard', request_method='POST', renderer='index.html',
             # only POST method will be handled, since the request_method param
             # is explicitly set
             decorator=require_http_methods(["GET", "POST"]))
def post_on_dashboard(request):
    request.response.status_code = 201
    return {'method': 'POST'}


@view_config(route_name='index.dashboard', request_method='PUT', renderer='index.html',
             # test multiple decorators combined
             decorator=(phony_decorator, phony_decorator))
def put_on_dashboard(request):
    return {'method': 'PUT'}


# Versioned views
# --------------------------------
@view_config(route_name='index.versions', request_method='GET', api_version='1.0', renderer='json')
Esempio n. 54
0
 def _inner(method):
     setattr(method, '_accepts', verbs)
     return method_decorator(
         require_http_methods([x.upper() for x in verbs]))(method)
Esempio n. 55
0
from django.conf.urls import patterns, url
from django.views.decorators.http import require_http_methods

from apps.requestlog import views

urlpatterns = patterns(
    '',
    url(r'^$', views.RequestsView.as_view(), name='requests'),

    url(r'^(?P<pk>\d+)/update$',
        require_http_methods(['POST'])(views.RequestUpdateView.as_view()),
        name='request_update'),
)