Example #1
0
def section(request, section_path=None, id_override=None):
    """
    A view of a section.
    """
    try:
        section = get_current_section()
    except MiddlewareNotUsed:
        lookup_from = id_override or request
        section = lookup_section(lookup_from)
    if section:
        return simple.direct_to_template(request, 
            template = "scaffold/section.html",
            extra_context = {'section': section}
        )        
    else:
        app_cache = AppCache()
        try:
            app_cache.get_app('flatpages')
            try:
                return flatpage(request, request.path_info)
            except Http404:
                pass
        except ImproperlyConfigured:
            pass
        raise Http404, "Section does not exist."
    def process_response(self, request, response):
        if response.status_code != 404:
            return response
        try:
            url = request.path_info

            if not url.startswith('/'):
                url = '/' + url

            f = get_object_or_404(
                FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID)

            request.breadcrumbs = (
                {'name': _(u'Home'), 'url': '/'},
                {'name': f.title, 'url': url})

            return flatpage(request, request.path_info)
        # Return the original response if any errors happened. Because this
        # is a middleware, we can't assume the errors will be caught elsewhere.
        except Http404:
            return response
        except:
            if settings.DEBUG:
                raise
            return response
Example #3
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        if request.path in self.allow_flatpages or '%s/' % request.path in self.allow_flatpages:
            from django.contrib.flatpages.views import flatpage
            return flatpage(request, request.path_info)

        if not self.enable_beta:
            #Do nothing is beta is not activated
            return

        invitation_code = request.COOKIES.get('invitation_code', '')
        in_beta, exists = InvitationCode.validate_code(invitation_code)
        whitelisted_modules = ['django.contrib.auth.views',
                               'django.contrib.admin.sites',
                               'django.views.static',
                               'django.contrib.staticfiles.views',
                               'hunger.views']

        short_name = view_func.__class__.__name__
        if short_name == 'function':
            short_name = view_func.__name__
        full_view_name = '%s.%s' % (view_func.__module__, short_name)

        #Check modules
        if self.always_allow_modules:
            whitelisted_modules += self.always_allow_modules

        #if view in module then ignore - except if view is signup confirmation
        if '%s' % view_func.__module__ in whitelisted_modules and not full_view_name == self.signup_confirmation_view:
            return

        #Check views
        if full_view_name in self.never_allow_views:
            return HttpResponseRedirect(self.redirect_url)

        if full_view_name in self.always_allow_views:
            return

        if full_view_name == self.signup_confirmation_view:
            #signup completed - deactivate invitation code
            request.session['beta_complete'] = True
            invite_used.send(sender=self.__class__, user=request.user, invitation_code=invitation_code)
            return

        if request.user.is_authenticated() and full_view_name not in self.signup_views:
            # User is logged in, or beta is not active, no need to check anything else.
            return

        if full_view_name in self.signup_views and in_beta:
            #if beta code is valid and trying to register then let them through
            return
        else:
            # next_page = request.META.get('REQUEST_URI')
            next_page = request.path
            if in_beta:
                return HttpResponseRedirect(self.signup_url + '?next=%s' % next_page)
            else:
                return HttpResponseRedirect(self.redirect_url + '?next=%s' % next_page)
Example #4
0
    def get(self, request, url):
        if not url.endswith('/') and settings.APPEND_SLASH:
            url += '/'

        from django.contrib.flatpages.views import flatpage, render_flatpage

        fp = get_object_or_404(FlatPage, url=url, sites=settings.SITE_ID)
        # if FlatPage.objects.filter(url=url, sites=settings.SITE_ID).exists():
        return flatpage(request, url)
Example #5
0
 def try_flatpage(self, request, path):
     '''See also FlatpageFallbackMiddleware.process_response'''
     try:
         return flatpage(request, path)
     except Http404:
         return None
     except:
         if settings.DEBUG:
             raise
         return None
Example #6
0
def contact(request):
    if request.POST.items():
        Record.objects.create(
            name = request.POST.get('name',''),
            lake_addr = request.POST.get('lake_addr',''),
            home_addr = request.POST.get('home_addr',''),
            email = request.POST.get('email',''),
            comments = request.POST.get('comments','')
        )
        return HttpResponseRedirect('/thankyou/')
    return flatpage(request,request.path)
