maxcountryman / flask-seasurf

SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).
http://readthedocs.org/docs/flask-seasurf/
Other
190 stars 49 forks source link

Flask-WTForms example doesn't make sense #66

Closed kkinder closed 6 years ago

kkinder commented 7 years ago

I'm looking at the wtforms example:

class SeaSurfForm(Form):
    @staticmethod
    @app.before_request
    def add_csrf():
        csrf_name = app.config.get('CSRF_COOKIE_NAME', '_csrf_token')
        setattr(SeaSurfForm,
                csrf_name,
                HiddenField(default=getattr(g, csrf_name)))

Why would you set the default value of the hidden variable to the name of the cookie, as fetched from flask.g? That doesn't make sense.

maxcountryman commented 7 years ago

It looks to me like the default value of the hidden field will be the result of calling getattr on g, using the cookie's name as the desired attribute.

What doesn't make sense to you?

kkinder commented 7 years ago

Well, let's say for example that my CSRF cookie is named, "best_sites_dot_whatnot_csrf". That's the cookie name, in the browser.

Why would that also be on flask.k as flask.g.best_sites_dot_whatnot_csrf?

It's also somewhat problematic because the default value might well be assigned before seasurf is initialized. I found it more reliable to not specify a default at all, then put the value in the constructor:

    def __init__(self, formdata=_Auto, obj=None, prefix='', csrf_context=None, secret_key=None, csrf_enabled=None, *args, **kwargs):
        super(SeaSurfForm, self).__init__(formdata, obj, prefix, csrf_context, secret_key, csrf_enabled, *args, **kwargs)

        csrf_name = app.config.get('CSRF_COOKIE_NAME', 'csrf_token')

        getattr(self, csrf_name).data = csrf._get_token()

Does that make sense?