def _validate_csrf(csrf_impl, field): form = Form() csrf_impl.form_meta = form.meta try: SessionCSRF.validate_csrf_token(csrf_impl, None, field) except ValidationError: return False return True
def init_app(self, app): self._app = app self.csrf_impl = SessionCSRF() self.generate_csrf = partial(_generate_csrf, self.csrf_impl) self.validate_csrf = partial(_validate_csrf, self.csrf_impl) app.jinja_env.globals['csrf_token'] = self.generate_csrf app.config.setdefault('WTF_CSRF_HEADERS', ['X-CSRFToken', 'X-CSRF-Token']) app.config.setdefault('WTF_CSRF_SSL_STRICT', True) app.config.setdefault('WTF_CSRF_ENABLED', True) app.config.setdefault('WTF_CSRF_CHECK_DEFAULT', True) app.config.setdefault('WTF_CSRF_METHODS', ['POST', 'PUT', 'PATCH']) # expose csrf_token as a helper in all templates @app.context_processor def csrf_token(): return dict(csrf_token=self.generate_csrf) @app.before_request def _csrf_protect(): # many things come from django.middleware.csrf if not app.config['WTF_CSRF_ENABLED']: return if not app.config['WTF_CSRF_CHECK_DEFAULT']: return if request.method not in app.config['WTF_CSRF_METHODS']: return if self._exempt_views or self._exempt_blueprints: if not request.endpoint: return view = app.view_functions.get(request.endpoint) if not view: return dest = '%s.%s' % (view.__module__, view.__name__) if dest in self._exempt_views: return if request.blueprint in self._exempt_blueprints: return self.protect()
def build_csrf(self, form): """ Build a CSRF implementation. This is called once per form instance. The default implementation builds the class referenced to by :attr:`csrf_class` with zero arguments. If `csrf_class` is ``None``, will instead use the default implementation :class:`wtforms.csrf.session.SessionCSRF`. :param form: The form. :return: A CSRF implementation. """ if self.csrf_class is not None: return self.csrf_class() from wtforms.csrf.session import SessionCSRF return SessionCSRF()
def _generate_csrf(csrf_impl): form = Form() csrf_impl.form_meta = form.meta return SessionCSRF.generate_csrf_token(csrf_impl, None)