1 # -*- coding: utf-8 -*-
2 # This file is part of django-ssify, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See README.md for more information.
5 from __future__ import absolute_import, unicode_literals
6 from django.conf import settings
7 from django.core.urlresolvers import NoReverseMatch, reverse, resolve
8 from django.middleware.csrf import get_token, _sanitize_token
9 from django import template
10 from django.utils.translation import get_language
11 from ssify.decorators import ssi_variable
12 from ssify.variables import SsiVariable
15 from django.middleware.csrf import rotate_token
17 from django.middleware.csrf import _get_new_csrf_key
19 # Missing in Django 1.4
20 def rotate_token(request):
22 "CSRF_COOKIE_USED": True,
23 "CSRF_COOKIE": _get_new_csrf_key(),
28 register = template.Library()
31 @register.simple_tag(takes_context=True)
32 def ssi_include(context, name_, **kwargs):
34 Inserts an SSI include statement for an URL.
36 Works similarly to {% url %}, but only use keyword arguments are
39 In addition to just outputting the SSI include statement, it
40 remembers any request-info the included piece declares as needed.
43 b_kwargs = {'lang': get_language()}
46 for k, value in kwargs.items():
47 if isinstance(value, SsiVariable):
56 url = reverse(name_, kwargs=b_kwargs)
57 except NoReverseMatch:
59 url = reverse(name_, kwargs=b_kwargs)
60 view = resolve(url).func
62 for numstr, orig in subst.items():
63 url = url.replace(numstr, orig.as_var())
64 request = context['request']
66 # Remember the SSI vars the included view says it needs.
67 get_ssi_vars = getattr(view, 'get_ssi_vars', None)
69 pass_vars = get_ssi_vars(**kwargs)
71 if not isinstance(var, SsiVariable):
72 var = SsiVariable(*var)
73 request.ssi_vars_needed[var.name] = var
75 # Output the SSI include.
76 return "<!--#include file='%s'-->" % url
79 @ssi_variable(register, vary=('Cookie',))
80 def get_csrf_token(request):
82 CsrfViewMiddleware.process_view is never called for cached
83 responses, and we still need to provide a CSRF token as an
84 ssi variable, we must make sure here that the CSRF token
85 is in request.META['CSRF_COOKIE'].
88 token = get_token(request)
90 # CSRF token is already in place, just return it.
93 # Mimicking CsrfViewMiddleware.process_view.
95 token = _sanitize_token(request.COOKIES[settings.CSRF_COOKIE_NAME])
96 request.META['CSRF_COOKIE'] = token
98 # Create new CSRF token.
100 token = get_token(request)
105 @register.inclusion_tag('ssify/csrf_token.html', takes_context=True)
106 def csrf_token(context):
107 return {'request': context['request']}