Blame view

flaskr/forms.py 9.15 KB
37fd3b20   Antoine Goutenoir   Update the base F...
1
from flask_wtf import FlaskForm
d014ea17   Antoine Goutenoir   feat: improve aut...
2
from werkzeug.datastructures import FileStorage
c81df6e7   Goutte   Add the forms mod...
3
4
5
6
from wtforms import \
    StringField, \
    PasswordField, \
    TextAreaField, \
35e3e5e8   Antoine Goutenoir   Add the select fi...
7
    SelectField, \
9e44bb98   Antoine Goutenoir   Support file uplo...
8
9
    BooleanField, \
    FileField
c81df6e7   Goutte   Add the forms mod...
10
from wtforms import validators
c81df6e7   Goutte   Add the forms mod...
11

d8a2ae6b   Antoine Goutenoir   Provide configura...
12
from .content import content_dict as content
77e86148   Antoine Goutenoir   Fake support for ...
13
from .core import models
d014ea17   Antoine Goutenoir   feat: improve aut...
14
from .models import User
35a99ac7   Goutte   Move more text co...
15
16

form_content = content['estimate']['form']
d25ff871   Antoine Goutenoir   Move train distan...
17
train_values = form_content['use_train_below_km']['values']
57f17703   Antoine Goutenoir   fix: pragmatism
18
IS_HUMAN = 'carbon'
c81df6e7   Goutte   Add the forms mod...
19

cb22e72e   Antoine Goutenoir   Add a Captcha and...
20

c81df6e7   Goutte   Add the forms mod...
21
22
# ESTIMATION FORM #############################################################

37fd3b20   Antoine Goutenoir   Update the base F...
23
class EstimateForm(FlaskForm):
77e86148   Antoine Goutenoir   Fake support for ...
24

f47a875d   Antoine Goutenoir   Remove the email ...
25
26
27
28
29
30
31
32
    # email = StringField(
    #     label=form_content['email']['label'],
    #     description=form_content['email']['description'],
    #     validators=[
    #         validators.DataRequired(),
    #         validators.Email(),
    #     ],
    # )
77e86148   Antoine Goutenoir   Fake support for ...
33

8ae021a2   Antoine Goutenoir   Merge shelved cha...
34
35
36
37
38
39
40
41
    run_name = StringField(
        label=form_content['run_name']['label'],
        description=form_content['run_name']['description'],
        validators=[
            validators.Optional(),
            validators.Length(max=128),
        ],
        render_kw={
d014ea17   Antoine Goutenoir   feat: improve aut...
42
            "placeholder": form_content['run_name']['placeholder'],
8ae021a2   Antoine Goutenoir   Merge shelved cha...
43
44
        },
    )
c81df6e7   Goutte   Add the forms mod...
45
    first_name = StringField(
35a99ac7   Goutte   Move more text co...
46
47
        label=form_content['first_name']['label'],
        description=form_content['first_name']['description'],
c81df6e7   Goutte   Add the forms mod...
48
49
        validators=[
            validators.Optional(),
8ae021a2   Antoine Goutenoir   Merge shelved cha...
50
            validators.Length(max=128),
c81df6e7   Goutte   Add the forms mod...
51
        ],
f47a875d   Antoine Goutenoir   Remove the email ...
52
        render_kw={
d014ea17   Antoine Goutenoir   feat: improve aut...
53
54
            "placeholder": form_content['first_name']['placeholder'],
            "autocomplete": "given-name",
f47a875d   Antoine Goutenoir   Remove the email ...
55
        },
c81df6e7   Goutte   Add the forms mod...
56
57
    )
    last_name = StringField(
35a99ac7   Goutte   Move more text co...
58
59
        label=form_content['last_name']['label'],
        description=form_content['last_name']['description'],
c81df6e7   Goutte   Add the forms mod...
60
61
        validators=[
            validators.Optional(),
8ae021a2   Antoine Goutenoir   Merge shelved cha...
62
            validators.Length(max=128),
c81df6e7   Goutte   Add the forms mod...
63
        ],
f47a875d   Antoine Goutenoir   Remove the email ...
64
        render_kw={
d014ea17   Antoine Goutenoir   feat: improve aut...
65
66
            "placeholder": form_content['last_name']['placeholder'],
            "autocomplete": "family-name",
f47a875d   Antoine Goutenoir   Remove the email ...
67
        },
c81df6e7   Goutte   Add the forms mod...
68
69
    )
    institution = StringField(
35a99ac7   Goutte   Move more text co...
70
71
        label=form_content['institution']['label'],
        description=form_content['institution']['description'],
c81df6e7   Goutte   Add the forms mod...
72
73
        validators=[
            validators.Optional(),
8ae021a2   Antoine Goutenoir   Merge shelved cha...
74
            validators.Length(max=128),
c81df6e7   Goutte   Add the forms mod...
75
76
        ],
    )