Example #7
0
    def get(self, request, url):
        if not url.endswith('/') and settings.APPEND_SLASH:
            url += '/'

        from django.contrib.flatpages.views import flatpage, render_flatpage

        if not request.user.is_superuser or FlatPage.objects.filter(url='url', sites=settings.SITE_ID).exists():
            return flatpage(request, url)
        else:
            f = FlatPage(url=url)
            return render_flatpage(request, f)
Example #8
0
    def get(self, request, url):
        if not url.endswith('/') and settings.APPEND_SLASH:
            url += '/'

        from django.contrib.flatpages.views import flatpage, render_flatpage

        if not request.user.is_superuser or FlatPage.objects.filter(url='url', sites=settings.SITE_ID).exists():
            return flatpage(request, url)
        else:
            f = FlatPage(url=url)
            return render_flatpage(request, f)
Example #9
0
 def process_response(self, request, response):
     if response.status_code != 404:
         return response # No need to check for a flatpage for non-404 responses.
     try:
         return flatpage(request, request.path)
     # Return the original response if any errors happened. Because this
     # is a middleware, we can't assume the errors will be caught elsewhere.
     except:
         if DEBUG:
             raise
         return response
Example #10
0
 def process_response(self, request, response):
     if response.status_code != 404:
         return response  # No need to check for a flatpage for non-404 responses.
     try:
         return flatpage(request, request.path_info)
     # Return the original response if any errors happened. Because this
     # is a middleware, we can't assume the errors will be caught elsewhere.
     except Http404:
         return response
     except Exception:
         if settings.DEBUG:
             raise
         return response
Example #11
0
 def process_request(self, request):
     urlconf = getattr(request, 'urlconf', None)
     # Skip if we don't want to append slashes or there's a view for
     # the current URL.
     if (not settings.APPEND_SLASH or
             urlresolvers.is_valid_path(request.path_info, urlconf)):
         return None
     try:
         return flatpage(request, request.path_info)
     except Http404:
         return None
     except:
         if settings.DEBUG:
             raise
         return None
Example #12
0
def read_only_error(request, status=503):

    request.read_only_error = True

    if request.is_ajax():
        content = simplejson.dumps({'error': ReadOnlyError.message})
        return HttpResponse(content,
                            status=status,
                            content_type='application/json')

    try:
        return flatpage(request, '/readonly/', status=status)
    except Http404:
        content = ReadOnlyError.message
        return HttpResponse(content, status=status, content_type='text/plain')
Example #13
0
def read_only_error(request, status=503):

    request.read_only_error = True

    if request.is_ajax():
        content = simplejson.dumps({
            'error': ReadOnlyError.message
        })
        return HttpResponse(content, status=status, content_type='application/json')

    try:
        return flatpage(request, '/readonly/', status=status)
    except Http404:
        content = ReadOnlyError.message
        return HttpResponse(content, status=status, content_type='text/plain')
Example #14
0
def flatpage_translation(request, url):
    """
    Search for a flatpage translated into a different language
    EG returns index_tet for a request to index, if index_tet exists.
    """
    if not url.startswith('/'):
        url = '/' + url
    site_id = get_current_site(request).id
    try:
        return render_flatpage(request, FlatPage.objects.get(
            url='{}{}/'.format(url, request.LANGUAGE_CODE),
            sites=site_id))

    except FlatPage.DoesNotExist:
        return flatpage(request, url)
