PageRenderTime 35ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/django-1.3/django/contrib/formtools/wizard.py

https://github.com/theosp/google_appengine
Python | 287 lines | 267 code | 0 blank | 20 comment | 1 complexity | d0e809cbf8391ffd851a8222efdd04c9 MD5 | raw file
  1. """
  2. FormWizard class -- implements a multi-page form, validating between each
  3. step and storing the form's state as HTML hidden fields so that no state is
  4. stored on the server side.
  5. """
  6. import cPickle as pickle
  7. from django import forms
  8. from django.conf import settings
  9. from django.contrib.formtools.utils import security_hash, form_hmac
  10. from django.http import Http404
  11. from django.shortcuts import render_to_response
  12. from django.template.context import RequestContext
  13. from django.utils.crypto import constant_time_compare
  14. from django.utils.hashcompat import md5_constructor
  15. from django.utils.translation import ugettext_lazy as _
  16. from django.utils.decorators import method_decorator
  17. from django.views.decorators.csrf import csrf_protect
  18. class FormWizard(object):
  19. # The HTML (and POST data) field name for the "step" variable.
  20. step_field_name="wizard_step"
  21. # METHODS SUBCLASSES SHOULDN'T OVERRIDE ###################################
  22. def __init__(self, form_list, initial=None):
  23. """
  24. Start a new wizard with a list of forms.
  25. form_list should be a list of Form classes (not instances).
  26. """
  27. self.form_list = form_list[:]
  28. self.initial = initial or {}
  29. # Dictionary of extra template context variables.
  30. self.extra_context = {}
  31. # A zero-based counter keeping track of which step we're in.
  32. self.step = 0
  33. def __repr__(self):
  34. return "step: %d\nform_list: %s\ninitial_data: %s" % (self.step, self.form_list, self.initial)
  35. def get_form(self, step, data=None):
  36. "Helper method that returns the Form instance for the given step."
  37. return self.form_list[step](data, prefix=self.prefix_for_step(step), initial=self.initial.get(step, None))
  38. def num_steps(self):
  39. "Helper method that returns the number of steps."
  40. # You might think we should just set "self.num_steps = len(form_list)"
  41. # in __init__(), but this calculation needs to be dynamic, because some
  42. # hook methods might alter self.form_list.
  43. return len(self.form_list)
  44. def _check_security_hash(self, token, request, form):
  45. expected = self.security_hash(request, form)
  46. if constant_time_compare(token, expected):
  47. return True
  48. else:
  49. # Fall back to Django 1.2 method, for compatibility with forms that
  50. # are in the middle of being used when the upgrade occurs. However,
  51. # we don't want to do this fallback if a subclass has provided their
  52. # own security_hash method - because they might have implemented a
  53. # more secure method, and this would punch a hole in that.
  54. # PendingDeprecationWarning <- left here to remind us that this
  55. # compatibility fallback should be removed in Django 1.5
  56. FormWizard_expected = FormWizard.security_hash(self, request, form)
  57. if expected == FormWizard_expected:
  58. # They didn't override security_hash, do the fallback:
  59. old_expected = security_hash(request, form)
  60. return constant_time_compare(token, old_expected)
  61. else:
  62. return False
  63. @method_decorator(csrf_protect)
  64. def __call__(self, request, *args, **kwargs):
  65. """
  66. Main method that does all the hard work, conforming to the Django view
  67. interface.
  68. """
  69. if 'extra_context' in kwargs:
  70. self.extra_context.update(kwargs['extra_context'])
  71. current_step = self.determine_step(request, *args, **kwargs)
  72. self.parse_params(request, *args, **kwargs)
  73. # Sanity check.
  74. if current_step >= self.num_steps():
  75. raise Http404('Step %s does not exist' % current_step)
  76. # Validate and process all the previous forms before instantiating the
  77. # current step's form in case self.process_step makes changes to
  78. # self.form_list.
  79. # If any of them fails validation, that must mean the validator relied
  80. # on some other input, such as an external Web site.
  81. # It is also possible that alidation might fail under certain attack
  82. # situations: an attacker might be able to bypass previous stages, and
  83. # generate correct security hashes for all the skipped stages by virtue
  84. # of:
  85. # 1) having filled out an identical form which doesn't have the
  86. # validation (and does something different at the end),
  87. # 2) or having filled out a previous version of the same form which
  88. # had some validation missing,
  89. # 3) or previously having filled out the form when they had more
  90. # privileges than they do now.
  91. #
  92. # Since the hashes only take into account values, and not other other
  93. # validation the form might do, we must re-do validation now for
  94. # security reasons.
  95. previous_form_list = []
  96. for i in range(current_step):
  97. f = self.get_form(i, request.POST)
  98. if not self._check_security_hash(request.POST.get("hash_%d" % i, ''),
  99. request, f):
  100. return self.render_hash_failure(request, i)
  101. if not f.is_valid():
  102. return self.render_revalidation_failure(request, i, f)
  103. else:
  104. self.process_step(request, f, i)
  105. previous_form_list.append(f)
  106. # Process the current step. If it's valid, go to the next step or call
  107. # done(), depending on whether any steps remain.
  108. if request.method == 'POST':
  109. form = self.get_form(current_step, request.POST)
  110. else:
  111. form = self.get_form(current_step)
  112. if form.is_valid():
  113. self.process_step(request, form, current_step)
  114. next_step = current_step + 1
  115. if next_step == self.num_steps():
  116. return self.done(request, previous_form_list + [form])
  117. else:
  118. form = self.get_form(next_step)
  119. self.step = current_step = next_step
  120. return self.render(form, request, current_step)
  121. def render(self, form, request, step, context=None):
  122. "Renders the given Form object, returning an HttpResponse."
  123. old_data = request.POST
  124. prev_fields = []
  125. if old_data:
  126. hidden = forms.HiddenInput()
  127. # Collect all data from previous steps and render it as HTML hidden fields.
  128. for i in range(step):
  129. old_form = self.get_form(i, old_data)
  130. hash_name = 'hash_%s' % i
  131. prev_fields.extend([bf.as_hidden() for bf in old_form])
  132. prev_fields.append(hidden.render(hash_name, old_data.get(hash_name, self.security_hash(request, old_form))))
  133. return self.render_template(request, form, ''.join(prev_fields), step, context)
  134. # METHODS SUBCLASSES MIGHT OVERRIDE IF APPROPRIATE ########################
  135. def prefix_for_step(self, step):
  136. "Given the step, returns a Form prefix to use."
  137. return str(step)
  138. def render_hash_failure(self, request, step):
  139. """
  140. Hook for rendering a template if a hash check failed.
  141. step is the step that failed. Any previous step is guaranteed to be
  142. valid.
  143. This default implementation simply renders the form for the given step,
  144. but subclasses may want to display an error message, etc.
  145. """
  146. return self.render(self.get_form(step), request, step, context={'wizard_error': _('We apologize, but your form has expired. Please continue filling out the form from this page.')})
  147. def render_revalidation_failure(self, request, step, form):
  148. """
  149. Hook for rendering a template if final revalidation failed.
  150. It is highly unlikely that this point would ever be reached, but See
  151. the comment in __call__() for an explanation.
  152. """
  153. return self.render(form, request, step)
  154. def security_hash(self, request, form):
  155. """
  156. Calculates the security hash for the given HttpRequest and Form instances.
  157. Subclasses may want to take into account request-specific information,
  158. such as the IP address.
  159. """
  160. return form_hmac(form)
  161. def determine_step(self, request, *args, **kwargs):
  162. """
  163. Given the request object and whatever *args and **kwargs were passed to
  164. __call__(), returns the current step (which is zero-based).
  165. Note that the result should not be trusted. It may even be a completely
  166. invalid number. It's not the job of this method to validate it.
  167. """
  168. if not request.POST:
  169. return 0
  170. try:
  171. step = int(request.POST.get(self.step_field_name, 0))
  172. except ValueError:
  173. return 0
  174. return step
  175. def parse_params(self, request, *args, **kwargs):
  176. """
  177. Hook for setting some state, given the request object and whatever
  178. *args and **kwargs were passed to __call__(), sets some state.
  179. This is called at the beginning of __call__().
  180. """
  181. pass
  182. def get_template(self, step):
  183. """
  184. Hook for specifying the name of the template to use for a given step.
  185. Note that this can return a tuple of template names if you'd like to
  186. use the template system's select_template() hook.
  187. """
  188. return 'forms/wizard.html'
  189. def render_template(self, request, form, previous_fields, step, context=None):
  190. """
  191. Renders the template for the given step, returning an HttpResponse object.
  192. Override this method if you want to add a custom context, return a
  193. different MIME type, etc. If you only need to override the template
  194. name, use get_template() instead.
  195. The template will be rendered with the following context:
  196. step_field -- The name of the hidden field containing the step.
  197. step0 -- The current step (zero-based).
  198. step -- The current step (one-based).
  199. step_count -- The total number of steps.
  200. form -- The Form instance for the current step (either empty
  201. or with errors).
  202. previous_fields -- A string representing every previous data field,
  203. plus hashes for completed forms, all in the form of
  204. hidden fields. Note that you'll need to run this
  205. through the "safe" template filter, to prevent
  206. auto-escaping, because it's raw HTML.
  207. """
  208. context = context or {}
  209. context.update(self.extra_context)
  210. return render_to_response(self.get_template(step), dict(context,
  211. step_field=self.step_field_name,
  212. step0=step,
  213. step=step + 1,
  214. step_count=self.num_steps(),
  215. form=form,
  216. previous_fields=previous_fields
  217. ), context_instance=RequestContext(request))
  218. def process_step(self, request, form, step):
  219. """
  220. Hook for modifying the FormWizard's internal state, given a fully
  221. validated Form object. The Form is guaranteed to have clean, valid
  222. data.
  223. This method should *not* modify any of that data. Rather, it might want
  224. to set self.extra_context or dynamically alter self.form_list, based on
  225. previously submitted forms.
  226. Note that this method is called every time a page is rendered for *all*
  227. submitted steps.
  228. """
  229. pass
  230. # METHODS SUBCLASSES MUST OVERRIDE ########################################
  231. def done(self, request, form_list):
  232. """
  233. Hook for doing something with the validated data. This is responsible
  234. for the final processing.
  235. form_list is a list of Form instances, each containing clean, valid
  236. data.
  237. """
  238. raise NotImplementedError("Your %s class has not defined a done() method, which is required." % self.__class__.__name__)