35e3e5e8   Antoine Goutenoir   Add the select fi...
77
78
79
    use_train_below_km = SelectField(
        label=form_content['use_train_below_km']['label'],
        description=form_content['use_train_below_km']['description'],
d25ff871   Antoine Goutenoir   Move train distan...
80
81
        default=500,
        choices=[(v['value'], v['label']) for v in train_values],
35e3e5e8   Antoine Goutenoir   Add the select fi...
82
83
        coerce=int,
    )
c81df6e7   Goutte   Add the forms mod...
84
    comment = TextAreaField(
35a99ac7   Goutte   Move more text co...
85
86
        label=form_content['comment']['label'],
        description=form_content['comment']['description'],
c81df6e7   Goutte   Add the forms mod...
87
88
        validators=[
            validators.Optional(),
8ae021a2   Antoine Goutenoir   Merge shelved cha...
89
            validators.Length(max=4096),
c81df6e7   Goutte   Add the forms mod...
90
91
92
        ],
    )
    origin_addresses = TextAreaField(
35a99ac7   Goutte   Move more text co...
93
94
        label=form_content['origin_addresses']['label'],
        description=form_content['origin_addresses']['description'],
c81df6e7   Goutte   Add the forms mod...
95
        validators=[
be2eb14f   Antoine Goutenoir   fix: origins and ...
96
            # validators.DataRequired(),
c81df6e7   Goutte   Add the forms mod...
97
        ],
35a99ac7   Goutte   Move more text co...
98
        render_kw={
d014ea17   Antoine Goutenoir   feat: improve aut...
99
            "placeholder": form_content['origin_addresses']['placeholder'],
35a99ac7   Goutte   Move more text co...
100
        },
c81df6e7   Goutte   Add the forms mod...
101
102
    )
    destination_addresses = TextAreaField(
35a99ac7   Goutte   Move more text co...
103
104
        label=form_content['destination_addresses']['label'],
        description=form_content['destination_addresses']['description'],
c81df6e7   Goutte   Add the forms mod...
105
        validators=[
be2eb14f   Antoine Goutenoir   fix: origins and ...
106
            # validators.DataRequired(),
c81df6e7   Goutte   Add the forms mod...
107
        ],
35a99ac7   Goutte   Move more text co...
108
        render_kw={
d014ea17   Antoine Goutenoir   feat: improve aut...
109
            "placeholder": form_content['destination_addresses']['placeholder'],
35a99ac7   Goutte   Move more text co...
110
111
        },
    )
9e44bb98   Antoine Goutenoir   Support file uplo...
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
    origin_addresses_file = FileField(
        label=form_content['origin_addresses_file']['label'],
        description=form_content['origin_addresses_file']['description'],
        validators=[
            # We disabled validators because they bug with multiple FileFields
            # validators.Optional(),
            # FileAllowed(
            #     ['csv', 'xls', 'xlsx'],
            #     form_content['origin_addresses_file']['error']
            # )
        ],
    )
    destination_addresses_file = FileField(
        label=form_content['destination_addresses_file']['label'],
        description=form_content['destination_addresses_file']['description'],
        validators=[
            # We disabled validators because they bug with multiple FileFields
            # validators.Optional(),
            # FileAllowed(
            #     ['csv', 'xls', 'xlsx'],
            #     form_content['destination_addresses_file']['error']
            # )
        ],
    )
f9c4d6c0   Antoine Goutenoir   fix: disable the ...
136
137
138
139
140
141
142
143
    # captcha = StringField(
    #     label=form_content['captcha']['label'],
    #     description=form_content['captcha']['description'],
    #     validators=[
    #         validators.InputRequired(),
    #         validators.Length(max=16),
    #     ],
    # )
9e44bb98   Antoine Goutenoir   Support file uplo...
144
145

    upload_set = ['csv', 'xls', 'xlsx']
77e86148   Antoine Goutenoir   Fake support for ...
146

7f7c6b10   Antoine Goutenoir   Disable RFI in th...
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
    # compute_optimal_destination = BooleanField(
    #     label=form_content['compute_optimal_destination']['label'],
    #     description=form_content['compute_optimal_destination']['description'],
    #     default=False,
    #     validators=[
    #         validators.Optional(),
    #     ],
    # )
    # use_atmosfair_rfi = BooleanField(
    #     label=form_content['use_atmosfair_rfi']['label'],
    #     description=form_content['use_atmosfair_rfi']['description'],
    #     default=False,
    #     validators=[
    #         validators.Optional(),
    #     ],
    # )
