Simple integration of Flask and WTForms, including CSRF, file upload and Recaptcha integration.

Overview
Comments
  • Validation (FileAllowed) issue upgrading 0.13.1 -> 0.14

    Validation (FileAllowed) issue upgrading 0.13.1 -> 0.14

    I upgraded Flask-WTF last night from 0.13.1 -> 0.14

    The issue I have is that when the FileField is blank (if the user chooses not to upload an image) then the validation fails. I do not require the field.

    class PostForm(FlaskForm):
        """Handle the input from the web for posts and replies."""
        body = TextAreaField('Post')
    
        upload = FileField('Upload', [
            FileAllowed(['gif', 'jpg', 'jpeg', 'png'],
                        'Only "gif", "jpg", "jpeg" and "png" files are supported')
        ])
    
        permission = RadioField('Permission', choices=[
            ('0', 'Public'),
            ('1', 'Pjuu'),
            ('2', 'Approved')
        ], default=0)
    
        def validate_body(self, field):
            if len(field.data.strip()) == 0 and not self.upload.data:
                raise ValidationError('Sorry. A message or an image is required.')
    
            if len(field.data.replace('\r\n', '\n')) > MAX_POST_LENGTH:
                raise ValidationError('Oh no! Posts can not be larger than '
                                      '{} characters'.format(MAX_POST_LENGTH))
    

    If I do this through my test suite all is okay using the following code:

    resp = self.client.post(
        url_for('posts.post'),
        data={
            'body': 'Test',
            'upload': '',
        },
        follow_redirects=True
    )
    

    The the post is successful. However if I make the request through Firefox (or Chrome) the validation is triggered saying I have an invalid format.

    Request body:

    Content-Type: multipart/form-data; boundary=---------------------------138689464934064453715802001
    Content-Length: 651
    
    -----------------------------138689464934064453715802001
    Content-Disposition: form-data; name="body"
    
    Test
    -----------------------------138689464934064453715802001
    Content-Disposition: form-data; name="csrf_token"
    
    IjY4YTZmYjNmNWM4MWJlNmVjMjc3Y2Y4YjBiMTM1Nzk3YTdhMGZkNjci.C1Vusg.RCp4SBZKai60nRqMGYP63i8JfXM
    -----------------------------138689464934064453715802001
    Content-Disposition: form-data; name="permission"
    
    0
    -----------------------------138689464934064453715802001
    Content-Disposition: form-data; name="upload"; filename=""
    Content-Type: application/octet-stream
    
    
    -----------------------------138689464934064453715802001--
    

    This was happening before I fixed the deprecation warnings that FileField is getting removed and to use the built-in WTForms FileField and after I changed the code to use this.

    I believe it's something to do with this change but can't find any documentation.

    I have had to revert the change as it stopped my site being usable.

    Thanks in advance

    bug 
    opened by docapotamus 13
  • Problem with importing wtforms inside html5.py file

    Problem with importing wtforms inside html5.py file

    I'm doing blog application to learn Python and Flask and I would like to launch it on Google App Engine. Unfortunately I have small problem with importing WTForms to the application. I'm currently using Flask 0.9, WTForms 1.0.1 and Flask-WTForms 0.8. I've added flaskext_wtf folder to root path of my project but I'm getting error from html5.py file.

    [code] File "/Users/lucas/Workspace/blog/flask_wtf/html5.py", line 1, in from wtforms import TextField File "/Users/lucas/Workspace/blog/flask/exthook.py", line 86, in load_module raise ImportError('No module named %s' % fullname) ImportError: No module named flask.ext.wtf.wtforms It looks like it tries to find wtforms inside the extension path instead of my project path. How can I inform the html5.py file to look for the wtforms in the root?[/code]

    Here are sources of my project - https://bitbucket.org/lucas_mendelowski/wblog/src

    opened by lcmen 13
  • Recaptcha validator passes Google the wrong IP

    Recaptcha validator passes Google the wrong IP

    This part of the validation code https://github.com/lepture/flask-wtf/blob/0598f96f70a695d5f84c05a9f4e11feff1d64caa/flask_wtf/recaptcha/validators.py#L43

    It's sending Google servers the wrong IP when the application is being proxied by something like nginx. Replacing request.remote_addr with request.access_route[-1] should fix the issue when being proxied.

    opened by Avamander 11
  • How to use the built-in translations provided by WTForms

    How to use the built-in translations provided by WTForms

    As describe in WTForms's documentation here, we can define a base class to set the default locale app-widely:

    from wtforms import Form
    
    class MyBaseForm(Form):
        class Meta:
            locales = ['es_ES', 'es']
    

    How to achieve this with Flask-WTF?

    opened by greyli 10
  • Why use referrer header for CSRF protection when you have sychronizer tokens?

    Why use referrer header for CSRF protection when you have sychronizer tokens?

    I'm new to the security game. I'd understood that a sychronizer token and a referrer header were doing basically the same thing, and that a sychronizer token is more robust. What does a referrer header add that a sychronizer token doesn't address?

    csrf 
    opened by knod 9
  • Fix forms & csrf_enabled deprecation doc

    Fix forms & csrf_enabled deprecation doc

    I had hard times understanding the deprecation of csrf_enabled. The only way I managed to do it was by reading form.py.

    Let's make the doc and deprecation message better :-)

    opened by JocelynDelalande 9
  • TypeError: b'' is not JSON serializable

    TypeError: b'' is not JSON serializable

    While using python 3.5.2 I got this error: TypeError: b'' is not JSON serializable So there is a problem with serializing a byte string For me I solved it this way editing csrf.py generate_csrf method: setattr(g, field_name, s.dumps(session[field_name].decode('utf-8'))) I added .decode('utf-8') to session[field_name] to make it work on python 3.

    I am not sure if this is an issue, but may be I helped somehow :)

    opened by yerassyl 9
  • Forms should distinguish which one was submitted

    Forms should distinguish which one was submitted

    I have a page with two forms, one contains two checkboxes and the other some text inputs. I construct each form with data from DB, e.g. the checkboxes are sometimes preselected. When I submit the other form, then the form with the checkboxes thinks that it has been submitted too (the form.is_submitted() only looks at request and checks that its post or put). Therefore both checkboxes are set unchecked, as the form thinks that it has been submitted, but no data for the checkboxes are found (=> which means that the checkboxes get prefilled with False).

    invalid 
    opened by bkabrda 9
  • Disabling CSRF check by default doesn't work for forms

    Disabling CSRF check by default doesn't work for forms

    I noticed that setting WTF_CSRF_CHECK_DEFAULT doesn't won't work if the endpoint validates any FlaskForm. The CSRF token doesn't seem to be checked, but when I check the my logs, they say that The CSRF token is missing. Would it be possible to completely disable the CSRF check for forms if WTF_CSRF_CHECK_DEFAULT is set to false?

    opened by james9909 8
  • Add csrf_token() to Jinja2 globals

    Add csrf_token() to Jinja2 globals

    Installing csrf_token() in the render context only causes errors in imported Jinja2 templates. It can be avoided by explicitly importing templates with context, but it is a cognitive burden to remember which templates should be imported with context and which don't have to be.

    todo 
    opened by clee704 8
  • Missing/Inconsistent imports

    Missing/Inconsistent imports

    Since this project imports "everything" from WTForms, it should import everything, not just some of the things. Or better drop importing anything and let the user decide. With the current design you need to update the imports every time something changes in WTForm. That makes this project hard to maintain.

    As an example: In the init.py file you import SQL Alchemy ext (if its installed), but you don't import everything from this extension. SQL Alchemy validators.py are missing. This leaves the us with a situation were we have to guess what is imported by the flask-wtf ext and what has to be imported directly from WTForms.

    I know this design decision is not made by the current project maintainer, but it should be re-evaluated to find a better solution.

    opened by simonklee 8
  • Setting WTF_CSRF_TIME_LIMIT to

    Setting WTF_CSRF_TIME_LIMIT to "None" is confusing

    In #258, it is made "clear" that WTF_CSRF_TIME_LIMIT can be set to None. But this isn't entirely clear because what is None in the context of an environment variable?

    Is it the absence of a value (presumably not, because then we get the default of 3600 seconds) - ?

    Is it an empty string? I think a better value for the behavior of "limited by user session" would be 0. This works better with configuration by environment variable.

    opened by malthe 0
  • Set JSONEncoder to json._default

    Set JSONEncoder to json._default

    • fixes #528

    Checklist:

    • [ ] Add tests that demonstrate the correct behavior of the change. Tests should fail without the change.
    • [ ] Add or update relevant docs, in the docs folder and in code.
    • [ ] Add an entry in docs/changes.rst summarizing the change and linking to the issue. Add .. versionchanged:: entries in any relevant code docs.
    opened by pythops 1
  • AttributeError: module 'quart.json' has no attribute 'JSONEncoder'

    AttributeError: module 'quart.json' has no attribute 'JSONEncoder'

    Bump into this error when I run pipenv run hypercorn --reload --quic-bind 0.0.0.0:4433 --certfile server.crt --keyfile server.key --bind 0.0.0.0:8080 src.main:app:

    <snip>
      File "/usr/src/PythonRestAPI/src/main.py", line 5, in <module>
        from flask_wtf.csrf import CSRFProtect, CSRFError
      File "/home/khteh/.local/share/virtualenvs/PythonRestAPI-JI5RzKtM/lib/python3.10/site-packages/flask_wtf/__init__.py", line 4, in <module>
        from .recaptcha import Recaptcha
      File "/home/khteh/.local/share/virtualenvs/PythonRestAPI-JI5RzKtM/lib/python3.10/site-packages/flask_wtf/recaptcha/__init__.py", line 1, in <module>
        from .fields import RecaptchaField
      File "/home/khteh/.local/share/virtualenvs/PythonRestAPI-JI5RzKtM/lib/python3.10/site-packages/flask_wtf/recaptcha/fields.py", line 3, in <module>
        from . import widgets
      File "/home/khteh/.local/share/virtualenvs/PythonRestAPI-JI5RzKtM/lib/python3.10/site-packages/flask_wtf/recaptcha/widgets.py", line 6, in <module>
        JSONEncoder = json.JSONEncoder
    AttributeError: module 'quart.json' has no attribute 'JSONEncoder'
    

    Environment:

    • Python version: 3.10.4
    • Flask-WTF version: 1.0.1
    • Flask version: 2.1.3 https://github.com/pallets/quart/issues/163
    opened by khteh 2
  • Validate the MIME type of files using FileAllowed

    Validate the MIME type of files using FileAllowed

    The flask_wtf.file.FileAllowed validator is very useful to validate the extension of an uploaded file, however, it is also important to validate the MIME type of the files as a user could easily change the extension of a file to violate this validator, thus breaking the integrity of the application. This is also a recommendation made by the HTML Standard:

    Authors are encouraged to specify both any MIME types and any corresponding extensions when looking for data in a specific format.

    In my opinion, the best place to specify the allowed MIME types is in the same list that receives this validator (just as the accept attribute of <input type="file"> works), for example:

    FileAllowed(upload_set=["doc", "docx", "xml", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"])
    
    opened by Tedpac 1
  • 'REMEMBER_COOKIE_HTTPONLY' causes

    'REMEMBER_COOKIE_HTTPONLY' causes "The CSRF tokens do not match" on mobile Firefox

    I've noticed that when enabling 'REMEMBER_COOKIE_HTTPONLY' within the config dict, it causes "The CSRF tokens do not match" in a POST request specifically for mobile Firefox. Non-mobile works just fine, as does Chromium.

    1. Set 'REMEMBER_COOKIE_HTTPONLY' within the config dict
    2. Go to a page that has a CSRF token and do a post request
    3. It fails with a "The CSRF tokens do not match"

    The POST request should complete just fine

    Environment:

    • Python version: 3.8.10
    • Flask-WTF version: 1.0.1
    • Flask version: 2.1.2
    opened by Lvl4Sword 0
  • The CSRF session token is missing.

    The CSRF session token is missing.

    Actual Behavior

    Everything works fine when the user is logged in, 400 Bad Request happens when I try to log the user in... same behavior is when I try to register a user (csrf_token is missing in the session when the user is anonymous)... have I missed something to configure maybe?

    Note: We are not using the wtforms, we have our own custom scheme.

    Thanks!

    Environment

    • Python version: Python 3.9.12
    • wtforms version: Flask-WTF==1.0.1
    • Flask version: Flask==2.0.3
    opened by TomeCirun 9
Releases(v1.0.1)
FlaskBB is a Forum Software written in Python using the micro framework Flask.

FlaskBB is a Forum Software written in Python using the micro framework Flask.

FlaskBB 2.3k Dec 30, 2022
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

null 4.6k Jan 5, 2023
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

null 4.6k Dec 31, 2022
A flexible forms validation and rendering library for Python.

WTForms WTForms is a flexible forms validation and rendering library for Python web development. It can work with whatever web framework and template

WTForms 1.4k Dec 31, 2022
Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.

django-widget-tweaks Tweak the form field rendering in templates, not in python-level form definitions. Altering CSS classes and HTML attributes is su

Jazzband 1.8k Jan 6, 2023
Easy and free contact form on your HTML page. No backend or JS required.

Easy and free contact form on your HTML page. No backend or JS required. ?? ??

0xDEADF00D 8 Dec 16, 2022
Toolkit for Pyramid, a Pylons Project, to add Authentication and Authorization using Velruse (OAuth) and/or a local database, CSRF, ReCaptcha, Sessions, Flash messages and I18N

Apex Authentication, Form Library, I18N/L10N, Flash Message Template (not associated with Pyramid, a Pylons project) Uses alchemy Authentication Authe

null 95 Nov 28, 2022
Bypass ReCaptcha: A Python script for dealing with recaptcha

Bypass ReCaptcha Bypass ReCaptcha is a Python script for dealing with recaptcha.

Marcos Camargo 1 Jan 11, 2022
SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).

Flask-SeaSurf SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF). CSRF vulnerabilities have been found in large and popular