Example #15
0
def event(request, slug):
    """Video, description, and other metadata."""
    try:
        event = Event.objects.get(slug=slug)
    except Event.DoesNotExist:
        try:
            event = Event.objects.get(slug__iexact=slug)
        except Event.DoesNotExist:
            try:
                old_slug = EventOldSlug.objects.get(slug=slug)
                return redirect('main:event', slug=old_slug.event.slug)
            except EventOldSlug.DoesNotExist:
                # does it exist as a static page
                return flatpage(request, slug)

    if not can_view_event(event, request.user):
        return redirect('main:login')

    warning = None
    if event.status not in (Event.STATUS_SCHEDULED, Event.STATUS_PENDING):
        if not request.user.is_active:
            return http.HttpResponse('Event not scheduled')
        else:
            warning = "Event is not publicly visible - not scheduled."

    if event.approval_set.filter(approved=False).exists():
        if not request.user.is_active:
            return http.HttpResponse('Event not approved')
        else:
            warning = "Event is not publicly visible - not yet approved."

    template_tagged = ''
    if event.template and not event.is_upcoming():
        context = {
            'md5': lambda s: hashlib.md5(s).hexdigest(),
            'event': event,
            'request': request,
            'datetime': datetime.datetime.utcnow(),
            'vidly_tokenize': vidly.tokenize,
            'edgecast_tokenize': edgecast_tokenize,
        }
        if isinstance(event.template_environment, dict):
            context.update(event.template_environment)
        template = Template(event.template.content)
        try:
            template_tagged = template.render(context)
        except vidly.VidlyTokenizeError, msg:
            template_tagged = '<code style="color:red">%s</code>' % msg
Example #16
0
def event(request, slug):
    """Video, description, and other metadata."""
    try:
        event = Event.objects.get(slug=slug)
    except Event.DoesNotExist:
        try:
            event = Event.objects.get(slug__iexact=slug)
        except Event.DoesNotExist:
            try:
                old_slug = EventOldSlug.objects.get(slug=slug)
                return redirect('main:event', slug=old_slug.event.slug)
            except EventOldSlug.DoesNotExist:
                # does it exist as a static page
                return flatpage(request, slug)

    if not can_view_event(event, request.user):
        return redirect('main:login')

    warning = None
    if event.status != Event.STATUS_SCHEDULED:
        if not request.user.is_active:
            return http.HttpResponse('Event not scheduled')
        else:
            warning = "Event is not publicly visible - not scheduled."

    if event.approval_set.filter(approved=False).exists():
        if not request.user.is_active:
            return http.HttpResponse('Event not approved')
        else:
            warning = "Event is not publicly visible - not yet approved."
    template_tagged = ''
    if event.template and not event.is_upcoming():
        context = {
            'md5': lambda s: hashlib.md5(s).hexdigest(),
            'event': event,
            'request': request,
            'datetime': datetime.datetime.utcnow(),
            'vidly_tokenize': vidly.tokenize,
            'edgecast_tokenize': edgecast_tokenize,
        }
        if isinstance(event.template_environment, dict):
            context.update(event.template_environment)
        template = Template(event.template.content)
        try:
            template_tagged = template.render(context)
        except vidly.VidlyTokenizeError, msg:
            template_tagged = '<code style="color:red">%s</code>' % msg
Example #17
0
 def process_response(self, request, response):
     from django.contrib.flatpages.views import flatpage
     from django.http import Http404
     from django.conf import settings
     if response.status_code != 404:
         return response # No need to check for a flatpage for non-404 responses.
     try:
         path = request.path
         if path[-1:] != '/':
             path += '/'
         return flatpage(request, path)
     # Return the original response if any errors happened. Because this
     # is a middleware, we can't assume the errors will be caught elsewhere.
     except Http404:
         return response
     except:
         if settings.DEBUG:
             raise
         return response
