예제 #1
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['has_users_edit_permission'] = acl.action_allowed(
            request, amo.permissions.USERS_EDIT)

        lookup_field = UserProfile.get_lookup_field(object_id)
        if lookup_field != 'pk':
            try:
                if lookup_field == 'email':
                    user = UserProfile.objects.get(email=object_id)
            except UserProfile.DoesNotExist:
                raise http.Http404
            url = request.path.replace(object_id, str(user.id), 1)
            if request.GET:
                url += '?' + request.GET.urlencode()
            return http.HttpResponsePermanentRedirect(url)

        return super(UserAdmin, self).change_view(
            request, object_id, form_url, extra_context=extra_context,
        )
예제 #2
0
    def wrapper(request, addon_id=None, app_slug=None, *args, **kw):
        """Provides an addon given either an addon id or an addon slug."""
        assert addon_id, 'Must provide addon id or slug'

        if addon_id and addon_id.isdigit():
            addon = get_object_or_404(qs(), id=addon_id)
            # Don't get in an infinite loop if addon.slug.isdigit().
            if addon.slug != addon_id:
                url = request.path.replace(addon_id, addon.slug, 1)

                if request.GET:
                    url += '?' + request.GET.urlencode()
                return http.HttpResponsePermanentRedirect(url)
        else:
            addon = get_object_or_404(qs(), slug=addon_id)
        # If the addon is unlisted it needs either an owner/viewer/dev/support,
        # or an unlisted addon reviewer.
        if not (addon.is_listed or owner_or_unlisted_reviewer(request, addon)):
            raise http.Http404
        return f(request, addon, *args, **kw)
예제 #3
0
def collection_detail(request, username, slug):
    collection = get_collection(request, username, slug)
    if not collection.listed:
        if not request.user.is_authenticated():
            return redirect_for_login(request)
        if not acl.check_collection_ownership(request, collection):
            raise PermissionDenied

    if request.GET.get('format') == 'rss':
        return http.HttpResponsePermanentRedirect(collection.feed_url())

    base = Addon.objects.valid() & collection.addons.all()
    filter = CollectionAddonFilter(request, base,
                                   key='sort', default='popular')
    notes = get_notes(collection)
    # Go directly to CollectionAddon for the count to avoid joins.
    count = CollectionAddon.objects.filter(
        Addon.objects.all().valid_q(
            amo.VALID_ADDON_STATUSES, prefix='addon__'),
        collection=collection.id)
    addons = paginate(request, filter.qs, per_page=15, count=count.count())

    if collection.author_id:
        qs = Collection.objects.listed().filter(author=collection.author)
        others = amo.utils.randslice(qs, limit=4, exclude=collection.id)
    else:
        others = []

    # `perms` is defined in django.contrib.auth.context_processors. Gotcha!
    user_perms = {
        'view_stats': acl.check_ownership(
            request, collection, require_owner=False),
    }

    tags = Tag.objects.filter(
        id__in=collection.top_tags) if collection.top_tags else []
    return render_cat(request, 'bandwagon/collection_detail.html',
                      {'collection': collection, 'filter': filter,
                       'addons': addons, 'notes': notes,
                       'author_collections': others, 'tags': tags,
                       'user_perms': user_perms})
예제 #4
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        lookup_field = Addon.get_lookup_field(object_id)
        if lookup_field != 'pk':
            try:
                if lookup_field == 'slug':
                    addon = self.queryset(request).all().get(slug=object_id)
                elif lookup_field == 'guid':
                    addon = self.queryset(request).get(guid=object_id)
            except Addon.DoesNotExist:
                raise http.Http404
            # Don't get in an infinite loop if addon.slug.isdigit().
            if addon.id and addon.id != object_id:
                url = request.path.replace(object_id, str(addon.id), 1)
                if request.GET:
                    url += '?' + request.GET.urlencode()
                return http.HttpResponsePermanentRedirect(url)

        return super().change_view(request,
                                   object_id,
                                   form_url,
                                   extra_context=extra_context)
예제 #5
0
    def process_request(self, request):
        # Bail if we already have trailing slash.
        if request.path.endswith('/'):
            return

        urlconf = getattr(request, 'urlconf', None)
        old_is_valid = lambda: urlresolvers.is_valid_path(request.path_info, urlconf)
        new_is_valid = lambda: urlresolvers.is_valid_path('%s/' % request.path_info, urlconf)

        # Bail for valid urls or slash version not being valid.
        if (old_is_valid() or not new_is_valid()):
            return

        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError("Can't redirect POST in AppendSlashMiddleware.")

        # Redirect rest:
        url = http_utils.urlquote('%s/' % request.path_info)
        if request.META.get('QUERY_STRING', ''):
            url += '?' + request.META['QUERY_STRING']
        return http.HttpResponsePermanentRedirect(url)
