|
1 |
| -from wtforms import form, __version__ as wtforms_version |
| 1 | +from os import urandom |
| 2 | + |
| 3 | +from flask import session, current_app |
| 4 | +from wtforms import form |
| 5 | +from wtforms.csrf.session import SessionCSRF |
2 | 6 | from wtforms.fields.core import UnboundField
|
| 7 | + |
| 8 | +from flask_admin._compat import text_type |
3 | 9 | from flask_admin.babel import Translations
|
4 | 10 |
|
5 | 11 | from .fields import * # noqa: F403,F401
|
@@ -40,35 +46,24 @@ def recreate_field(unbound):
|
40 | 46 | return unbound.field_class(*unbound.args, **unbound.kwargs)
|
41 | 47 |
|
42 | 48 |
|
43 |
| -if int(wtforms_version[0]) > 1: |
44 |
| - # only WTForms 2+ has built-in CSRF functionality |
45 |
| - from os import urandom |
46 |
| - from flask import session, current_app |
47 |
| - from wtforms.csrf.session import SessionCSRF |
48 |
| - from flask_admin._compat import text_type |
49 |
| - |
50 |
| - class SecureForm(BaseForm): |
51 |
| - """ |
52 |
| - BaseForm with CSRF token generation and validation support. |
53 |
| -
|
54 |
| - Requires WTForms 2+ |
55 |
| - """ |
56 |
| - class Meta: |
57 |
| - csrf = True |
58 |
| - csrf_class = SessionCSRF |
59 |
| - _csrf_secret = urandom(24) |
60 |
| - |
61 |
| - @property |
62 |
| - def csrf_secret(self): |
63 |
| - secret = current_app.secret_key or self._csrf_secret |
64 |
| - if isinstance(secret, text_type): |
65 |
| - secret = secret.encode('utf-8') |
66 |
| - return secret |
67 |
| - |
68 |
| - @property |
69 |
| - def csrf_context(self): |
70 |
| - return session |
71 |
| -else: |
72 |
| - class SecureForm(BaseForm): |
73 |
| - def __init__(self, *args, **kwargs): |
74 |
| - raise Exception("SecureForm requires WTForms 2+") |
| 49 | +class SecureForm(BaseForm): |
| 50 | + """ |
| 51 | + BaseForm with CSRF token generation and validation support. |
| 52 | +
|
| 53 | + Requires WTForms 2+ |
| 54 | + """ |
| 55 | + class Meta: |
| 56 | + csrf = True |
| 57 | + csrf_class = SessionCSRF |
| 58 | + _csrf_secret = urandom(24) |
| 59 | + |
| 60 | + @property |
| 61 | + def csrf_secret(self): |
| 62 | + secret = current_app.secret_key or self._csrf_secret |
| 63 | + if isinstance(secret, text_type): |
| 64 | + secret = secret.encode('utf-8') |
| 65 | + return secret |
| 66 | + |
| 67 | + @property |
| 68 | + def csrf_context(self): |
| 69 | + return session |
0 commit comments