Example #18
0
    def process_response(self, request, response):
        # Composer pages and flatpages only render on 404
        if response.status_code != 404:
            return response

        try:
            response = SlotView.as_view()(request)
            if isinstance(response, TemplateResponse):
                return response.render()
            else:
                return response
        except Http404:
            # Try the url with a slash appended.
            url = request.path_info
            if not url.endswith("/") and settings.APPEND_SLASH:
                url += "/"
                try:
                    f = get_object_or_404(Slot.permitted,
                                          url=url,
                                          slot_name="content")
                    return HttpResponsePermanentRedirect("%s/" % request.path)
                except Http404:
                    # No slot with slash appended. Fall through.
                    pass
            else:
                # Settings say do not append a slash.
                pass

        # Both "pass" conditions above means we did not find a suitable slot.
        if "flatpages" not in settings.INSTALLED_APPS:
            return response

        try:
            return flatpage(request, request.path_info)
        # Return the original response if any errors happened. Because this
        # is a middleware, we can't assume the errors will be caught elsewhere.
        except Http404:
            return response
        except Exception:
            if settings.DEBUG:
                raise
            return response
 def process_response(self, request, response):
     if response.status_code != 404:
         return response # No need to check for a flatpage for non-404 responses.
     try:
         # In old 1.0 we have a patch for flat pages, but as live app, we can't
         # touch in django code, so we clone flat page middleware with some
         # modifications :)
         # We need to get flat page, aniway, but if fail, fail silently. Also we
         # check for permissions, parts of code are from flat page view
         f = get_object_or_404(FlatPage, url__exact=request.path_info, sites__id__exact=settings.SITE_ID)
         if f: breadcrumbs_for_flatpages(request,f)
         return flatpage(request, request.path_info)
     # Return the original response if any errors happened. Because this
     # is a middleware, we can't assume the errors will be caught elsewhere.
     except Http404:
         return response
     except:
         if settings.DEBUG:
             raise
         return response
Example #20
0
 def process_response(self, request, response):
     if response.status_code != 404:
         return response  # No need to check for a flatpage for non-404 responses.
     try:
         # In old 1.0 we have a patch for flat pages, but as live app, we can't
         # touch in django code, so we clone flat page middleware with some
         # modifications :)
         # We need to get flat page, aniway, but if fail, fail silently. Also we
         # check for permissions, parts of code are from flat page view
         f = get_object_or_404(FlatPage,
                               url__exact=request.path_info,
                               sites__id__exact=settings.SITE_ID)
         if f: breadcrumbs_for_flatpages(request, f)
         return flatpage(request, request.path_info)
     # Return the original response if any errors happened. Because this
     # is a middleware, we can't assume the errors will be caught elsewhere.
     except Http404:
         return response
     except:
         if settings.DEBUG:
             raise
         return response
Example #21
0
def section(request, section_path=None, id_override=None):
    """
    A view of a section.
    """
    try:
        section = get_current_section()
    except MiddlewareNotUsed:
        lookup_from = id_override or request
        section = lookup_section(lookup_from)
    if section:
        return render_to_response("scaffold/section.html", {'section': section}, context_instance=RequestContext(request))
    else:
        app_cache = AppCache()
        try:
            app_cache.get_app('flatpages')
            try:
                return flatpage(request, request.path_info)
            except Http404:
                pass
        except ImproperlyConfigured:
            pass
        raise Http404, "Section does not exist."
Example #22
0
def section(request, section_path=None, id_override=None):
    """
    A view of a section.
    """
    try:
        section = get_current_section()
    except MiddlewareNotUsed:
        lookup_from = id_override or request
        section = lookup_section(lookup_from)
    if section:
        return simple.direct_to_template(request,
                                         template="scaffold/section.html",
                                         extra_context={'section': section})
    else:
        app_cache = AppCache()
        try:
            app_cache.get_app('flatpages')
            try:
                return flatpage(request, request.path_info)
            except Http404:
                pass
        except ImproperlyConfigured:
            pass
        raise Http404, "Section does not exist."
Example #23
0
def collection_introduction(request, slug="slug"):
    collection = get_object_or_404(models.Collection, slug=slug)
    return flatpage(request, collection.url_base+'/introduction/')