예제 #6
0
    def get(self, request, *args, **kwargs):
        m = get_object_or_404(AnalyticalDocument, pk=kwargs['file_id'])

        if m.upload:
            filepath = AWS_ANALYTICAL_MEDIA_LOCATION + '/' + str(m.upload)
            url = self.get_redirect_url(filepath=filepath)

            # The below is taken straight from RedirectView.
            if url:
                if self.permanent:
                    return http.HttpResponsePermanentRedirect(url)
                else:
                    return http.HttpResponseRedirect(url)
            else:
                logger.warning(
                    'Gone: %s',
                    self.request.path,
                    extra={'status_code': 410, 'request': self.request})
                return http.HttpResponseGone()
        else:
            raise http.Http404
예제 #7
0
 def post(self, *args, **kwargs):
     employee = Employee.objects.get(user=self.request.user)
     try:
         shift = Shift.objects.get(pk=kwargs['pk'])
         default = shift.Employee
         shift.Employee = employee
         shift.save()
     except Shift.DoesNotExist:
         return http.HttpResponsePermanentRedirect(self.url)
     date = shift.date
     shift_date = date + timedelta(days = 7)
     scheduleperiod = SchedulePeriod.objects.get(House=House.objects.get(name='Aoii'))
     end_date = scheduleperiod.end_date
     while shift_date <= end_date:
         shifts = Shift.objects.create(
             Type = shift.Type,
             Employee = employee,
             date = shift_date,
         )
         shift_date += timedelta(days = 7)
     return self.get(self, *args, **kwargs)
예제 #8
0
 def get(self, request, *args, **kwargs):
     download = get_object_or_404(PrivateDownload, id=kwargs['id'])
     user = request.user
     if user.is_authenticated and user.is_staff:
         url = self.get_redirect_url(filepath=download.private_file.name)
         # The below is taken straight from RedirectView.
         if url:
             if self.permanent:
                 return http.HttpResponsePermanentRedirect(url)
             else:
                 return http.HttpResponseRedirect(url)
         else:
             logger.warning('Gone: %s',
                            self.request.path,
                            extra={
                                'status_code': 410,
                                'request': self.request
                            })
             return http.HttpResponseGone()
     else:
         raise http.Http404
예제 #9
0
def blog_post(request, oid):
    if oid.endswith('/'):
        oid = oid[:-1]
    try:
        post = BlogItem.objects.get(oid=oid)
    except BlogItem.DoesNotExist:
        try:
            post = BlogItem.objects.get(oid__iexact=oid)
        except BlogItem.DoesNotExist:
            if oid == 'add':
                return redirect(reverse('add_post'))
            raise http.Http404(oid)

    ## Reasons for not being here
    if request.method == 'HEAD':
        return http.HttpResponse('')
    elif (request.method == 'GET' and
          (request.GET.get('replypath') or request.GET.get('show-comments'))):
        return http.HttpResponsePermanentRedirect(request.path)

    try:
        redis_increment('plog:misses', request)
    except Exception:
        logging.error('Unable to redis.zincrby', exc_info=True)

    data = {
        'post': post,
    }
    try:
        data['previous_post'] = post.get_previous_by_pub_date()
    except BlogItem.DoesNotExist:
        data['previous_post'] = None
    try:
        data['next_post'] = post.get_next_by_pub_date(pub_date__lt=utc_now())
    except BlogItem.DoesNotExist:
        data['next_post'] = None
    data['related'] = get_related_posts(post)
    data['show_buttons'] = True
    data['home_url'] = request.build_absolute_uri('/')
    return render(request, 'plog/post.html', data)
예제 #10
0
    def process_response(self, request, response):
        if response.status_code != 404:
            return response # No need to check for a redirect for non-404 responses.
        path = request.get_full_path()
        try:
            r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path)
        except Redirect.DoesNotExist:
            r = None
        if r is None and settings.APPEND_SLASH:
            # Try removing the trailing slash.
            try:
                r = Redirect.objects.get(site__id__exact=settings.SITE_ID,
                    old_path=path[:path.rfind('/')]+path[path.rfind('/')+1:])
            except Redirect.DoesNotExist:
                pass
        if r is not None:
            if r.new_path == '':
                return http.HttpResponseGone()
            return http.HttpResponsePermanentRedirect(r.new_path)

        # No redirect was found. Return the response.
        return response