c81df6e7   Goutte   Add the forms mod...
163
164
165
166
167
168
169
170

    def validate(self):
        check_validate = super(EstimateForm, self).validate()

        # Do our validators pass?
        if not check_validate:
            return False

f9c4d6c0   Antoine Goutenoir   fix: disable the ...
171
172
173
174
175
176
        # if self.captcha.data != IS_HUMAN:
        #     if not captcha.validate():
        #         self.captcha.errors.append(
        #             "Captcha do not match.  Try again."
        #         )
        #         return False
cb22e72e   Antoine Goutenoir   Add a Captcha and...
177

be2eb14f   Antoine Goutenoir   fix: origins and ...
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
        # Origins must be set either by field or file
        if (
            (not self.origin_addresses.data)
            and
            (not self.origin_addresses_file.data)
        ):
            self.origin_addresses.errors.append(
                "You need to provide either a list of cities or a file."
            )
            return False

        # Destinations must be set either by field or file
        if (
            (not self.destination_addresses.data)
            and
            (not self.destination_addresses_file.data)
        ):
            self.destination_addresses.errors.append(
                "You need to provide either a list of cities or a file."
            )
            return False

        # At least one model should be used
77e86148   Antoine Goutenoir   Fake support for ...
201
202
203
        uses_at_least_one_model = False
        for model in models:
            use_model = getattr(self, 'use_model_%s' % model.slug)
cb22e72e   Antoine Goutenoir   Add a Captcha and...
204
            # print("Model data", model.slug, use_model.data)
77e86148   Antoine Goutenoir   Fake support for ...
205
206
207
208
209
            if use_model.data:
                uses_at_least_one_model = True

        if not uses_at_least_one_model:
            last_model = getattr(self, 'use_model_%s' % models[-1].slug)
9e44bb98   Antoine Goutenoir   Support file uplo...
210
211
212
213
            last_model.errors.append(
                "Please select at least one plane model, "
                "<em>even for train-only estimations.</em>"
            )
77e86148   Antoine Goutenoir   Fake support for ...
214
215
            return False

9e44bb98   Antoine Goutenoir   Support file uplo...
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
        # Check uploaded files' extensions, if any
        # We have to do this "by hand" because of a bug in flask wtf
        if isinstance(self.origin_addresses_file.data, FileStorage):
            fn = self.origin_addresses_file.data.filename.lower()
            if fn and not any(fn.endswith('.' + x) for x in self.upload_set):
                self.origin_addresses_file.errors.append(
                    form_content['origin_addresses_file']['error']
                )
                return False
        if isinstance(self.destination_addresses_file.data, FileStorage):
            fn = self.destination_addresses_file.data.filename.lower()
            if fn and not any(fn.endswith('.' + x) for x in self.upload_set):
                self.destination_addresses_file.errors.append(
                    form_content['destination_addresses_file']['error']
                )
                return False

c81df6e7   Goutte   Add the forms mod...
233
234
235
        return True


77e86148   Antoine Goutenoir   Fake support for ...
236
237
238
239
240
241
242
243
# Add the models' checkboxes to the above Form
for model in models:
    setattr(  # setattr() takes no keyword arguments -.-
        EstimateForm,
        'use_model_%s' % model.slug,
        BooleanField(
            label=model.name,
            # description=model.short_description,
845bbf90   Antoine Goutenoir   Activate the `sel...
244
            default=model.selected,
77e86148   Antoine Goutenoir   Fake support for ...
245
246
247
248
249
250
251
            validators=[
                validators.Optional(),
            ],
        )
    )


c81df6e7   Goutte   Add the forms mod...
252
253
# LOGIN FORM ##################################################################

37fd3b20   Antoine Goutenoir   Update the base F...
254
class LoginForm(FlaskForm):
c81df6e7   Goutte   Add the forms mod...
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    username = StringField(u'Username', validators=[validators.required()])
    password = PasswordField(u'Password', validators=[validators.optional()])

    def validate(self):
        check_validate = super(LoginForm, self).validate()

        # Do our validators pass?
        if not check_validate:
            return False

        # Does the user even exist?
        user = User.query.filter_by(username=self.username.data).first()
        if not user:
            self.username.errors.append('Invalid username or password')
            return False

        # Do the passwords match?
        if not user.check_password(self.password.data):
            self.username.errors.append('Invalid username or password')
            return False

        return True