Example #24
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        if not self.enable_beta:
            return

        if (request.path in self.allow_flatpages or
            (getattr(settings, 'APPEND_SLASH', True) and
             '%s/' % request.path in self.allow_flatpages)):
            from django.contrib.flatpages.views import flatpage
            return flatpage(request, request.path_info)

        whitelisted_modules = ['django.contrib.auth.views',
                               'django.contrib.admin.sites',
                               'django.views.static',
                               'django.contrib.staticfiles.views']

        # All hunger views, except NotBetaView, are off limits until in beta
        whitelisted_views = ['hunger.views.NotBetaView',
                             'hunger.views.verify_invite',
                             'hunger.views.InvalidView']

        short_name = view_func.__class__.__name__
        if short_name == 'function':
            short_name = view_func.__name__
        view_name = self._get_view_name(request)

        full_view_name = '%s.%s' % (view_func.__module__, short_name)

        if self.always_allow_modules:
            whitelisted_modules += self.always_allow_modules

        if '%s' % view_func.__module__ in whitelisted_modules:
            return

        if self.always_allow_views:
            whitelisted_views += self.always_allow_views

        if (full_view_name in whitelisted_views or
                view_name in whitelisted_views):
            return

        if not request.user.is_authenticated():
            # Ask anonymous user to log in if trying to access in-beta view
            return redirect(setting('LOGIN_URL'))

        if request.user.is_staff:
            return

        # Prevent queries by caching in_beta status in session
        if request.session.get('hunger_in_beta'):
            return

        cookie_code = request.COOKIES.get('hunger_code')
        invitations = Invitation.objects.filter(
            Q(user=request.user) |
            Q(email=request.user.email)
            ).select_related('code')

        # User already in the beta - cache in_beta in session
        if any([i.used for i in invitations if i.invited]):
            request.session['hunger_in_beta'] = True
            return

        # User has been invited - use the invitation and place in beta.
        activates = [i for i in invitations if i.invited and not i.used]

        # Check for matching cookie code if available.
        if cookie_code:
            for invitation in activates:
                if invitation.code and invitation.code.code == cookie_code:
                    # Invitation may be attached to email
                    invitation.user = request.user
                    invitation.used = now()
                    invitation.save()
                    request.session['hunger_in_beta'] = True
                    request._hunger_delete_cookie = True
                    return

        # No cookie - let's just choose the first invitation if it exists
        if activates:
            invitation = activates[0]
            # Invitation may be attached to email
            invitation.user = request.user
            invitation.used = now()
            invitation.save()
            request.session['hunger_in_beta'] = True
            return

        if not cookie_code:
            if not invitations:
                invitation = Invitation(user=request.user)
                invitation.save()
            return redirect(self.redirect)

        # No invitation, all we have is this cookie code
        try:
            code = InvitationCode.objects.get(code=cookie_code,
                                              num_invites__gt=0)
        except InvitationCode.DoesNotExist:
            request._hunger_delete_cookie = True
            return redirect(reverse('hunger-invalid', args=(cookie_code,)))

        right_now = now()
        if code.private:
            # User is trying to use a valid private code, but has no
            # authority to use it (neither via username nor email)
            request._hunger_delete_cookie = True
            return redirect(reverse('hunger-invalid', args=(cookie_code,)))
        else:
            invitation = Invitation(user=request.user,
                                    code=code,
                                    invited=right_now,
                                    used=right_now)
            code.num_invites -= 1
        invitation.save()
        code.save()
        return
Example #25
0
 def cant_find_event(self, request, slug):
     """return an appropriate response if no event can be found"""
     return flatpage(request, slug)
