Example #1
0
def redirect_urlpatterns():
    """
    Helper function to return a URL pattern for index page http://host/.
    """
    if settings.INDEX_TEMPLATE is None:
        return patterns('', url(r'^$', never_cache(RedirectView.as_view(url=reverse_lazy('webindex'))), name="index" ))
    else:
        return patterns('', url( r'^$', never_cache(RedirectView.as_view(url=reverse_lazy('webindex_custom'))), name="index" ),)
 def inner(filename, *args, **kwargs):
     if not getattr(settings, 'TABULAR_RESPONSE_DEBUG', False):
         return f(filename, *args, **kwargs)
     else:
         resp = never_cache(export_to_debug_html_response)(filename, *args, **kwargs)
         del resp['Content-Disposition']  # Don't trigger a download
         return resp
Example #3
0
    def rest_view(self, view, cacheable=False):
        """
        Decorator to create an rest view attached to this ``RestSite``. 

        You'll want to use this from within ``RestSite.get_urls()``:

            class MyRestSite(RestSite):

                def get_urls(self):
                    from django.conf.urls.defaults import patterns, url

                    urls = super(MyRestSite, self).get_urls()
                    urls += patterns('',
                        url(r'^my_view/$', self.rest_view(some_view))
                    )
                    return urls

        By default, rest_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view)
Example #4
0
 def wrap(view):
     def wrapper(request, *args, **kwargs):
         if not self.admin_site.has_permission(request):
             return self.admin_site.login(request)
         return view(request, *args, **kwargs)
     wrapper = never_cache(wrapper)
     return update_wrapper(wrapper, view)    
def admin_staff_member_required(
    view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
    login_url='admin:login', cacheable=False
):
    """
    Decorator for views that checks that the user is logged in and is a staff
    member, redirecting to the login page if necessary.

    Also it make csrf_protect for each view and if need mark as chachable
    """

    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_staff,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )

    view_func = actual_decorator(view_func)

    # make views as non chached
    if not cacheable:
        view_func = never_cache(view_func)

    # We add csrf_protect here so this function can be used as a utility
    # function for any view, without having to repeat 'csrf_protect'.
    if not getattr(view_func, 'csrf_exempt', False):
        view_func = csrf_protect(view_func)

    return view_func
Example #6
0
    def admin_view(self, view, cacheable=False):
        """Decorator to create an admin view attached to this AdminSite. This
        wraps the view and provides permission checking by calling
        self.has_permission (except for the logout page).
  
        """

        def inner(request, * args, ** kwargs):
            if not self.has_permission(request) and view != self.logout:
                if not request.user.is_authenticated():
                    return self.login(request)
                else:
                    return render_to_response('shibsso/no_permission.html', {
                                              'title': _('Site administration')
                                              }, context_instance=RequestContext(request))
                                          
            return view(request, * args, ** kwargs)
        if not cacheable:
            inner = never_cache(inner)
        try:
            # Backwards-compatibility for Django 1.1.1
            if not getattr(view, 'csrf_exempt', False):
                inner = csrf_protect(inner)
        except:
            pass
        return update_wrapper(inner, view)
Example #7
0
    def admin_view(self, view, cacheable=False):
        """
        Override superclass admin_view to provide our own auth flow.

        Specifically:
        * Return 403 if authenticated and has_permission returns False
        * Redirect to login if not authenticated
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request):
                if request.path == reverse('admin:logout', current_app=self.name):
                    index_path = reverse('admin:index', current_app=self.name)
                    return HttpResponseRedirect(index_path)
                # Inner import to prevent django.contrib.admin (app) from
                # importing django.contrib.auth.models.User (unrelated model).
                from django.contrib.auth.views import redirect_to_login
                # Begin overriden portion here
                if not request.user.is_authenticated():
                    return redirect_to_login(
                        request.get_full_path(),
                        reverse('admin:login', current_app=self.name)
                    )
                else:
                    return HttpResponseForbidden(_('Permission Denied.'))
                # End overriden portion
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(view, 'csrf_exempt', False):
            inner = csrf_protect(inner)
        return update_wrapper(inner, view)
Example #8
0
    def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import patterns, url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += patterns('',
                        url(r'^my_view/$', self.admin_view(some_view))
                    )
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view)
Example #9
0
def decorate(view):
    """
    Decorate our views as login_required and never_cache
    :param view: The view to decorate
    :return: The view, decorated with login_required and never_cache
    """
    return login_required(never_cache(view))
Example #10
0
    def as_view(self, view, cacheable=False, extra_permission=None):
        """
        Wraps a view in authentication/caching logic

        extra_permission can be used to require an extra permission for this view, such as a module permission
        """

        def inner(request, *args, **kwargs):
            if not self.has_permission(request, extra_permission):
                # show login pane
                return self.login(request)
            return view(request, *args, **kwargs)

        # Mark it as never_cache
        if not cacheable:
            inner = never_cache(inner)

        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(view, "csrf_exempt", False):
            inner = csrf_protect(inner)

        inner = ensure_csrf_cookie(inner)

        return update_wrapper(inner, view)