Max Countryman 183 Dec 28, 2022
SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).

Flask-SeaSurf SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF). CSRF vulnerabilities have been found in large and popular

Max Countryman 183 Dec 28, 2022
Dead simple CSRF security middleware for Starlette ⭐ and Fast API ⚡

csrf-starlette-fastapi Dead simple CSRF security middleware for Starlette ⭐ and Fast API ⚡ Will work with either a <input type="hidden"> field or ajax

Nathaniel Sabanski 9 Nov 20, 2022
A proof of concept ai-powered Recaptcha v2 solver

Recaptcha Fullauto I've decided to open source my old Recaptcha v2 solver. My latest version will be opened sourced this summer. I am hoping this proj

Nate 60 Dec 20, 2022
reCaptchaBypasser For Bypass Any reCaptcha For Selenium Python

reCaptchaBypasser ' Usage : from selenium import webdriver from reCaptchaBypasser import reCaptchaScraper import time driver = webdriver.chrome(execu

Dr.Linux 8 Dec 17, 2022
An async Python library to automate solving ReCAPTCHA v2 by audio using Playwright.

Playwright nonoCAPTCHA An async Python library to automate solving ReCAPTCHA v2 by audio using Playwright. Disclaimer This project is for educational

Michael Mooney 69 Dec 28, 2022
Google Recaptcha solver.