Example #26
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        #print 0
        if not self.enable_beta:
            return

        #print 1
        if (request.path in self.allow_flatpages or
            (getattr(settings, 'APPEND_SLASH', True) and
             '%s/' % request.path in self.allow_flatpages)):
            from django.contrib.flatpages.views import flatpage
            #print "returning flatpage!"
            return flatpage(request, request.path_info)

        #print 2
        whitelisted_modules = ['django.contrib.auth.views',
                               'django.contrib.admin.sites',
                               'django.views.static',
                               'django.contrib.staticfiles.views',
                               'hunger.views']

        short_name = view_func.__class__.__name__
        if short_name == 'function':
            short_name = view_func.__name__
        view_name = self._get_view_name(request)

        full_view_name = '%s.%s' % (view_func.__module__, short_name)

        if self.always_allow_modules:
            whitelisted_modules += self.always_allow_modules

        if '%s' % view_func.__module__ in whitelisted_modules:
            #print "whitelisted"
            return

        #print 3
        if (full_view_name in self.always_allow_views or
                view_name in self.always_allow_views):
            return

        #print 4
        if not request.user.is_authenticated():
            return redirect(self.redirect)

        #print 5
        if request.user.is_staff:
            return
        #print 6

        # Prevent queries by caching in_beta status in session
        if request.session.get('hunger_in_beta'):
            return

        #print 7

        invitations = request.user.invitation_set.select_related('code')
        #print "USER", request.user, request.user.email
        #print "INVITATIONS", invitations

        if not invitations and not request.COOKIES.get('hunger_code'):
            #print "no invitations, no code for logged in user,"
            #print "make one and redirect"
            invitation = Invitation(
                user=request.user,
                email=request.user.email
            )
            invitation.save()
            return redirect(self.redirect)

        #print 8

        if any([i.used for i in invitations]):
            #print "some are used, therefore we are in Beta"
            request.session['hunger_in_beta'] = True
            return

        #print 9

        # User has been invited - use the invitation and place in beta.
        activates = [i for i in invitations if i.invited and not i.used]
        for invitation in activates:
            #print "let's activate"
            invitation.used = now()
            invitation.save()
            request.session['hunger_in_beta'] = True
            return

        #print 10
        # get from cookie, assume is authenticated and has email.
        invite = invite_from_cookie_and_email(request)
        if invite:
            invite.accept_invite(request.user)
            return
        else:
            return redirect(self.redirect)
Example #27
0
 def cant_find_event(self, request, slug):
     """return an appropriate response if no event can be found"""
     return flatpage(request, slug)
Example #28
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        if not self.enable_beta:
            return

        if (request.path in self.allow_flatpages
                or (getattr(settings, 'APPEND_SLASH', True)
                    and '%s/' % request.path in self.allow_flatpages)):
            from django.contrib.flatpages.views import flatpage
            return flatpage(request, request.path_info)

        whitelisted_modules = [
            'django.contrib.auth.views', 'django.contrib.admin.sites',
            'django.views.static', 'django.contrib.staticfiles.views'
        ]

        # All hunger views, except NotBetaView, are off limits until in beta
        whitelisted_views = [
            'hunger.views.NotBetaView', 'hunger.views.verify_invite',
            'hunger.views.InvalidView'
        ]

        short_name = view_func.__class__.__name__
        if short_name == 'function':
            short_name = view_func.__name__
        view_name = self._get_view_name(request)

        full_view_name = '%s.%s' % (view_func.__module__, short_name)

        if self.always_allow_modules:
            whitelisted_modules += self.always_allow_modules

        if '%s' % view_func.__module__ in whitelisted_modules:
            return

        if self.always_allow_views:
            whitelisted_views += self.always_allow_views

        if (full_view_name in whitelisted_views
                or view_name in whitelisted_views):
            return

        if not request.user.is_authenticated():
            # Ask anonymous user to log in if trying to access in-beta view
            return redirect(setting('LOGIN_URL'))

        if request.user.is_staff:
            return

        # Prevent queries by caching in_beta status in session
        if request.session.get('hunger_in_beta'):
            return

        cookie_code = request.COOKIES.get('hunger_code')
        invitations = Invitation.objects.filter(
            Q(user=request.user)
            | Q(email=request.user.email)).select_related('code')

        # User already in the beta - cache in_beta in session
        if any([i.used for i in invitations if i.invited]):
            request.session['hunger_in_beta'] = True
            return

        # User has been invited - use the invitation and place in beta.
        activates = [i for i in invitations if i.invited and not i.used]

        # Check for matching cookie code if available.
        if cookie_code:
            for invitation in activates:
                if invitation.code.code == cookie_code:
                    # Invitation may be attached to email
                    invitation.user = request.user
                    invitation.used = now()
                    invitation.save()
                    request.session['hunger_in_beta'] = True
                    request._hunger_delete_cookie = True
                    return

        # No cookie - let's just choose the first invitation if it exists
        if activates:
            invitation = activates[0]
            # Invitation may be attached to email
            invitation.user = request.user
            invitation.used = now()
            invitation.save()
            request.session['hunger_in_beta'] = True
            return

        if not cookie_code:
            if not invitations:
                invitation = Invitation(user=request.user)
                invitation.save()
            return redirect(self.redirect)

        # No invitation, all we have is this cookie code
        try:
            code = InvitationCode.objects.get(code=cookie_code,
                                              num_invites__gt=0)
        except InvitationCode.DoesNotExist:
            request._hunger_delete_cookie = True
            return redirect(reverse('hunger-invalid', args=(cookie_code, )))

        right_now = now()
        if code.private:
            # If we got here, we're trying to fix up a previous private
            # invitation to the correct user/email.
            invitation = Invitation.objects.filter(code=code)[0]
            invitation.user = request.user
            invitation.invited = right_now
            invitation.used = right_now
            code.num_invites = 0
        else:
            invitation = Invitation(user=request.user,
                                    code=code,
                                    invited=right_now,
                                    used=right_now)
            code.num_invites -= 1
        invitation.save()
        code.save()
        return