예제 #11
0
    def wrapper(request, addon_id=None, *args, **kw):
        """Provides an addon instance to the view given addon_id, which can be
        an Addon pk, guid or a slug."""
        assert addon_id, 'Must provide addon id, guid or slug'

        qs = Addon.unfiltered.all

        lookup_field = Addon.get_lookup_field(addon_id)
        if lookup_field == 'pk':
            addon = get_object_or_404(qs(), pk=addon_id)
        else:
            addon = get_object_or_404(qs(), **{lookup_field: addon_id})
            # FIXME: this replace() is fragile, if the add-on slug appears
            # elsewhere in the URL it will break. Instead, we should probably
            # use `request.resolver_match` to rebuild the URL, replacing
            # `kwargs['addon_id']` if present by `addon.pk`.
            url = request.path.replace(addon_id, str(addon.pk), 1)
            if request.GET:
                url += '?' + request.GET.urlencode()
            return http.HttpResponsePermanentRedirect(url)

        return f(request, addon, *args, **kw)
예제 #12
0
    def get(self, request, *args, **kwargs):
        m = get_object_or_404(Recording, pk=kwargs['pk'])
        u = request.user
        p = get_person(request)

        audio_file = m.audio_file
        if m.audio_file_aac:
            audio_file = m.audio_file_aac

        key = '{0}:{0}:listen'.format(p.uuid, m.id)
        access = cache.get(key)
        # logger.debug('CAN VIEW:  {0} {1}'.format(key, access))

        if (u.is_authenticated() and u.is_staff) or (p
                                                     == m.person) or (access):
            try:
                url = audio_file.path
                url = audio_file.url
            except:
                try:
                    url = self.get_redirect_url(filepath=audio_file.name)
                except:
                    url = audio_file.url

            if url:
                if self.permanent:
                    return http.HttpResponsePermanentRedirect(url)
                else:
                    return http.HttpResponseRedirect(url)
            else:
                logger.warning('Gone: %s',
                               self.request.path,
                               extra={
                                   'status_code': 410,
                                   'request': self.request
                               })
                return http.HttpResponseGone()
        else:
            raise http.Http404
예제 #13
0
def impala_addon_detail(request, addon):
    """Add-ons details page dispatcher."""
    # addon needs to have a version and be valid for this app.
    if addon.type in request.APP.types:
        if addon.type == amo.ADDON_PERSONA:
            return persona_detail(request, addon)
        else:
            if not addon.current_version:
                raise http.Http404

            return impala_extension_detail(request, addon)
    else:
        # Redirect to an app that supports this type.
        try:
            new_app = [a for a in amo.APP_USAGE if addon.type in a.types][0]
        except IndexError:
            raise http.Http404
        else:
            prefixer = urlresolvers.get_url_prefix()
            prefixer.app = new_app.short
            return http.HttpResponsePermanentRedirect(
                reverse('addons.i_detail', args=[addon.slug]))
예제 #14
0
    def process_request(self, request):
        """
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        """

        # Check for denied User-Agents
        if request.META.has_key('HTTP_USER_AGENT'):
            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
                if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
                    return http.HttpResponseForbidden('<h1>Forbidden</h1>')

        # Check for a redirect based on settings.APPEND_SLASH and settings.PREPEND_WWW
        host = http.get_host(request)
        old_url = [host, request.path]
        new_url = old_url[:]
        if settings.PREPEND_WWW and old_url[0] and not old_url[0].startswith(
                'www.'):
            new_url[0] = 'www.' + old_url[0]
        # Append a slash if append_slash is set and the URL doesn't have a
        # trailing slash or a file extension.
        if settings.APPEND_SLASH and (old_url[1][-1] != '/') and (
                '.' not in old_url[1].split('/')[-1]):
            new_url[1] = new_url[1] + '/'
            if settings.DEBUG and request.method == 'POST':
                raise RuntimeError, "You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to %s%s (note the trailing slash), or set APPEND_SLASH=False in your Django settings." % (
                    new_url[0], new_url[1])
        if new_url != old_url:
            # Redirect
            if new_url[0]:
                newurl = "%s://%s%s" % (request.is_secure() and 'https'
                                        or 'http', new_url[0], new_url[1])
            else:
                newurl = new_url[1]
            if request.GET:
                newurl += '?' + request.GET.urlencode()
            return http.HttpResponsePermanentRedirect(newurl)

        return None