Example #11
0
 def admin_view(self, view, cacheable=False):
     # not everything can take extra_context
     excludes = [
         'password_change',
         'password_change_done',
         'i18n_javascript',
         'login',
         'logout',
         'user_change_password',
     ]
     def inner(request, *args, **kwargs):
         if not self.has_permission(request):
             return self.login(request)
         if view.__name__ not in excludes:
             extra_context = kwargs.get('extra_context', {})
             extra_context = self.annotate_context(extra_context)
             kwargs['extra_context'] = extra_context
         return view(request, *args, **kwargs)
     if not cacheable:
         inner = never_cache(inner)
     # We add csrf_protect here so this function can be used as a utility
     # function for any view, without having to repeat 'csrf_protect'.
     if not getattr(view, 'csrf_exempt', False):
         inner = csrf_protect(inner)
     return update_wrapper(inner, view)
Example #12
0
    def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls.defaults import patterns, url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += patterns('',
                        url(r'^my_view/$', self.admin_view(some_view))
                    )
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request):
                return self.login(request)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(view, 'csrf_exempt', False):
            inner = csrf_protect(inner)
        return update_wrapper(inner, view)
Example #13
0
def test_shared_cache_control_decorator_keeps_no_cache(rf, settings):
    request = rf.get('/foo')
    response = shared_cache_control(never_cache(simple_view))(request)
    assert response.status_code == 200
    assert 'public' not in response['Cache-Control']
    assert 's-maxage' not in response['Cache-Control']
    assert_no_cache_header(response)
Example #14
0
    def get_plugin_urls(self):
        subscription_view = self.get_subscription_view()

        return patterns('',
            url(
                r'^subscribe/$', never_cache(subscription_view),
                name='aldryn-mailchimp-subscribe'),
        )
Example #15
0
def never_cache_patterns(*args):
    """Prevent any included URLs from being cached by the browser.

    It's sometimes desirable not to allow browser caching for a set of URLs.
    Any URLs passed in will have the
    :py:func:`~django.views.decorators.cache.never_cache` decorator applied.

    Args:
        *args (tuple):
            The URL arguments to pass to the function.

            If the first parameter is a prefix string for view lookup strings,
            then this will emit a deprecation warning, as these are no longer
            supported in Django 1.10 or higher.

    Returns:
        list:
        A list of URL patterns.
    """
    if isinstance(args[0], six.string_types):
        prefix = args[0]
        args = args[1:]
    else:
        prefix = None

    if prefix:
        msg = ('String prefixes for URLs in never_cache_patterns() is '
               'deprecated, and will not work on Django 1.10 or higher.')

        if hasattr(RegexURLPattern, 'add_prefix'):
            warnings.warn(msg, RemovedInDjblets20Warning)
        else:
            raise ValueError(msg)

    pattern_list = []

    for t in args:
        if prefix:
            if isinstance(t, (list, tuple)):
                # This will crash on Django 1.10. The user has been warned.
                t = url(prefix=prefix, *t)
            elif isinstance(t, RegexURLPattern):
                # This will crash on Django 1.10. The user has been warned.
                t.add_prefix(prefix)

        cb = never_cache(t.callback)

        if hasattr(t, '_callback'):
            # Django <= 1.9
            t._callback = cb
        else:
            # Django >= 1.10
            t.callback = cb

        pattern_list.append(t)

    return pattern_list
Example #16
0
 def wrapped_view_func(request, *args, **kwargs):
     try:
         (cache_timeout, cache_kwargs) = req_cache_func(request,
                                                        *args,
                                                        **kwargs)
         ret = cache_page(cache_timeout, **cache_kwargs)(view_func)
     except TypeError:
         ret = never_cache(view_func)
     return ret(request, *args, **kwargs)
Example #17
0
 def get_allow_handler(self):
     """
     When never_cache is truthy, wraps the base handler in
     django.views.decorators.cache.never_cache().
     
     """
     allow = super(NeverCache, self).get_allow_handler()
     if self.get_never_cache():
         allow = cache.never_cache(allow)
     return allow
Example #18
0
 def with_perms(self, view, cacheable=False):
     def inner(request, *args, **kwargs):
         if not self.has_permission(request):
             return self.login(request)
         return view(request, *args, **kwargs)
     if not cacheable:
         inner = never_cache(inner)
     if not getattr(view, 'csrf_exempt', False):
         inner = csrf_protect(inner)
     return update_wrapper(inner, view)
