-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathforms.py
More file actions
368 lines (325 loc) · 13.8 KB
/
forms.py
File metadata and controls
368 lines (325 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import logging
import uuid
from django import forms
from django.conf import settings
from django.core.validators import URLValidator
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from oauth2_provider.forms import AllowForm as DotAllowForm
from oauth2_provider.models import get_application_model
from apps.accounts.models import UserProfile
from apps.capabilities.models import ProtectedCapability
from apps.dot_ext.constants import PRINTABLE_SPECIAL_ASCII
from apps.dot_ext.scopes import CapabilitiesScopes
from apps.dot_ext.models import Application, InternalApplicationLabels
from apps.dot_ext.validators import validate_logo_image, validate_notags
from django.contrib.auth.models import Group, User
from django.forms.widgets import URLInput
from apps.constants import HHS_SERVER_LOGNAME_FMT
logger = logging.getLogger(HHS_SERVER_LOGNAME_FMT.format(__name__))
# TODO Consider refactoring the following two forms which are possibly redundant
# Refer to comment on BB2-2933
class CustomRegisterApplicationForm(forms.ModelForm):
logo_image = forms.ImageField(
label='Logo URI Image Upload',
required=False,
help_text='Upload your logo image file here in JPG, JPEG, or PNG (.jpg, .jpeg, .png) format! '
'The maximum file size allowed is %sKB and maximum dimensions are %sx%s pixels. '
'This will update the Logo URI after saving.'
% (
settings.APP_LOGO_SIZE_MAX,
settings.APP_LOGO_WIDTH_MAX,
settings.APP_LOGO_HEIGHT_MAX,
),
)
description = forms.CharField(
label='Application Description',
help_text='This is plain-text up to 1000 characters in length.',
widget=forms.Textarea,
empty_value='',
required=False,
max_length=1000,
validators=[validate_notags],
)
policy_uri = forms.CharField(
required=False,
max_length=2048,
validators=[URLValidator()],
widget=URLInput,
)
tos_uri = forms.CharField(
required=False,
max_length=2048,
validators=[URLValidator()],
widget=URLInput,
)
website_uri = forms.CharField(
required=False,
max_length=2048,
validators=[URLValidator()],
widget=URLInput,
)
def __init__(self, user, *args, **kwargs):
agree_label = 'Yes I have read and agree to the <a target="_blank" href="%s">API Terms of Service Agreement</a>*' % (
settings.TOS_URI
)
super(CustomRegisterApplicationForm, self).__init__(*args, **kwargs)
self.fields['authorization_grant_type'].choices = settings.GRANT_TYPES
self.fields['client_type'].initial = 'confidential'
self.fields['agree'].label = mark_safe(agree_label)
self.fields['name'].label = 'Name*'
self.fields['name'].required = True
self.fields['client_type'].label = 'Client Type*'
self.fields['client_type'].required = False
self.fields['authorization_grant_type'].label = 'Authorization Grant Type*'
self.fields['authorization_grant_type'].required = False
self.fields['redirect_uris'].label = 'Redirect URIs*'
self.fields['logo_uri'].disabled = True
self.fields['internal_application_labels'] = forms.ModelMultipleChoiceField(
queryset=InternalApplicationLabels.objects.all(), widget=forms.SelectMultiple
)
self.fields['internal_application_labels'].required = False
class Meta:
model = get_application_model()
fields = (
'name',
'client_type',
'authorization_grant_type',
'redirect_uris',
'logo_uri',
'logo_image',
'website_uri',
'description',
'policy_uri',
'tos_uri',
'support_email',
'support_phone_number',
'contacts',
'agree',
'require_demographic_scopes',
'internal_application_labels',
)
required_css_class = 'required'
def clean(self):
return self.cleaned_data
def clean_name(self):
name = self.cleaned_data.get('name')
app_model = get_application_model()
if app_model.objects.filter(name__iexact=name).exclude(pk=self.instance.pk).exists():
raise forms.ValidationError(
"""
It looks like this application name
is already in use with another app.
Please enter a different application
name to prevent future errors.
Note that names are case-insensitive.
"""
)
if not app_model.objects.filter(name__iexact=name).exists():
# new app, restrict app name to only printable ASCII (32-127)
if not (str(name).isprintable() and str(name).isascii()):
raise forms.ValidationError(
"""
Invalid character(s) in application name ({}),
Allowed characters:
Alphanumeric characters 0 to 9, a to z, A to Z, space character,
Special characters {}
""".format(name, PRINTABLE_SPECIAL_ASCII)
)
return name
def clean_agree(self):
agree = self.cleaned_data.get('agree')
if not agree:
msg = _('You must agree to the API Terms of Service Agreement')
raise forms.ValidationError(msg)
return agree
def clean_redirect_uris(self):
redirect_uris = self.cleaned_data.get('redirect_uris')
if getattr(settings, 'BLOCK_HTTP_REDIRECT_URIS', True):
if redirect_uris:
for u in redirect_uris.split():
if u.startswith('http://'):
msg = _('Redirect URIs must not use http.')
raise forms.ValidationError(msg)
return redirect_uris
def clean_logo_image(self):
logo_image = self.cleaned_data.get('logo_image')
if getattr(logo_image, 'name', False):
validate_logo_image(logo_image)
return logo_image
def clean_require_demographic_scopes(self):
require_demographic_scopes = self.cleaned_data.get('require_demographic_scopes')
if not isinstance(require_demographic_scopes, bool):
msg = _('Does your application need to collect beneficiary demographic information must be (Yes/No).')
raise forms.ValidationError(msg)
return require_demographic_scopes
def save(self, *args, **kwargs):
self.instance.client_type = 'confidential'
self.instance.authorization_grant_type = 'authorization-code'
app = self.instance
# Only log agreement from a Register form
if app.agree and isinstance(self, CustomRegisterApplicationForm):
logmsg = '%s agreed to %s for the application %s' % (
app.user,
app.op_tos_uri,
app.name,
)
logger.info(logmsg)
app = super().save(*args, **kwargs)
app.save()
uri = app.store_media_file(self.cleaned_data.pop('logo_image', None))
if uri:
app.logo_uri = uri
app.save()
return app
class CreateNewApplicationForm(forms.ModelForm):
logo_image = forms.ImageField(
label='Logo URI Image Upload',
required=False,
help_text='Upload your logo image file here in JPG, JPEG, or PNG (.jpg, .jpeg, .png) format! '
'The maximum file size allowed is %sKB and maximum dimensions are %sx%s pixels. '
'This will update the Logo URI after saving.'
% (
settings.APP_LOGO_SIZE_MAX,
settings.APP_LOGO_WIDTH_MAX,
settings.APP_LOGO_HEIGHT_MAX,
),
)
description = forms.CharField(
label='Application Description',
help_text='This is plain-text up to 1000 characters in length.',
widget=forms.Textarea,
empty_value='',
required=False,
max_length=1000,
validators=[validate_notags],
)
organization_name = forms.CharField(required=True)
policy_uri = forms.CharField(
required=False,
max_length=2048,
validators=[URLValidator()],
widget=URLInput,
)
tos_uri = forms.CharField(
required=False,
max_length=2048,
validators=[URLValidator()],
widget=URLInput,
)
website_uri = forms.CharField(
required=False,
max_length=2048,
validators=[URLValidator()],
widget=URLInput,
)
class Meta:
model = get_application_model()
fields = (
'name',
'organization_name',
'contacts',
'redirect_uris',
'require_demographic_scopes',
'policy_uri',
'tos_uri',
'website_uri',
'support_email',
'support_phone_number',
'logo_image',
'description',
'internal_application_labels',
'jwks_uri',
'allowed_auth_type',
)
# Duplication of clean_name() from above form, see TODO comment at start of file
# about candidate for refactoring
def clean_name(self):
name = self.cleaned_data.get('name')
app_model = get_application_model()
if app_model.objects.filter(name__iexact=name).exclude(pk=self.instance.pk).exists():
raise forms.ValidationError(
"""
It looks like this application name
is already in use with another app.
Please enter a different application
name to prevent future errors.
Note that names are case-insensitive.
"""
)
if not app_model.objects.filter(name__iexact=name).exists():
# new app, restrict app name to only printable ASCII (32-127)
if not (str(name).isprintable() and str(name).isascii()):
raise forms.ValidationError(
"""
Invalid character(s) in application name ({}),
Allowed characters:
Alphanumeric characters 0 to 9, a to z, A to Z, space character,
Special characters {}
""".format(name, PRINTABLE_SPECIAL_ASCII)
)
return name
def clean_logo_image(self):
logo_image = self.cleaned_data.get('logo_image')
if getattr(logo_image, 'name', False):
validate_logo_image(logo_image)
return logo_image
def clean_redirect_uris(self):
redirect_uris = self.cleaned_data.get('redirect_uris')
if getattr(settings, 'BLOCK_HTTP_REDIRECT_URIS', True):
if redirect_uris:
for u in redirect_uris.split():
if u.startswith('http://'):
msg = _('Redirect URIs must not use http.')
raise forms.ValidationError(msg)
return redirect_uris
def clean_require_demographic_scopes(self):
require_demographic_scopes = self.cleaned_data.get('require_demographic_scopes')
if not isinstance(require_demographic_scopes, bool):
msg = _('Does your application need to collect beneficiary demographic information must be (Yes/No).')
raise forms.ValidationError(msg)
return require_demographic_scopes
def save(self, *args, **kwargs):
app = self.instance
new_user_model = User.objects.create(
username=self.cleaned_data.get('name') + '@example.com',
password=str(uuid.uuid4()),
is_active=True,
)
group = Group.objects.get(name='BlueButton')
new_user_model.groups.add(group)
new_user_model.save()
UserProfile.objects.create(
user=new_user_model,
organization_name=self.cleaned_data.get('organization_name'),
)
app = super().save(*args, **kwargs)
app.agree = True
app.user = new_user_model
app.authorization_grant_type = Application.GRANT_AUTHORIZATION_CODE
app.client_type = Application.CLIENT_CONFIDENTIAL
app.save()
app.scope.add(*list(ProtectedCapability.objects.filter(default=True).values_list('id', flat=True)))
app.save()
uri = app.store_media_file(self.cleaned_data.pop('logo_image', None))
if uri:
app.logo_uri = uri
app.save()
return app
class SimpleAllowForm(DotAllowForm):
code_challenge = forms.CharField(required=False, widget=forms.HiddenInput())
code_challenge_method = forms.CharField(required=False, widget=forms.HiddenInput())
share_demographic_scopes = forms.CharField(required=False)
def clean(self):
cleaned_data = super().clean()
scope = cleaned_data.get('scope', None)
if scope is None:
cleaned_data['scope'] = ''
scope = ''
else:
cleaned_scope_list = CapabilitiesScopes().condense_scopes(scope.split(' '))
# Remove demographic information scopes, if beneficiary is not sharing
if cleaned_data.get('share_demographic_scopes') != 'True':
cleaned_scope_list = CapabilitiesScopes().remove_demographic_scopes(cleaned_scope_list)
cleaned_data['scope'] = ' '.join(cleaned_scope_list)
return cleaned_data