byerecaptcha - Google Recaptcha solver. Model and some codes takes from embium's repository -Installation- pip install byerecaptcha -How to use- from

Vladislav Zenkevich 21 Dec 19, 2022
A simple telegram Bot, Upload Media File| video To telegram using the direct download link. (youtube, Mediafire, google drive, mega drive, etc)

URL-Uploader (Bot) A Bot Upload file|video To Telegram using given Links. Features: ?? Only Auth Users (AUTH_USERS) Can Use The Bot ?? Upload YTDL Sup

Hash Minner 18 Dec 17, 2022
A simple bot to upload file to various cloud servers.

Cloudsy Bot A simple bot to upload file to various cloud servers. Variables API_HASH Your API Hash from my.telegram.org API_ID Your API ID from my.tel

Flying Santas 8 Oct 31, 2022
flask-apispec MIT flask-apispec (🥉24 · ⭐ 520) - Build and document REST APIs with Flask and apispec. MIT

flask-apispec flask-apispec is a lightweight tool for building REST APIs in Flask. flask-apispec uses webargs for request parsing, marshmallow for res

Joshua Carp 617 Dec 30, 2022
This is an app that allows users to upload photos and display and store the photos in a file until the user deletes them.

Qt Photo App This is an app that allows users to upload photos and display and store the photos in a file until the user deletes them. Setup python3 -

Kathy Yang 5 Jan 22, 2022
dotsend is a web application which helps you to upload your large files and share file via link

dotsend is a web application which helps you to upload your large files and share file via link

Devocoe 0 Dec 3, 2022