Permalink
Browse files

Using Funfactory with Session CSRF

  • Loading branch information...
1 parent b6afa69 commit a17eba76fae6909e87b0f0ed149eca8d52e7e877 @davedash davedash committed with ozten Aug 29, 2011
@@ -1,10 +0,0 @@
-from django.conf import settings
-from django.utils import translation
-
-
-def i18n(request):
- return {'LANGUAGES': settings.LANGUAGES,
- 'LANG': settings.LANGUAGE_URL_MAP.get(translation.get_language())
- or translation.get_language(),
- 'DIR': 'rtl' if translation.get_language_bidi() else 'ltr',
- }
View
@@ -1,80 +0,0 @@
-import datetime
-import urllib
-import urlparse
-
-from django.conf import settings
-from django.template import defaultfilters
-from django.utils.html import strip_tags
-from django.utils.encoding import smart_str
-
-from jingo import register
-import jinja2
-
-from .urlresolvers import reverse
-
-
-# Yanking filters from Django.
-register.filter(strip_tags)
-register.filter(defaultfilters.timesince)
-register.filter(defaultfilters.truncatewords)
-
-
-@register.function
-def thisyear():
- """The current year."""
- return jinja2.Markup(datetime.date.today().year)
-
-
-@register.function
-def url(viewname, *args, **kwargs):
- """Helper for Django's ``reverse`` in templates."""
- return reverse(viewname, args=args, kwargs=kwargs)
-
-
-@register.filter
-def absolutify(url):
- """Takes a URL and prepends the SITE_URL"""
- protocol = settings.PROTOCOL
- hostname = settings.DOMAIN
- port = settings.PORT
- if (protocol, port) in (('https://', port == 443), ('http://', 80)):
- return ''.join(map(str, (protocol, hostname, url)))
- else:
- return ''.join(map(str, (protocol, hostname, ':', port, url)))
-
-
-@register.filter
-def urlparams(url_, hash=None, **query):
- """
- Add a fragment and/or query paramaters to a URL.
-
- New query params will be appended to exising parameters, except duplicate
- names, which will be replaced.
- """
- url = urlparse.urlparse(url_)
- fragment = hash if hash is not None else url.fragment
-
- # Use dict(parse_qsl) so we don't get lists of values.
- q = url.query
- query_dict = dict(urlparse.parse_qsl(smart_str(q))) if q else {}
- query_dict.update((k, v) for k, v in query.items())
-
- query_string = _urlencode([(k, v) for k, v in query_dict.items()
- if v is not None])
- new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params,
- query_string, fragment)
- return new.geturl()
-
-
-def _urlencode(items):
- """A Unicode-safe URLencoder."""
- try:
- return urllib.urlencode(items)
- except UnicodeEncodeError:
- return urllib.urlencode([(k, smart_str(v)) for k, v in items])
-
-
-@register.filter
-def urlencode(txt):
- """Url encode a path."""
- return urllib.quote_plus(txt)
View
@@ -1,58 +0,0 @@
-"""
-Taken from zamboni.amo.middleware.
-
-This is django-localeurl, but with mozilla style capital letters in
-the locale codes.
-"""
-
-import urllib
-
-from django.http import HttpResponsePermanentRedirect
-from django.utils.encoding import smart_str
-
-import tower
-
-from . import urlresolvers
-from .helpers import urlparams
-
-class LocaleURLMiddleware(object):
- """
- 1. Search for the locale.
- 2. Save it in the request.
- 3. Strip them from the URL.
- """
-
- def process_request(self, request):
- prefixer = urlresolvers.Prefixer(request)
- urlresolvers.set_url_prefix(prefixer)
- full_path = prefixer.fix(prefixer.shortened_path)
-
- if 'lang' in request.GET:
- # Blank out the locale so that we can set a new one. Remove lang
- # from the query params so we don't have an infinite loop.
- prefixer.locale = ''
- new_path = prefixer.fix(prefixer.shortened_path)
- query = dict((smart_str(k), request.GET[k]) for k in request.GET)
- query.pop('lang')
- return HttpResponsePermanentRedirect(urlparams(new_path, **query))
-
- if full_path != request.path:
- query_string = request.META.get('QUERY_STRING', '')
- full_path = urllib.quote(full_path.encode('utf-8'))
-
- if query_string:
- full_path = '%s?%s' % (full_path, query_string)
-
- response = HttpResponsePermanentRedirect(full_path)
-
- # Vary on Accept-Language if we changed the locale
- old_locale = prefixer.locale
- new_locale, _ = prefixer.split_path(full_path)
- if old_locale != new_locale:
- response['Vary'] = 'Accept-Language'
-
- return response
-
- request.path_info = '/' + prefixer.shortened_path
- request.locale = prefixer.locale
- tower.activate(prefixer.locale)
View
No changes.
No changes.
@@ -1,13 +0,0 @@
-from nose.tools import eq_
-
-from django.conf import settings
-
-from commons import helpers
-
-
-def test_absolutify():
- protocol = settings.PROTOCOL
- hostname = settings.DOMAIN
- port = settings.PORT
- expected = '%s%s:%s/boo' % (protocol, hostname, port)
- eq_(helpers.absolutify('/boo'), expected)
@@ -1,50 +0,0 @@
-import re
-from os import listdir
-from os.path import join, dirname
-
-import test_utils
-
-import manage
-
-
-class MigrationTests(test_utils.TestCase):
- """Sanity checks for the SQL migration scripts."""
-
- @staticmethod
- def _migrations_path():
- """Return the absolute path to the migration script folder."""
- return manage.path('migrations')
-
- def test_unique(self):
- """Assert that the numeric prefixes of the DB migrations are unique."""
- leading_digits = re.compile(r'^\d+')
- seen_numbers = set()
- path = self._migrations_path()
- for filename in listdir(path):
- match = leading_digits.match(filename)
- if match:
- number = match.group()
- if number in seen_numbers:
- self.fail('There is more than one migration #%s in %s.' %
- (number, path))
- seen_numbers.add(number)
-
- def test_innodb_and_utf8(self):
- """Make sure each created table uses the InnoDB engine and UTF-8."""
- # Heuristic: make sure there are at least as many "ENGINE=InnoDB"s as
- # "CREATE TABLE"s. (There might be additional "InnoDB"s in ALTER TABLE
- # statements, which are fine.)
- path = self._migrations_path()
- for filename in sorted(listdir(path)):
- with open(join(path, filename)) as f:
- contents = f.read()
- creates = contents.count('CREATE TABLE')
- engines = contents.count('ENGINE=InnoDB')
- encodings = (contents.count('CHARSET=utf8') +
- contents.count('CHARACTER SET utf8'))
- assert engines >= creates, ("There weren't as many "
- 'occurrences of "ENGINE=InnoDB" as of "CREATE TABLE" in '
- 'migration %s.' % filename)
- assert encodings >= creates, ("There weren't as many "
- 'UTF-8 declarations as "CREATE TABLE" occurrences in '
- 'migration %s.' % filename)
@@ -1,115 +0,0 @@
-from threading import local
-
-from django.conf import settings
-from django.core.urlresolvers import reverse as django_reverse
-from django.utils.translation.trans_real import parse_accept_lang_header
-
-
-# Thread-local storage for URL prefixes. Access with (get|set)_url_prefix.
-_local = local()
-
-
-def set_url_prefix(prefix):
- """Set the ``prefix`` for the current thread."""
- _local.prefix = prefix
-
-
-def get_url_prefix():
- """Get the prefix for the current thread, or None."""
- return getattr(_local, 'prefix', None)
-
-
-def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None):
- """Wraps Django's reverse to prepend the correct locale."""
- prefixer = get_url_prefix()
-
- if prefixer:
- prefix = prefix or '/'
- url = django_reverse(viewname, urlconf, args, kwargs, prefix)
- if prefixer:
- return prefixer.fix(url)
- else:
- return url
-
-
-def find_supported(test):
- return [settings.LANGUAGE_URL_MAP[x] for
- x in settings.LANGUAGE_URL_MAP if
- x.split('-', 1)[0] == test.lower().split('-', 1)[0]]
-
-
-class Prefixer(object):
-
- def __init__(self, request):
- self.request = request
- split = self.split_path(request.path_info)
- self.locale, self.shortened_path = split
-
- def split_path(self, path_):
- """
- Split the requested path into (locale, path).
-
- locale will be empty if it isn't found.
- """
- path = path_.lstrip('/')
-
- # Use partitition instead of split since it always returns 3 parts
- first, _, rest = path.partition('/')
-
- lang = first.lower()
- if lang in settings.LANGUAGE_URL_MAP:
- return settings.LANGUAGE_URL_MAP[lang], rest
- else:
- supported = find_supported(first)
- if len(supported):
- return supported[0], rest
- else:
- return '', path
-
- def get_language(self):
- """
- Return a locale code we support on the site using the
- user's Accept-Language header to determine which is best. This
- mostly follows the RFCs but read bug 439568 for details.
- """
- if 'lang' in self.request.GET:
- lang = self.request.GET['lang'].lower()
- if lang in settings.LANGUAGE_URL_MAP:
- return settings.LANGUAGE_URL_MAP[lang]
-
- if self.request.META.get('HTTP_ACCEPT_LANGUAGE'):
- best = self.get_best_language(
- self.request.META['HTTP_ACCEPT_LANGUAGE'])
- if best:
- return best
- return settings.LANGUAGE_CODE
-
- def get_best_language(self, accept_lang):
- """Given an Accept-Language header, return the best-matching language."""
- LUM = settings.LANGUAGE_URL_MAP
- PREFIXES = dict((x.split('-')[0], LUM[x]) for x in LUM)
- langs = dict(LUM)
- langs.update((k.split('-')[0], v) for k, v in LUM.items() if
- k.split('-')[0] not in langs)
- ranked = parse_accept_lang_header(accept_lang)
- for lang, _ in ranked:
- lang = lang.lower()
- if lang in langs:
- return langs[lang]
- pre = lang.split('-')[0]
- if pre in langs:
- return langs[pre]
- # Could not find an acceptable language.
- return False
-
- def fix(self, path):
- path = path.lstrip('/')
- url_parts = [self.request.META['SCRIPT_NAME']]
-
- if path.partition('/')[0] not in settings.SUPPORTED_NONLOCALES:
- locale = self.locale if self.locale else self.get_language()
- url_parts.append(locale)
-
- url_parts.append(path)
-
- return '/'.join(url_parts)
View
@@ -5,9 +5,8 @@
from django.db import models
from django.dispatch import receiver
-from commons.helpers import absolutify
-from commons.urlresolvers import reverse
-from manage import path
+from funfactory.urlresolvers import reverse
+from funfactory.utils import absolutify
class Invite(models.Model):
@@ -26,7 +25,6 @@ class Meta:
db_table = 'invite'
-
@receiver(models.signals.pre_save, sender=Invite)
def generate_code(sender, instance, raw, using, **kwargs):
if instance.code:
@@ -5,8 +5,8 @@
import test_utils
from nose.tools import eq_
-from commons.urlresolvers import reverse
-from manage import path
+from funfactory.urlresolvers import reverse
+from funfactory.manage import path
# The test data (below in module constants) must match data in
# directory/testsuite/mozillians-bulk-test-data.ldif
@@ -32,6 +32,7 @@ def pending_user_client():
client = test.Client()
url = reverse('login')
r = client.post(url, data, follow=True)
+ eq_(r.status_code, 200, "Something broke. Got a %d error." % r.status_code)
eq_(PENDING['email'], str(r.context['user']))
return client
@@ -3,7 +3,7 @@
from nose.tools import eq_
from pyquery import PyQuery as pq
-from commons.urlresolvers import reverse
+from funfactory.urlresolvers import reverse
from phonebook.models import Invite
from phonebook.tests import LDAPTestCase
@@ -6,7 +6,7 @@
from pyquery import PyQuery as pq
import test_utils
-from commons.urlresolvers import reverse
+from funfactory.urlresolvers import reverse
from phonebook.views import UNAUTHORIZED_DELETE
# The test data (below in module constants) must matches data in
View
@@ -13,7 +13,7 @@
from tower import ugettext as _
import commonware.log
-from commons.urlresolvers import reverse
+from funfactory.urlresolvers import reverse
from larper import UserSession, AdminSession, NO_SUCH_PERSON
from larper import MOZILLA_IRC_SERVICE_URI
from phonebook import forms
Oops, something went wrong.

0 comments on commit a17eba7

Please sign in to comment.