Example #19
0
 def api_view(self, view, cacheable=False):
     def inner(request, *args, **kwargs):
         return view(request, *args, **kwargs)
     if not cacheable:
         inner = never_cache(inner)
     # We add csrf_protect here so this function can be used as a utility
     # function for any view, without having to repeat 'csrf_protect'.
     if not getattr(view, 'csrf_exempt', False):
         inner = csrf_protect(inner)
     return update_wrapper(inner, view)
Example #20
0
 def admin_view(self, view, cacheable=False):
     def inner(request, *args, **kwargs):
         if not self.has_permission(request):
             raise PermissionDenied
         return view(request, *args, **kwargs)
     if not cacheable:
         inner = never_cache(inner)
     # We add csrf_protect here so this function can be used as a utility
     # function for any view, without having to repeat 'csrf_protect'.
     inner = csrf_protect(inner)
     return update_wrapper(inner, view)
Example #21
0
 def admin_view(self, view, cacheable=False):
     def inner(request, *args, **kwargs):
         if not self.has_permission(request):
             return self.login(request)
         for key in kwargs.keys():
             if key.startswith(OBJECT_ID_PREFIX):
                 self.base_object_ids.update({key[len(OBJECT_ID_PREFIX):]: kwargs.pop(key)})
             if key.startswith(MODEL_ADMIN_PREFIX):
                 self.base_tools_model_admins.update({key[len(MODEL_ADMIN_PREFIX):]: kwargs.pop(key)})
         return view(request, *args, **kwargs)
     if not cacheable:
         inner = never_cache(inner)
     return update_wrapper(inner, view)
    def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import patterns, url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += patterns('',
                        url(r'^my_view/$', self.admin_view(some_view))
                    )
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request):
                country = get_country_from_url(request.get_full_path())
                if request.path == reverse(country+':logout',current_app=self.name):
                    index_path = reverse(country+':index', current_app=self.name)
                    return HttpResponseRedirect(index_path)

                if not "/password/" in request.path:
                    return self.login(request)
                else:
                    if "/password/reset/done/" in request.path:
                        return self.pwd_reset_done(request)
                    elif "/password/reset/confirm/complete/" in request.path:
                        return self.pwd_reset_confirm_complete(request)
                    elif "/password/reset/confirm/" in request.path:
                        return self.pwd_reset_confirm(request)
                    else:
                        return self.pwd_reset(request)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(view, 'csrf_exempt', False):
            inner = csrf_protect(inner)
        return update_wrapper(inner, view)
Example #23
0
 def decorator(func):
     @require_http_methods([method])
     @wraps(func)
     def decorated(request, *args, **kwargs):
         try:
             return func(request, *args, **kwargs)
         except Exception as e:
             print e
             raise
     if cache is False:
         decorated = never_cache(decorated)
     if ssl:
         decorated = require_ssl(decorated)
     decorated.push = push
     return decorated
Example #24
0
 def admin_view(self, view, cacheable=False):
     """
     Override to pass kwargs to self.login so we can pass in URL variables
     """
     def inner(request, *args, **kwargs):
         if not self.has_permission(request):
             return self.login(request, *args, **kwargs)
         return view(request, *args, **kwargs)
     if not cacheable:
         inner = never_cache(inner)
     # We add csrf_protect here so this function can be used as a utility
     # function for any view, without having to repeat 'csrf_protect'.
     if not getattr(view, 'csrf_exempt', False):
         inner = csrf_protect(inner)
     return update_wrapper(inner, view)
Example #25
0
 def admin_view(self, view, cacheable = False):
     def inner(request, *args, **kwargs):
         if not self.has_permission(request):
             if request.path == reverse('logout',
                                        current_app=self.name):
                 index_path = reverse('index', current_app=self.name)
                 return HttpResponseRedirect(index_path)
             return self.login(request)
         return view(request, *args, **kwargs)
     if not cacheable:
         inner = never_cache(inner)
         # We add csrf_protect here so this function can be used as a utility
     # function for any view, without having to repeat 'csrf_protect'.
     if not getattr(view, 'csrf_exempt', False):
         inner = csrf_protect(inner)
     return update_wrapper(inner, view)