예제 #15
0
    def process_request(self, request):
        """Redirect legacy links to new ones

        Currently this middleware handles these types of legacy links:

        - /ak/?doc=osd.html -> /ak/osd/

        - /naujienos/?id=naujiena_1047 -> /naujienos/naujiena_1047/

        """
        if request.path == '/naujienos/' and 'id' in request.GET:
            url = '/naujienos/%s/' % request.GET['id']
        elif 'doc' in request.GET:
            doc = request.GET['doc']
            tail = doc[:-5] if doc.endswith('.html') else doc
            url = '%s%s/' % (request.path, tail)
        else:
            url = None

        if url:
            return http.HttpResponsePermanentRedirect(url)
        else:
            return None
예제 #16
0
    def process_request(self, request):
        if getattr(settings, 'APPEND_SLASH') and getattr(
                settings, 'REMOVE_SLASH'):
            raise ImproperlyConfigured(
                "APPEND_SLASH and REMOVE_SLASH may not both be True.")

        old_url = request.path_info  # path_info only includes path, query information
        if getattr(settings, 'REMOVE_SLASH', False) and old_url[-1] == "/":
            urlconf = getattr(request, 'urlconf', None)

            new_url = old_url[:-1]

            # If the url with a / would 404 and without a slash wouldn't
            if (not urlresolvers.is_valid_path(
                    old_url, urlconf)) and urlresolvers.is_valid_path(
                        new_url, urlconf):
                if settings.DEBUG and request.method == 'POST':
                    if old_url.startswith("/api/"):
                        return api.error(
                            "You made a POST request to a URL ending with a slash. Please repeat your request without the slash."
                        )

                    raise RuntimeError((
                        ""
                        "You called this URL via POST, but the URL ends in a "
                        "slash and you have REMOVE_SLASH set. Django can't "
                        "redirect to the non-slash URL while maintaining POST "
                        "data. Change your form to point to %s (without a "
                        "trailing slash), or set REMOVE_SLASH=False in your "
                        "Django settings.") % (new_url))

                # The ? and everything after
                query_data = re.match(
                    r'^[^?]*(\?.*)?$',
                    request.build_absolute_uri()).group(1) or ""

                return http.HttpResponsePermanentRedirect(new_url + query_data)
예제 #17
0
    def process_response(self, request, response):

        try:
            if response.status_code == 404:

                log('got 404')
                url = request.get_full_path()
                parts = urlsplit(url)

                if parts.scheme == '':
                    if request.is_secure():
                        scheme = 'https'
                    else:
                        scheme = 'http'
                else:
                    scheme = parts.scheme
                new_host = settings.REDIRECT_404_SERVER

                new_url = urlunsplit([
                    scheme, new_host, parts.path, parts.query, parts.fragment
                ])

                try:
                    response = http.HttpResponsePermanentRedirect(new_url)

                except Exception:
                    # just log it and return the exsting 404
                    log(f'url: {url}')
                    log('parts: %s' % repr(parts))
                    log(f'new url: {new_url}')
                    log(format_exc())

        except Exception:
            log(format_exc())
            raise

        return response
예제 #18
0
    def process_request(self, request):

        old_url = request.build_absolute_uri()
        # match any / followed by ? (query string present)
        # OR match / at the end of the string (no query string)
        trailing_slash_regexp = r'(\/(?=\?))|(\/$)'
        new_url = old_url

        if getattr(settings, 'APPEND_SLASH') and getattr(
                settings, 'REMOVE_SLASH'):
            raise ImproperlyConfigured(
                "APPEND_SLASH and REMOVE_SLASH may not both be True.")

        # Remove slash if REMOVE_SLASH is set and the URL has a trailing slash
        # and there is no pattern for the current path
        if getattr(settings, 'REMOVE_SLASH', False) and re.search(
                trailing_slash_regexp, old_url):
            urlconf = getattr(request, 'urlconf', None)
            if (not urlresolvers.is_valid_path(request.path_info, urlconf)
                ) and urlresolvers.is_valid_path(request.path_info[:-1],
                                                 urlconf):
                new_url = re.sub(trailing_slash_regexp, '', old_url)
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError((
                        ""
                        "You called this URL via POST, but the URL ends in a "
                        "slash and you have REMOVE_SLASH set. Django can't "
                        "redirect to the non-slash URL while maintaining POST "
                        "data. Change your form to point to %s (without a "
                        "trailing slash), or set REMOVE_SLASH=False in your "
                        "Django settings.") % (new_url))

        if new_url == old_url:
            # No redirects required.
            return
        return http.HttpResponsePermanentRedirect(new_url)