Example #29
0
def help(request):
    """Wrapper to admin lock requests to /admin/help/*.  Loads flatpage."""
    url = request.path.replace('/admin/help', '')
    return flatpage(request, url)
Example #30
0
def top_secret(request, url, lala=None):
    """
    A wrapping view that performs the permission check given in the decorator
    """
    print "secret!"
    return flatpage(request, url)
Example #31
0
 def info_page(req, **kwargs):
     return flatpage(req, **kwargs)
Example #32
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        if request.path in self.allow_flatpages or '%s/' % request.path in self.allow_flatpages:
            from django.contrib.flatpages.views import flatpage
            return flatpage(request, request.path_info)

        if not self.enable_beta:
            #Do nothing is beta is not activated
            return

        invitation_code = request.COOKIES.get('invitation_code', '')
        in_beta, exists = InvitationCode.validate_code(invitation_code)
        whitelisted_modules = [
            'django.contrib.auth.views', 'django.contrib.admin.sites',
            'django.views.static', 'django.contrib.staticfiles.views',
            'hunger.views'
        ]

        short_name = view_func.__class__.__name__
        if short_name == 'function':
            short_name = view_func.__name__
        full_view_name = '%s.%s' % (view_func.__module__, short_name)

        #Check modules
        if self.always_allow_modules:
            whitelisted_modules += self.always_allow_modules

        #if view in module then ignore - except if view is signup confirmation
        if '%s' % view_func.__module__ in whitelisted_modules and not full_view_name == self.signup_confirmation_view:
            error_log("whitelisted or signup confirmation view")
            return

        #Check views
        if full_view_name in self.never_allow_views:
            error_log("never allow views")
            return HttpResponseRedirect(self.redirect_url)

        if full_view_name in self.always_allow_views:
            error_log("always allow views")
            return

        if full_view_name == self.signup_confirmation_view or request.path == self.signup_confirmation_url:
            #signup completed - deactivate invitation code
            error_log("signup complete")
            request.session['beta_complete'] = True
            # invite_used.send(sender=self.__class__, user=request.user, invitation_code=invitation_code)
            return

        if request.user.is_authenticated(
        ) and full_view_name not in self.signup_views:
            error_log("user is authed")
            # User is logged in, or beta is not active, no need to check anything else.
            return

        if full_view_name == 'registration.views.register' and not in_beta:
            error_log("not in beta, trying to register")
            return HttpResponseRedirect(self.signup_url)

        if full_view_name in self.signup_views and in_beta:
            #if beta code is valid and trying to register then let them through
            error_log("has beta code trying to register")
            return
        else:
            # next_page = request.META.get('REQUEST_URI')
            next_page = request.path
            if in_beta:
                error_log("redirect to signup")
                return HttpResponseRedirect(
                    getattr(settings, 'BETA_SIGNUP_ACCOUNT_URL',
                            '/accounts/register'))
            else:
                error_log("redirect to redirect url")
                return HttpResponseRedirect(self.redirect_url +
                                            '?next=%s' % next_page)