Example #26
0
    def site_view_decor(self, view, cacheable=False):
        """
        为所有 View 提供公共装饰,访问权限验证
        在Site.get_urls 方法中使用该方法

        :param cacheable: 默认情况下,所有的 AdminView 会通过 ``never_cache`` 标记成不做缓存,如果确实需要缓存,可以设置 cacheable=True
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                # 没有权限则跳转到登录页
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)

        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view)
Example #27
0
    def admin_view(cls, cached=False, **kwargs):
        view = func(cls, **kwargs)

        def has_permission(request):
            if request.user.is_active:
                return True
            else:
                return False

        def inner(request, *args, **kwargs):
            if not has_permission(request) and getattr(cls, 'need_site_permission', True):
                return LoginView.as_view()(request, *args, **kwargs)
            return view(request, *args, **kwargs)

        if not cached:
            inner = never_cache(inner)
        return update_wrapper(inner, view)
Example #28
0
    def wrapp_view(self, meth):

        def wrapper(request, *args, **kwargs):
            view = login_required(meth, login_url=reverse('djoe_client:login'))
            return view(request, *args, **kwargs)

        if getattr(meth, 'jsonable', False):
            wrapper = self.json_decor(wrapper)

        if not getattr(meth, 'cacheable', False):
            wrapper = never_cache(wrapper)

        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(meth, 'csrf_exempt', False):
            wrapper = csrf_protect(wrapper)
        return wrapper
Example #29
0
    def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """

        def inner(request, *args, **kwargs):
            if not self.has_permission(request):
                if request.path == reverse('admin:logout', current_app=self.name):
                    index_path = reverse('admin:index', current_app=self.name)
                    return HttpResponseRedirect(index_path)
                # Inner import to prevent django.contrib.admin (app) from
                # importing django.contrib.auth.models.User (unrelated model).
                from django.contrib.auth.views import redirect_to_login
                return redirect_to_login(
                    request.get_full_path(),
                    reverse('admin:login', current_app=self.name)
                )
            return view(request, *args, **kwargs)

        if not cacheable:
            inner = never_cache(inner)
        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(view, 'csrf_exempt', False):
            inner = csrf_protect(inner)
        return update_wrapper(inner, view)
Example #30
0
def never_cache_patterns(prefix, *args):
    """
    Prevents any included URLs from being cached by the browser.

    It's sometimes desirable not to allow browser caching for a set of URLs.
    This can be used just like patterns().
    """
    pattern_list = []
    for t in args:
        if isinstance(t, (list, tuple)):
            t = url(prefix=prefix, *t)
        elif isinstance(t, RegexURLPattern):
            t.add_prefix(prefix)

        t._callback = never_cache(t.callback)
        pattern_list.append(t)

    return pattern_list
Example #31
0
from django.core.exceptions import ValidationError
from django.core.validators import EmailValidator
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.cache import never_cache

from parliament.accounts.models import LoginToken, TokenError, User
from parliament.core.views import disable_on_readonly_db
from parliament.utils.views import JSONView


class CurrentAccountView(JSONView):
    def get(self, request):
        return {'email': request.authenticated_email}


current_account = never_cache(CurrentAccountView.as_view())


class LogoutView(JSONView):
    def post(self, request):
        request.authenticated_email = None
        return True


logout = never_cache(LogoutView.as_view())


def _get_ip(request):
    ip = request.META['REMOTE_ADDR']
    if ip == '127.0.0.1' and 'HTTP_X_REAL_IP' in request.META:
        ip = request.META['HTTP_X_REAL_IP']
Example #32
0
from stars.apps.institutions.data_displays.views import *

app_name = 'data_displays'

urlpatterns = [
    # data views
    url(r'^$',
        TemplateView.as_view(
            template_name='institutions/data_views/index.html'),
        name="data_view_index"),
    url(r'^pie-chart-visualization/$', PieChartView.as_view(),
        name="piechart"),
    url(r'^dashboard/$', Dashboard.as_view(), name="dashboard"),
    url(r'^(?P<cs_version>[^\/]+)/categories/$',
        never_cache(AggregateFilter.as_view()),
        name="categories_data_display"),
    url(r'^(?P<cs_version>[^\/]+)/scores/$',
        never_cache(ScoreFilter.as_view()),
        name="scores_data_display"),
    url(r'^(?P<cs_version>[^\/]+)/content/$',
        never_cache(ContentFilter.as_view()),
        name="content_data_display"),
    url(r'^(?P<cs_version>[^\/]+)/scores/excel/$',
        never_cache(ScoreExcelFilter.as_view())),
    url(r'^(?P<cs_version>[^\/]+)/content/excel/$',
        never_cache(ContentExcelFilter.as_view())),
    url(r'^callback/cs/(?P<cs_id>\d+)/$',
        CategoryInCreditSetCallback.as_view()),
    url(r'^callback/cat/(?P<category_id>\d+)/$',
        SubcategoryInCategoryCallback.as_view()),
Example #33
0
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)
fully_decorated = require_safe(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)
fully_decorated = login_required(fully_decorated)
fully_decorated = permission_required('change_world')(fully_decorated)

# django.contrib.admin.views.decorators
fully_decorated = staff_member_required(fully_decorated)

# django.utils.functional
fully_decorated = memoize(fully_decorated, {}, 1)
fully_decorated = allow_lazy(fully_decorated)
fully_decorated = lazy(fully_decorated)
Example #34
0
    def delete(self, request, pk):
        if request.instance.session:
            return HttpResponse(status=codes.bad_request)
        request.instance.delete()
        return HttpResponse(status=codes.no_content)