예제 #19
0
 def wrapper(request,
             addon_id=None,
             app_slug=None,
             inapp=None,
             *args,
             **kw):
     """Provides an addon given either an addon_id or app_slug."""
     assert addon_id or app_slug, 'Must provide addon_id or app_slug'
     get = lambda **kw: get_object_or_404(qs(), **kw)
     if addon_id and addon_id.isdigit():
         addon = get(id=addon_id)
         # Don't get in an infinite loop if addon.slug.isdigit().
         if addon.slug != addon_id:
             url = request.path.replace(addon_id, addon.slug)
             if request.GET:
                 url += '?' + request.GET.urlencode()
             return http.HttpResponsePermanentRedirect(url)
     elif addon_id:
         addon = get(slug=addon_id)
     elif app_slug:
         addon = get(app_slug=app_slug)
         if inapp:
             kw['inapp'] = get_list_or_404(InappPayment, name=inapp)[0].name
     return f(request, addon, *args, **kw)
예제 #20
0
    def process_request(self, request):
        host = request.get_host()
        old_url = [host, request.path]
        new_url = old_url[:]

        if (settings.REMOVE_WWW and old_url[0] and old_url[0].startswith('www.')):
            new_url[0] = old_url[0][4:]

        if new_url != old_url:
            try:
                urlresolvers.resolve(new_url[1])
            except urlresolvers.Resolver404:
                pass
            else:
                if new_url[0]:
                    newurl = "%s://%s%s" % (
                        request.is_secure() and 'https' or 'http',
                        new_url[0], urlquote(new_url[1]))
                else:
                    newurl = urlquote(new_url[1])
                if request.GET:
                    newurl += '?' + request.GET.urlencode()
                return http.HttpResponsePermanentRedirect(newurl)
        return None
예제 #21
0
    def process_request(self, request):
        host = request.get_host()
        old_url = [host, request.path]
        new_url = old_url[:]

        if host == 'de.pycon.org':
            if old_url[1].startswith('/2011/'):
                new_url[0] = '2011.de.pycon.org'
            else:
                new_url[0] = '2012.de.pycon.org'

        if new_url == old_url:
            return

        # Stolen from Django's APPEND_SLASH middleware
        if new_url[0]:
            newurl = "%s://%s%s" % (
                request.is_secure() and 'https' or 'http',
                new_url[0], urlquote(new_url[1]))
        else:
            newurl = urlquote(new_url[1])
        if request.META.get('QUERY_STRING', ''):
            newurl += '?' + request.META['QUERY_STRING']
        return http.HttpResponsePermanentRedirect(newurl)
예제 #22
0
 def RedirectBase(self):
     """Return a redirect to the main GRR page."""
     return http.HttpResponsePermanentRedirect(
         config_lib.CONFIG["AdminUI.url"])
예제 #23
0
 def show(self, request, redirect):
     if not redirect.redirect_to:
         return http.HttpResponseGone()
     return http.HttpResponsePermanentRedirect(redirect.redirect_to)
예제 #24
0
def permanent_redirect(url, *args, **kwargs):
    if '/' not in url or args or kwargs:
        url = urls.reverse(url, args=args, kwargs=kwargs)
    return http.HttpResponsePermanentRedirect(url)
