@view_config(renderer="templates/form.pt", name="pyramid_csrf_demo")
@demonstrate("Pyramid CSRF Demo (using schema binding)")
def pyramid_csrf_demo(self):
@colander.deferred
def deferred_csrf_default(node, kw):
request = kw.get("request")
csrf_token = request.session.get_csrf_token()
return csrf_token
@colander.deferred
def deferred_csrf_validator(node, kw):
def validate_csrf(node, value):
request = kw.get("request")
csrf_token = request.session.get_csrf_token()
if value != csrf_token:
raise ValueError("Bad CSRF token")
return validate_csrf
class CSRFSchema(colander.Schema):
csrf = colander.SchemaNode(
colander.String(),
default=deferred_csrf_default,
validator=deferred_csrf_validator,
widget=deform.widget.HiddenWidget(),
)
# subclass from CSRFSchema everywhere to get CSRF validation
class MySchema(CSRFSchema):
text = colander.SchemaNode(
colander.String(),
validator=colander.Length(max=100),
widget=deform.widget.TextInputWidget(),
description="Enter some text",
)
schema = MySchema().bind(request=self.request)
form = deform.Form(schema, buttons=("submit",))
return self.render_form(form)