Example #33
0
	def process_response(self, request, response):
		if response.status_code != 404:
			return response
		try:
			return flatpage(request, request.path_info)
		except Http404:
Example #34
0
def index(request):
    return flatpage(request, '/index/')
Example #35
0
 def process_response(self, request, response):
     if response.status_code != 404:
         return response  # No need to check for a flatpage for non-404 responses.
     else:
         return flatpage(request, '/404/')
Example #36
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        if not self.enable_beta:
            return

        if request.path in self.allow_flatpages or (
            getattr(settings, "APPEND_SLASH", True) and "%s/" % request.path in self.allow_flatpages
        ):
            from django.contrib.flatpages.views import flatpage

            return flatpage(request, request.path_info)

        whitelisted_modules = [
            "django.contrib.auth.views",
            "django.contrib.admin.sites",
            "django.views.static",
            "django.contrib.staticfiles.views",
        ]

        # All hunger views, except NotBetaView, are off limits until in beta
        whitelisted_views = ["hunger.views.NotBetaView", "hunger.views.verify_invite", "hunger.views.InvalidView"]

        short_name = view_func.__class__.__name__
        if short_name == "function":
            short_name = view_func.__name__
        view_name = self._get_view_name(request)

        full_view_name = "%s.%s" % (view_func.__module__, short_name)

        if self.always_allow_modules:
            whitelisted_modules += self.always_allow_modules

        if "%s" % view_func.__module__ in whitelisted_modules:
            return

        if self.always_allow_views:
            whitelisted_views += self.always_allow_views

        if full_view_name in whitelisted_views or view_name in whitelisted_views:
            return

        if not request.user.is_authenticated():
            # Ask anonymous user to log in if trying to access in-beta view
            return redirect(setting("LOGIN_URL"))

        if request.user.is_staff:
            return

        # Prevent queries by caching in_beta status in session
        if request.session.get("hunger_in_beta"):
            return

        cookie_code = request.COOKIES.get("hunger_code")
        invitations = Invitation.objects.filter(Q(user=request.user) | Q(email=request.user.email)).select_related(
            "code"
        )

        # User already in the beta - cache in_beta in session
        if any([i.used for i in invitations if i.invited]):
            request.session["hunger_in_beta"] = True
            return

        # User has been invited - use the invitation and place in beta.
        activates = [i for i in invitations if i.invited and not i.used]

        # Check for matching cookie code if available.
        if cookie_code:
            for invitation in activates:
                if invitation.code.code == cookie_code:
                    # Invitation may be attached to email
                    invitation.user = request.user
                    invitation.used = now()
                    invitation.save()
                    request.session["hunger_in_beta"] = True
                    request._hunger_delete_cookie = True
                    return

        # No cookie - let's just choose the first invitation if it exists
        if activates:
            invitation = activates[0]
            # Invitation may be attached to email
            invitation.user = request.user
            invitation.used = now()
            invitation.save()
            request.session["hunger_in_beta"] = True
            return

        if not cookie_code:
            if not invitations:
                invitation = Invitation(user=request.user)
                invitation.save()
            return redirect(self.redirect)

        # No invitation, all we have is this cookie code
        try:
            code = InvitationCode.objects.get(code=cookie_code, num_invites__gt=0)
        except InvitationCode.DoesNotExist:
            request._hunger_delete_cookie = True
            return redirect(reverse("hunger-invalid", args=(cookie_code,)))

        right_now = now()
        if code.private:
            # If we got here, we're trying to fix up a previous private
            # invitation to the correct user/email.
            invitation = Invitation.objects.filter(code=code)[0]
            invitation.user = request.user
            invitation.invited = right_now
            invitation.used = right_now
            code.num_invites = 0
        else:
            invitation = Invitation(user=request.user, code=code, invited=right_now, used=right_now)
            code.num_invites -= 1
        invitation.save()
        code.save()
        return
Example #37
0
def collection_about_staff(request, slug="slug"):
    collection = get_object_or_404(models.Collection, slug=slug)
    return flatpage(request, collection.url_base+'/about/staff/')
Example #38
0
def page(request, page):
    return flatpage(request, '/page/%s/' % page)