예제 #25
0
    def process_request(self, request):
        """
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        """

        # Check for denied User-Agents
        if 'HTTP_USER_AGENT' in request.META:
            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
                if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
                    logger.warning('Forbidden (User agent): %s',
                                   request.path,
                                   extra={
                                       'status_code': 403,
                                       'request': request
                                   })
                    return http.HttpResponseForbidden('<h1>Forbidden</h1>')

        # Check for a redirect based on settings.APPEND_SLASH
        # and settings.PREPEND_WWW
        host = request.get_host()
        old_url = [host, request.path]
        new_url = old_url[:]

        if (settings.PREPEND_WWW and old_url[0]
                and not old_url[0].startswith('www.')):
            new_url[0] = 'www.' + old_url[0]

        # Append a slash if APPEND_SLASH is set and the URL doesn't have a
        # trailing slash and there is no pattern for the current path
        if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
            urlconf = getattr(request, 'urlconf', None)
            if (not urlresolvers.is_valid_path(request.path_info, urlconf)
                    and urlresolvers.is_valid_path("%s/" % request.path_info,
                                                   urlconf)):
                new_url[1] = new_url[1] + '/'
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError((
                        ""
                        "You called this URL via POST, but the URL doesn't end "
                        "in a slash and you have APPEND_SLASH set. Django can't "
                        "redirect to the slash URL while maintaining POST data. "
                        "Change your form to point to %s%s (note the trailing "
                        "slash), or set APPEND_SLASH=False in your Django "
                        "settings.") % (new_url[0], new_url[1]))

        if new_url == old_url:
            # No redirects required.
            return
        if new_url[0]:
            newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http',
                                    new_url[0], urlquote(new_url[1]))
        else:
            newurl = urlquote(new_url[1])
        if request.META.get('QUERY_STRING', ''):
            if six.PY3:
                newurl += '?' + request.META['QUERY_STRING']
            else:
                # `query_string` is a bytestring. Appending it to the unicode
                # string `newurl` will fail if it isn't ASCII-only. This isn't
                # allowed; only broken software generates such query strings.
                # Better drop the invalid query string than crash (#15152).
                try:
                    newurl += '?' + request.META['QUERY_STRING'].decode()
                except UnicodeDecodeError:
                    pass
        return http.HttpResponsePermanentRedirect(newurl)
예제 #26
0
    def process_request(self, request):
        # We've got a few different things to do here depending on settings.
        # TODO(termie): This should really have an associated diagram.

        level = logging.DEBUG

        host = request.get_host()
        request.mobile = False

        check_url = '%s%s (secure: %s)' % (host, request.get_full_path(),
                                           request.is_secure())
        logging.log(level, 'domain|checking| %s', check_url)

        # TODO(termie): Temporary fix
        if host == settings.GAE_DOMAIN:
            return

        # Queue requests seem to come in on a variety of subdomains...
        # TODO(termie): Temporary fix
        if request.META.get('HTTP_X_APPENGINE_QUEUENAME', None):
            return

        full_url = 'http://%s%s' % (settings.DOMAIN, request.get_full_path())
        # TODO(termie): this needs to be significantly smarter, a query string
        #               breaks this immediately
        full_url = full_url.rstrip('/')

        # check if we are at one of the urls that needs to be served over SSL
        # TODO(termie): these are hardcoded at the moment
        #               but it seems like incorporating into urls.py is overkill

        if (settings.SSL_LOGIN_ENABLED
                and (request.path == '/login' or request.path == '/join')):
            ssl_url = 'https://%s%s' % (settings.GAE_DOMAIN,
                                        request.get_full_path())

            if not request.is_secure():
                logging.log(level,
                            'domain|redirect| ssl on and login but insecure')
                return http.HttpResponsePermanentRedirect(ssl_url)

            if not host == settings.GAE_DOMAIN:
                logging.log(level,
                            'domain|redirect| ssl on and login but not gae')
                return http.HttpResponsePermanentRedirect(ssl_url)

            logging.log(level,
                        'domain|success | ssl on, secure request, login')
            return

        # we already handled any of the secure requests we intend on handling
        if request.is_secure():
            logging.log(level, 'domain|redirect| unhandled secure request')
            return http.HttpResponsePermanentRedirect(full_url)

        # shortcut if we are now in the proper place
        if host == settings.DOMAIN:
            logging.log(level, 'domain|success | on target domain')
            return

        # if we're not hosted we only have one domain to work with
        if not settings.HOSTED_DOMAIN_ENABLED and host != settings.DOMAIN:
            logging.log(level,
                        'domain|redirect| no hosted domain and %s != %s', host,
                        settings.DOMAIN)
            return http.HttpResponsePermanentRedirect(full_url)

        # if we don't have subdomains enabled, we better be at the real domain
        if not settings.SUBDOMAINS_ENABLED and host != settings.DOMAIN:
            logging.log(level,
                        'domain|redirect| subdomains disabled and %s != %s',
                        host, settings.DOMAIN)
            return http.HttpResponsePermanentRedirect(full_url)

        # TODO(termie): i'm sure this is the least efficient way to do any of this,
        #               but i don't want to waste brain cycles on it at the moment
        host_parts = host.split('.')
        expected_parts = settings.HOSTED_DOMAIN.split('.')

        while expected_parts:
            expected_last = expected_parts.pop()
            host_last = host_parts.pop()
            if expected_last != host_last:
                logging.log(level,
                            'domain|redirect| subdomain check, %s not in %s',
                            host, settings.HOSTED_DOMAIN)
                return http.HttpResponsePermanentRedirect(full_url)

        # the leftovers
        subdomain = '.'.join(host_parts)

        if subdomain == '':
            logging.log(level,
                        'domain|redirect| subdomain check, %s is emptry', host)
            return http.HttpResponsePermanentRedirect(full_url)

        # check for mobile and tag the request, if it is a double subdomain
        # strip off the .m and continue processing as normal
        elif subdomain == 'm':
            logging.log(level, 'domain|mobile| yup')
            request.mobile = True
        elif subdomain.endswith('.m'):
            logging.log(level, 'domain|mobile| stripping .m: %s', subdomain)
            request.mobile = True
            subdomain = subdomain[:-2]

        # if it is a subdomain we know about
        if subdomain == settings.DEFAULT_HOSTED_SUBDOMAIN:
            logging.log(level, 'domain|success | subdomain is default: %s',
                        subdomain)
            return
        elif subdomain in settings.INSTALLED_SUBDOMAINS:
            request.urlconf = settings.INSTALLED_SUBDOMAINS[subdomain]
            logging.log(level, 'domain|success | subdomain found: %s',
                        subdomain)
            return

        # if we don't have a wildcard we've got nowhere else to go
        if not settings.WILDCARD_USER_SUBDOMAINS_ENABLED:
            logging.log(
                level,
                'domain|redirect| subdomain not found and no wildcards: %s',
                subdomain)
            return http.HttpResponsePermanentRedirect(full_url)

        # otherwise this is probably a user page
        request.urlconf = 'actor.urls'
        request.subdomain = subdomain
        logging.log(level, 'domain|success | using actor wildcard: %s',
                    subdomain)
        return
예제 #27
0
 def get(self, request, *args, **kwargs):
     return http.HttpResponsePermanentRedirect(reverse('article:list'))
예제 #28
0
def search(request, tag_name=None):
    APP = request.APP
    types = (amo.ADDON_EXTENSION, amo.ADDON_THEME, amo.ADDON_DICT,
             amo.ADDON_SEARCH, amo.ADDON_LPAPP)

    category = request.GET.get('cat')

    if category == 'collections':
        extra_params = {'sort': {'newest': 'created'}}
    else:
        extra_params = None
    fixed = fix_search_query(request.GET, extra_params=extra_params)
    if fixed is not request.GET:
        return http.HttpResponsePermanentRedirect(
            urlparams(request.path, **fixed))

    facets = request.GET.copy()

    # In order to differentiate between "all versions" and an undefined value,
    # we use "any" instead of "" in the frontend.
    if 'appver' in facets and facets['appver'] == 'any':
        facets['appver'] = ''

    form = ESSearchForm(facets or {})
    form.is_valid()  # Let the form try to clean data.

    form_data = form.cleaned_data
    if tag_name:
        form_data['tag'] = tag_name

    if category == 'collections':
        return _collections(request)
    elif category == 'themes' or form_data.get('atype') == amo.ADDON_PERSONA:
        return _personas(request)

    sort, extra_sort = split_choices(form.sort_choices, 'created')
    if form_data.get('atype') == amo.ADDON_SEARCH:
        # Search add-ons should not be searched by ADU, so replace 'Users'
        # sort with 'Weekly Downloads'.
        sort, extra_sort = list(sort), list(extra_sort)
        sort[1] = extra_sort[1]
        del extra_sort[1]

    # Perform search, using aggregation so that we can build the facets UI.
    # Note that we don't need to aggregate on platforms, that facet it built
    # from our constants directly, using the current application for this
    # request (request.APP).
    appversion_field = 'current_version.compatible_apps.%s.max' % APP.id
    qs = (Addon.search_public().filter(app=APP.id).aggregate(
        tags={'terms': {
            'field': 'tags'
        }},
        appversions={'terms': {
            'field': appversion_field
        }},
        categories={'terms': {
            'field': 'category',
            'size': 200
        }}))

    filters = ['atype', 'appver', 'cat', 'sort', 'tag', 'platform']
    mapping = {
        'users': '-average_daily_users',
        'rating': '-bayesian_rating',
        'created': '-created',
        'name': 'name_sort',
        'downloads': '-weekly_downloads',
        'updated': '-last_updated',
        'hotness': '-hotness'
    }
    qs = _filter_search(request, qs, form_data, filters, mapping, types=types)

    pager = amo.utils.paginate(request, qs)

    ctx = {
        'is_pjax': request.META.get('HTTP_X_PJAX'),
        'pager': pager,
        'query': form_data,
        'form': form,
        'sort_opts': sort,
        'extra_sort_opts': extra_sort,
        'sorting': sort_sidebar(request, form_data, form),
        'sort': form_data.get('sort'),
    }
    if not ctx['is_pjax']:
        aggregations = pager.object_list.aggregations
        ctx.update({
            'tag':
            tag_name,
            'categories':
            category_sidebar(request, form_data, aggregations),
            'platforms':
            platform_sidebar(request, form_data),
            'versions':
            version_sidebar(request, form_data, aggregations),
            'tags':
            tag_sidebar(request, form_data, aggregations),
        })
    return render(request, 'search/results.html', ctx)
예제 #29
0
def search(request, tag_name=None, template=None):
    APP = request.APP
    types = (amo.ADDON_EXTENSION, amo.ADDON_THEME, amo.ADDON_DICT,
             amo.ADDON_SEARCH, amo.ADDON_LPAPP)

    category = request.GET.get('cat')

    if category == 'collections':
        extra_params = {'sort': {'newest': 'created'}}
    else:
        extra_params = None
    fixed = fix_search_query(request.GET, extra_params=extra_params)
    if fixed is not request.GET:
        return http.HttpResponsePermanentRedirect(
            urlparams(request.path, **fixed))

    form = ESSearchForm(request.GET or {})
    form.is_valid()  # Let the form try to clean data.

    query = form.cleaned_data
    if tag_name:
        query['tag'] = tag_name

    if category == 'collections':
        return _collections(request)
    elif category == 'personas' or query.get('atype') == amo.ADDON_PERSONA:
        return _personas(request)

    sort, extra_sort = split_choices(form.sort_choices, 'created')
    if query.get('atype') == amo.ADDON_SEARCH:
        # Search add-ons should not be searched by ADU, so replace 'Users'
        # sort with 'Weekly Downloads'.
        sort, extra_sort = list(sort), list(extra_sort)
        sort[1] = extra_sort[1]
        del extra_sort[1]

    qs = (Addon.search().filter(
        status__in=amo.REVIEWED_STATUSES, is_disabled=False, app=APP.id).facet(
            tags={'terms': {
                'field': 'tag'
            }},
            platforms={'terms': {
                'field': 'platform'
            }},
            appversions={'terms': {
                'field': 'appversion.%s.max' % APP.id
            }},
            categories={'terms': {
                'field': 'category',
                'size': 200
            }}))

    filters = ['atype', 'appver', 'cat', 'sort', 'tag', 'platform']
    mapping = {
        'users': '-average_daily_users',
        'rating': '-bayesian_rating',
        'created': '-created',
        'name': 'name_sort',
        'downloads': '-weekly_downloads',
        'updated': '-last_updated',
        'hotness': '-hotness'
    }
    qs = _filter_search(request, qs, query, filters, mapping, types=types)

    pager = amo.utils.paginate(request, qs)

    ctx = {
        'is_pjax': request.META.get('HTTP_X_PJAX'),
        'pager': pager,
        'query': query,
        'form': form,
        'sort_opts': sort,
        'extra_sort_opts': extra_sort,
        'sorting': sort_sidebar(request, query, form),
        'sort': query.get('sort'),
    }
    if not ctx['is_pjax']:
        facets = pager.object_list.facets
        ctx.update({
            'tag': tag_name,
            'categories': category_sidebar(request, query, facets),
            'platforms': platform_sidebar(request, query, facets),
            'versions': version_sidebar(request, query, facets),
            'tags': tag_sidebar(request, query, facets),
        })
    return jingo.render(request, template, ctx)
예제 #30
0
파일: views.py 프로젝트: superduper/zamboni
def persona_redirect(request, persona_id):
    persona = get_object_or_404(Persona, persona_id=persona_id)
    to = reverse('addons.detail', args=[persona.addon.slug])
    return http.HttpResponsePermanentRedirect(to)