class DataContextHistoryResource(DataContextBase):
    "DataContext History Resource"

    def get(self, request):
        queryset = self.get_queryset(request, archived=True).iterator()
        return map(self.prepare, queryset)


datacontext_resource = never_cache(DataContextResource())
datacontext_history_resource = never_cache(DataContextHistoryResource())

# Resource endpoints
urlpatterns = patterns(
    '',
    url(r'^$', datacontext_resource, name='datacontexts'),
    url(r'^session/$',
        datacontext_resource, {'session': True},
        name='datacontext'),
    url(r'^(?P<pk>\d+)/$', datacontext_resource, name='datacontext'),
    url(r'^history/$',
        datacontext_history_resource,
        name='datacontext-history'),
)
Example #35
0
"""
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""
from django.conf.urls import url
from django.views.decorators.cache import never_cache

from submissions import views

urlpatterns = [
    # Submissions list
    url(r'^api/v1/submissions/$',
        never_cache(views.SubmissionListAPIView.as_view()),
        name='submissions-list'),

    # Submissions home (loads Submissions application)
    url(r'^submissions/',
        views.SubmissionsHomeView.as_view(),
        name='submissions-home')
]
Example #36
0
    re_path(r'^profile/', include('apps.users.urls')),
    re_path(r'^questions/', include('apps.questions.urls')),
    re_path(r'^i18n/', include(i18n)),

    # API urls
    re_path(r'^api/', include(ct_router.urls)),
    re_path(r'^api/', include(module_router.urls)),
    re_path(r'^api/', include(orga_router.urls)),
    re_path(r'^api/', include(question_router.urls)),
    re_path(r'^api/', include(likes_router.urls)),
    re_path(r'^api/', include(router.urls)),
    re_path(r'^upload/',
            user_is_project_admin(ck_views.upload),
            name='ckeditor_upload'),
    re_path(r'^browse/',
            never_cache(user_is_project_admin(ck_views.browse)),
            name='ckeditor_browse'),
    re_path(r'^components/$', contrib_views.ComponentLibraryView.as_view()),
    re_path(r'^jsi18n/$',
            JavaScriptCatalog.as_view(),
            name='javascript-catalog'),
    re_path(
        r'^(?P<organisation_slug>[-\w_]+)/',
        include([
            path(
                'budgeting/',
                include(('apps.budgeting.urls', 'a4_candy_budgeting'),
                        namespace='a4_candy_budgeting')),
            path('dashboard/', include('apps.dashboard.urls')),
            path(
                'ideas/',
Example #37
0
        httpcode = 200

    announcements = signals.get_announcements.send(sender="login",
                                                   location="loginpage")
    announcements = [announcement[1] for announcement in announcements]
    return HttpResponse(render_to_string(
        "registration/login.html", {
            "form": form,
            "error": error,
            "next": nextlocation,
            "annoucements": announcements
        }, request),
                        status=httpcode)


dologin = never_cache(dologin)


def dologout(request):
    """Logout current user."""
    if not request.user.is_anonymous:
        signals.user_logout.send(sender="dologout", request=request)
        logger = logging.getLogger("modoboa.auth")
        logger.info(
            _("User '{}' successfully logged out").format(
                request.user.username))
        logout(request)
    return HttpResponseRedirect(reverse("core:login"))


class PasswordResetView(auth_views.PasswordResetView):
Example #38
0
    else:
        form = None

    return render(
        request, template, {
            'all_super_groups': mgr.get_super_groups(),
            'page_class': 'settings',
            'title': title,
            'settings_group': settings,
            'group': group,
            'form': form,
            'use_db': use_db,
        })


group_settings = never_cache(
    permission_required('livesettings.change_setting')(group_settings))

# group_settings = never_cache(admins_only(group_settings))


# Site-wide setting editor is identical, but without a group
# permission_required is implied, since it calls group_settings
def site_settings(request):
    return group_settings(request,
                          group=None,
                          template='livesettings/site_settings.html')


def export_as_python(request):
    """Export site settings as a dictionary of dictionaries"""
Example #39
0
def staff_nocache(view):
    return staff_member_required(never_cache(view))
Example #40
0
# -*- coding: utf-8 -*-

from django.urls import re_path
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import ensure_csrf_cookie

from eventkit_cloud.auth.views import oauth, callback, logout

urlpatterns = [
    re_path(r'^oauth$', ensure_csrf_cookie(oauth), name='oauth'),
    re_path(r'^callback$', ensure_csrf_cookie(callback), name='callback'),
    re_path(r'^logout$',
            never_cache(ensure_csrf_cookie(logout)),
            name='logout')
]
def filebrowser_view(view):
    "Only let staff browse the files"
    return staff_member_required(never_cache(xframe_options_sameorigin(view)))
Example #42
0
from __future__ import absolute_import

import django
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache

from ckeditor_uploader import views

if django.VERSION >= (1, 8):
    urlpatterns = [
        url(r'^upload/', login_required(views.upload), name='ckeditor_upload'),
        url(r'^browse/', never_cache(login_required(views.browse)), name='ckeditor_browse'),
    ]
else:
    from django.conf.urls import patterns
    urlpatterns = patterns(
        '',
        url(r'^upload/', login_required(views.upload), name='ckeditor_upload'),
        url(r'^browse/', never_cache(login_required(views.browse)), name='ckeditor_browse'),
    )
Example #43
0
def filebrowser_view(view):
    "Only let staff browse the files"
    return staff_member_required(never_cache(view))
Example #44
0
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.contrib.staticfiles.views import serve
from django.views.decorators.cache import never_cache
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('main.urls', namespace='')),
]

if settings.DEBUG:
    urlpatterns.append(path('static/<path:path>', never_cache(serve)))
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)
Example #45
0
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
from django.views.decorators.cache import never_cache

from .auth import google

index = never_cache(TemplateView.as_view(template_name='index.html'))

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('api.urls')),
    path('auth/', include('djoser.urls')),
    path('auth/', include('djoser.urls.jwt')),
    path('auth/google', google),
    re_path(r'^.*', index)
]
Example #46
0
        {
            "dir": path,
            "p": p,
            "page": page,
            "results_var": results_var,
            "counter": counter,
            "query": query,
            "title": _("Media Library"),
            "settings_var": get_settings_var(),
            "breadcrumbs": get_breadcrumbs(query, path),
            "breadcrumbs_title": "",
        },
    )


browse = staff_member_required(never_cache(browse))


# mkdir signals
filebrowser_pre_createdir = Signal(providing_args=["path", "dirname"])
filebrowser_post_createdir = Signal(providing_args=["path", "dirname"])


@xframe_options_sameorigin
def mkdir(request):
    """
    Make Directory.
    """

    from filebrowser_safe.forms import MakeDirForm
Example #47
0
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

# ref: https://stackoverflow.com/questions/7013735/turn-off-caching-of-static-files-in-django-development-server
from django.conf import settings
from django.contrib.staticfiles.views import serve as serve_static
from django.views.decorators.cache import never_cache

from . import views

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^(?P<filename>(robots.txt)|(humans.txt))$', views.home_files, name='home_files'),
    url(r'^about/$', views.about, name='about'),
    url(r'^submissions/', views.submissions, name="submissions"),
    url(r'^ajax_update_ucd', views.ajax_update_ucd, name="ajax_update"),
    url(r'^ajax_select2', views.ajax_select2, name="ajax_select2"),
    url(r'^ingredient/', include('flavors.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'^select2/', include('django_select2.urls')),
    url(r'^accounts/', include('allauth.urls')),
]

if settings.DEBUG:
    urlpatterns.append(url(r'^static/(?P<path>.*)$', never_cache(serve_static)))
Example #48
0
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from ckeditor_uploader import views as views_ckeditor
from django.views.decorators.cache import never_cache
import blog.views
import disposal.views
import account.views
import board.views
import market.views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', blog.views.main, name='main'),
    path('be_geppetto/', include('blog.urls')),
    path('disposal/', include('disposal.urls')),
    path('account/', include('account.urls')),
    path('board/', include('board.urls')),
    path('ckeditor/', include('ckeditor_uploader.urls')),
    path('market/', market.views.market, name="market"),
    path('market/<int:market_id>', market.views.detail4, name="detail4"),
    path('market/delete/<int:market_id>', market.views.delete4,
         name="delete4"),
    path('market/new', market.views.marketpost, name="newblog"),
    path(r'^upload/', views_ckeditor.upload, name="ckeditor_upload"),
    path(r'^browse/',
         never_cache(views_ckeditor.browse),
         name='ckeditor_browse'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Example #49
0
#
# You should have received a copy of the Apache License
# along with Galaxy.  If not, see <http://www.apache.org/licenses/>.

from django.conf.urls import url
from django.conf import settings
from django.views.decorators.cache import never_cache
from django.contrib.staticfiles.views import serve as serve_staticfiles
from django.views.static import serve as serve_static

app_name = 'main'
urlpatterns = []

if settings.DEBUG:
    urlpatterns += [
        url(r'^static/(?P<path>.*)$', never_cache(serve_staticfiles))
    ]
else:
    urlpatterns += [
        url(r'^static/(?P<path>.*)$',
            serve_static,
            kwargs={'document_root': settings.STATIC_ROOT}),
        url(r'^(?P<path>.*(?:css|js|png|jpg|jpeg|ico|woff|woff2|svg|ttf))/?$',
            serve_static,
            kwargs={'document_root': settings.STATIC_ROOT}),
        url(r'^(?!api|static|accounts|{})'.format(settings.ADMIN_URL_PATH),
            serve_static,
            kwargs={
                'document_root': settings.STATIC_ROOT,
                'path': 'index.html'
            })
Example #50
0
File: urls.py Project: aih/FlatGov
app_name = 'home'

urlpatterns = [
    # path('', views.index, name='index'),
    path(
        "robots.txt",
        TemplateView.as_view(template_name="robots.txt",
                             content_type="text/plain"),
    ),
    path('home/', views.home_view, name='home'),
    path('about/', views.AboutView.as_view(), name='about'),
]

api_urlpatterns = [
    path('home/bill-list/',
         never_cache(views.BillListAPIView.as_view()),
         name='bill-list'),
    path('home/bill-titles/<congressnumber>',
         never_cache(views.BillListTitleAPIView.as_view()),
         name='bill-titles'),
    path('home/bill-title/<bill>/',
         never_cache(views.GetBillTitleAPIView.as_view()),
         name='bill-title'),
    path('press-statements/<congress>/<bill_type>/<bill_number>/',
         never_cache(GetPressStatementsAPIView.as_view()),
         name='press-statements'),
]

urlpatterns += api_urlpatterns
Example #51
0
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.views import serve
from django.views.decorators.cache import never_cache

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('yandex.urls', namespace='yandex'))
]


if settings.DEBUG:
    urlpatterns.append(
        path('static/<path:path>', never_cache(serve))
    )
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Example #52
0
    from django.views.defaults import page_not_found

    urlpatterns += [
        url(r'^404/$', page_not_found, {'exception': None}),
    ]

# Only enable debug toolbar if it's an installed app
if apps.is_installed('debug_toolbar'):
    import debug_toolbar

    urlpatterns += [
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ]

# Serving static/media under debug
urlpatterns += static(settings.STATIC_URL, never_cache(staticfiles_serve))
urlpatterns += static(settings.MEDIA_URL,
                      never_cache(serve),
                      document_root=settings.MEDIA_ROOT)


def handler500(request, template_name='500.html'):
    """ 500 handler with request context. """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return HttpResponseServerError('<h1>Server Error (500)</h1>',
                                       content_type='text/html')
    return HttpResponseServerError(template.render({
        'request': request,
    }))
Example #53
0
            'session_key': request.session.session_key,
            'result_processor': ASYNC_QUERY_RESULT_PROCESSOR_NAME
        }

        job_id = async_get_result_rows(
            request.instance.context,
            request.instance.view,
            query_options,
            job_data,
            request=request)

        return HttpResponseRedirect(
            reverse('serrano:jobs:single', kwargs={'job_uuid': job_id}))


results_resource = never_cache(AsyncQueryResultsResource())

# Resource endpoints
urlpatterns = patterns(
    '',
    url(
        r'^(?P<pk>\d+)/results/$',
        results_resource,
        name='results'
    ),
    url(
        r'^session/results/$',
        results_resource,
        {'session': True},
        name='results'
    ),
Example #54
0
    path(
        "api/logs/projects/<slug:project_id>/clusters/<slug:cluster_id>/",
        include("backend.container_service.observability.log_stream.urls"),
    ),
    re_path(r"^api/helm/projects/(?P<project_id>\w{32})/",
            include("backend.helm.urls")),
    path(r"change_log/", include("backend.change_log.urls")),
    # cluster manager的代理请求
    url(
        r"^{}".format(settings.CLUSTER_MANAGER_PROXY["PREFIX_PATH"]),
        include("backend.container_service.clusters.mgr.proxy.urls"),
    ),
]

# 导入版本特定的urls
try:
    from backend.urls_ext import urlpatterns as urlpatterns_ext

    urlpatterns += urlpatterns_ext
except ImportError:
    pass

# vue urls 需要放到最后面
urlpatterns_vue = [
    # fallback to vue view
    url(r"^login_success.html", never_cache(LoginSuccessView.as_view())),
    url(r"^(?P<project_code>[\w\-]+)?",
        never_cache(VueTemplateView.as_view(container_orchestration="k8s"))),
]
urlpatterns += urlpatterns_vue
Example #55
0
from django.conf.urls import url
from django.views.decorators.cache import never_cache

from gwells.urls import app_root_slash
from . import views

urlpatterns = [
    # Template views
    url(r'^well/(?P<pk>[0-9]+)$',
        views.WellDetailView.as_view(),
        name='well_detail'),

    # API endpoints
    # Well
    url(r'^api/v1/wells/(?P<well_tag_number>[0-9]+)$',
        never_cache(views.WellDetail.as_view()),
        name='well-detail'),

    # Well tag search
    url(r'^api/v1/wells/tags/$',
        never_cache(views.WellTagSearchAPIView.as_view()),
        name='well-tag-search'),

    # Documents (well records)
    url(r'^api/v1/wells/(?P<tag>[0-9]+)/files$',
        never_cache(views.ListFiles.as_view()),
        name='file-list'),

    # Extract files
    url(r'^api/v1/wells/extracts$',
        views.ListExtracts.as_view(),
Example #56
0
            error_message = _('The username or password is incorrect.')

    else:
        form = EmailAuthenticationForm(request)

    request.session.set_test_cookie()
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)

    # For logging in API clients
    if request.method == "GET" and "api" in request.GET and request.GET[
            'api'] == 'yes':
        token = get_token(request)
        return HttpResponse(json.dumps({'csrfmiddlewaretoken': token}),
                            content_type='application/json')

    return render(
        request, template_name, {
            'form': form,
            REDIRECT_FIELD_NAME: settings.URL + redirect_to,
            'site': current_site,
            'site_name': current_site.name,
            'allow_registration': settings.ALLOW_REGISTRATION,
            'error_message': error_message
        })


mylogin = never_cache(mylogin)
Example #57
0
    url(r"^",
        include("backend.apps.paas_monitor.urls", namespace="paas_monitor")),
    url(r"^api-auth/",
        include("rest_framework.urls", namespace="rest_framework")),
    # BCS K8S special urls
    url(r"^", include("backend.bcs_k8s.helm.urls", namespace="bcs_k8s_app")),
    url(r"^", include("backend.bcs_k8s.app.urls", namespace="bcs_k8s_helm")),
    # Ticket凭证管理
    url(r"^", include("backend.apps.ticket.urls", namespace="ticket")),
    url(r"^",
        include("backend.bcs_k8s.authtoken.urls", namespace="bcs_authtoken")),
    url(r"^api/hpa/projects/(?P<project_id>\w{32})/",
        include("backend.apps.hpa.urls", namespace="hpa")),
]

# 导入版本特定的urls
try:
    from backend.urls_bk import urlpatterns as urlpatterns_bk

    urlpatterns += urlpatterns_bk
except ImportError:
    pass

# vue urls 需要放到最后面
urlpatterns_vue = [
    # fallback to vue view
    url(r"^login_success.html", never_cache(LoginSuccessView.as_view())),
    url(r"^.*$", never_cache(VueTemplateView.as_view())),
]
urlpatterns += urlpatterns_vue
Example #58
0
from sys import exc_info
from traceback import format_exception
import logging
from django.views.decorators.csrf import csrf_exempt

log = logging.getLogger()


def pay_ship_info(request):
    return payship.base_pay_ship_info(request,
                                      config_get_group('PAYMENT_PAYPAL'),
                                      payship.simple_pay_ship_process_form,
                                      'shop/checkout/paypal/pay_ship.html')


pay_ship_info = never_cache(pay_ship_info)


def confirm_info(request):
    payment_module = config_get_group('PAYMENT_PAYPAL')

    try:
        order = Order.objects.from_request(request)
    except Order.DoesNotExist:
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return HttpResponseRedirect(url)

    tempCart = Cart.objects.from_request(request)
    if tempCart.numItems == 0 and not order.is_partially_paid:
        template = lookup_template(payment_module,
                                   'shop/checkout/empty_cart.html')
Example #59
0
            raise serializers.ValidationError(
                {'error': "Search term 'q' must be set"})
        return super(APISearchQueryBackend,
                     self).filter_queryset(request, queryset, view)


class APISearchView(SearchView):
    serializer_class = APIDocumentSerializer
    renderer_classes = [JSONRenderer]
    filter_backends = (
        APISearchQueryBackend,
        KeywordQueryBackend,
        TagGroupFilterBackend,
        APILanguageFilterBackend,
        HighlightFilterBackend,
    )


search = never_cache(APISearchView.as_view())


@waffle_flag('bc-signals')
@api_view(['POST'])
def bc_signal(request):
    serializer = BCSignalSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.validated_data,
                        status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #60
0
from django.views.decorators.cache import never_cache
from django.contrib.auth.models import User
from django.contrib.admin.views.main import ChangeList
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION

from rt_www.photogallery.models import Gallery, Photo, PhotoPlace
from rt_www.swimmers.models import Swimmer


def index(request):
    c = Context(request, {'cl': ChangeList(request, Gallery)})
    return render_to_response('photogallery/admin/index.html', {},
                              context_instance=c)


index = staff_member_required(never_cache(index))


def change_gallery(request, add=None, gid=None):
    new_data = errors = {}
    gallery = None
    context_args = {'aphotos': Photo.objects.filter(gallery__isnull=True)}
    if gid:
        context_args['cphotos'] = Photo.objects.filter(
            gallery__id__exact=int(gid))
        try:
            context_args['gallery'] = Gallery.objects.get(pk=gid)
        except Gallery.DoesNotExist:
            errors.append(_('The Gallery was not found'))

    if request.POST: