Skip to content
This repository has been archived by the owner on Aug 26, 2022. It is now read-only.

Commit

Permalink
Fix bug 1173352 - Add a new view to serve as a redirect point for fil…
Browse files Browse the repository at this point in the history
…es included relatively in code samples.

It'll redirect to the real file serving view.
  • Loading branch information
jezdez committed Jun 16, 2015
1 parent 87e9e31 commit 000644c
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 10 deletions.
9 changes: 2 additions & 7 deletions kuma/attachments/models.py
Expand Up @@ -4,10 +4,9 @@
from django.db import models

import jingo
from kuma.core.urlresolvers import reverse

from .managers import AttachmentManager
from .utils import attachment_upload_to
from .utils import attachment_upload_to, full_attachment_url


class Attachment(models.Model):
Expand Down Expand Up @@ -46,11 +45,7 @@ def get_absolute_url(self):
return ('attachments.attachment_detail', (), {'attachment_id': self.id})

def get_file_url(self):
uri = reverse('attachments.raw_file', kwargs={
'attachment_id': self.id,
'filename': self.current_revision.filename(),
})
return '%s%s%s' % (settings.PROTOCOL, settings.ATTACHMENT_HOST, uri)
return full_attachment_url(self.id, self.current_revision.filename())

def attach(self, document, user, name):
if self.id not in document.attachments.values_list('id', flat=True):
Expand Down
11 changes: 11 additions & 0 deletions kuma/attachments/utils.py
Expand Up @@ -2,12 +2,23 @@
from datetime import datetime
import hashlib

from django.conf import settings
from django.core.files import temp as tempfile
from django.template import loader
from django.utils import timezone
from django.utils.http import http_date
from django.utils.safestring import mark_safe

from kuma.core.urlresolvers import reverse


def full_attachment_url(attachment_id, filename):
path = reverse('attachments.raw_file', kwargs={
'attachment_id': attachment_id,
'filename': filename,
})
return '%s%s%s' % (settings.PROTOCOL, settings.ATTACHMENT_HOST, path)


def convert_to_http_date(dt):
"""
Expand Down
2 changes: 1 addition & 1 deletion kuma/wiki/migrations/0001_initial.py
Expand Up @@ -62,7 +62,7 @@ class Migration(migrations.Migration):
('file', models.ForeignKey(to='attachments.Attachment')),
],
options={
'db_table': 'attachments_documentattachement',
'db_table': 'attachments_documentattachment',
},
bases=(models.Model,),
),
Expand Down
2 changes: 1 addition & 1 deletion kuma/wiki/models.py
Expand Up @@ -165,7 +165,7 @@ class DocumentAttachment(models.Model):
name = models.TextField()

class Meta:
db_table = 'attachments_documentattachement'
db_table = 'attachments_documentattachment'


@register_live_index
Expand Down
60 changes: 60 additions & 0 deletions kuma/wiki/tests/test_views.py
Expand Up @@ -17,13 +17,16 @@
from django.db.models import Q
from django.test.client import (FakePayload, encode_multipart,
BOUNDARY, CONTENT_TYPE_RE, MULTIPART_CONTENT)
from django.test.utils import override_settings
from django.http import Http404
from django.utils.encoding import smart_str

from constance import config
from jingo.helpers import urlparams
from waffle.models import Flag, Switch

from kuma.attachments.models import Attachment
from kuma.attachments.utils import make_test_file
from kuma.authkeys.models import Key
from kuma.core.cache import memcache as cache
from kuma.core.models import IPBan
Expand Down Expand Up @@ -3231,6 +3234,63 @@ def test_code_sample_iframe_embed(self):
eq_(if3.attr('src'), '')


class CodeSampleViewFileServingTests(UserTestCase, WikiTestCase):

@override_constance_settings(
KUMA_WIKI_IFRAME_ALLOWED_HOSTS='^https?\:\/\/testserver',
WIKI_ATTACHMENT_ALLOWED_TYPES='text/plain')
@override_settings(ATTACHMENT_HOST='testserver')
def test_code_sample_file_serving(self):
self.client.login(username='admin', password='testpass')
# first let's upload a file
file_for_upload = make_test_file(content='Something something unique')
post_data = {
'title': 'An uploaded file',
'description': 'A unique experience for your file serving needs.',
'comment': 'Yadda yadda yadda',
'file': file_for_upload,
}
response = self.client.post(reverse('attachments.new_attachment'),
data=post_data)
eq_(response.status_code, 302)

# then build the document and revision we need to test
attachment = Attachment.objects.get(title='An uploaded file')
filename = attachment.current_revision.filename()
url_css = 'url("files/%(attachment_id)s/%(filename)s")' % {
'attachment_id': attachment.id,
'filename': filename,
}
doc, rev = doc_rev("""
<p>This is a page. Deal with it.</p>
<div id="sample1" class="code-sample">
<pre class="brush: html">Some HTML</pre>
<pre class="brush: css">.some-css { background: %s }</pre>
<pre class="brush: js">window.alert("HI THERE")</pre>
</div>
<p>test</p>
""" % url_css)

# then see of the code sample view has successfully found the sample
response = self.client.get(reverse('wiki.code_sample',
args=[doc.slug, 'sample1'],
locale='en-US'))
eq_(response.status_code, 200)
normalized = normalize_html(response.content)
ok_(url_css in normalized)

# and then we try if a redirect by the file serving view redirects
# to the main file serving view
response = self.client.get(reverse('wiki.raw_code_sample_file',
args=[doc.slug,
'sample1',
attachment.id,
filename],
locale='en-US'))
eq_(response.status_code, 302)
eq_(response['Location'], attachment.get_file_url())


class DeferredRenderingViewTests(UserTestCase, WikiTestCase):
"""Tests for the deferred rendering system and interaction with views"""
localizing_client = True
Expand Down
3 changes: 3 additions & 0 deletions kuma/wiki/urls.py
Expand Up @@ -54,6 +54,9 @@
url(r'^\$quick-review$',
views.quick_review,
name='wiki.quick_review'),
url(r'^\$samples/(?P<sample_id>.+)/files/(?P<attachment_id>\d+)/(?P<filename>.+)$',
views.raw_code_sample_file,
name='wiki.raw_code_sample_file'),
url(r'^\$samples/(?P<sample_id>.+)$',
views.code_sample,
name='wiki.code_sample'),
Expand Down
25 changes: 24 additions & 1 deletion kuma/wiki/views.py
Expand Up @@ -44,7 +44,7 @@

from kuma.attachments.forms import AttachmentRevisionForm
from kuma.attachments.models import Attachment
from kuma.attachments.utils import attachments_json
from kuma.attachments.utils import attachments_json, full_attachment_url
from kuma.core.cache import memcache
from kuma.core.decorators import (never_cache, login_required,
permission_required, superuser_required)
Expand Down Expand Up @@ -1912,6 +1912,29 @@ def code_sample(request, document_slug, document_locale, sample_id):
return render(request, 'wiki/code_sample.html', data)


@require_GET
@allow_CORS_GET
@xframe_options_exempt
@process_document_path
def raw_code_sample_file(request, document_slug, document_locale,
sample_id, attachment_id, filename):
"""
A view redirecting to the real file serving view of the attachments app.
This exists so the writers can use relative paths to files in the
code samples instead of hard coding he file serving URLs.
For example on a code sample with the URL:
https://mdn.mozillademos.org/fr/docs/Web/CSS/Tools/Outil_Selecteur_Couleurs_CSS$samples/ColorPIcker_Tool
This would allow having files referred to in the CSS as::
url("files/6067/canvas-controls.png")
"""
return redirect(full_attachment_url(attachment_id, filename))


@require_POST
def helpful_vote(request, document_path):
"""Vote for Helpful/Not Helpful document"""
Expand Down

0 comments on commit 000644c

Please sign in to comment.