Better form for user submiting images, fix potential attack vector on bad file being resized and treated as an image

This commit is contained in:
2024-08-27 17:05:37 +02:00
parent e564c6604c
commit cc5df9b171
3 changed files with 179 additions and 171 deletions

View File

@ -201,10 +201,7 @@ class RegisteringForm(UserCreationForm):
class UserProfileForm(forms.ModelForm):
"""Form handling the user profile, managing the files
This form is actually pretty bad and was made in the rush before the migration. It should be refactored.
TODO: refactor this form.
"""
"""Form handling the user profile, managing the files"""
class Meta:
model = User
@ -237,25 +234,35 @@ class UserProfileForm(forms.ModelForm):
]
widgets = {
"date_of_birth": SelectDate,
"profile_pict": forms.ClearableFileInput,
"avatar_pict": forms.ClearableFileInput,
"scrub_pict": forms.ClearableFileInput,
"phone": RegionalPhoneNumberWidget,
"parent_phone": RegionalPhoneNumberWidget,
"quote": forms.Textarea,
}
labels = {
"profile_pict": _(
"Profile: you need to be visible on the picture, in order to be recognized (e.g. by the barmen)"
),
"avatar_pict": _("Avatar: used on the forum"),
"scrub_pict": _("Scrub: let other know how your scrub looks like!"),
}
def generate_name(self, field_name, f):
field_name = field_name[:-4]
return field_name + str(self.instance.id) + "." + f.content_type.split("/")[-1]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Image fields are injected here to override the file field provided by the model
# This would be better if we could have a SithImage sort of model input instead of a generic SithFile
self.fields["profile_pict"] = forms.ImageField(
required=False,
label=_(
"Profile: you need to be visible on the picture, in order to be recognized (e.g. by the barmen)"
),
)
self.fields["avatar_pict"] = forms.ImageField(
required=False,
label=_("Avatar: used on the forum"),
)
self.fields["scrub_pict"] = forms.ImageField(
required=False,
label=_("Scrub: let other know how your scrub looks like!"),
)
def process(self, files):
avatar = self.instance.avatar_pict
profile = self.instance.profile_pict
@ -305,7 +312,7 @@ class UserProfileForm(forms.ModelForm):
% {
"file_name": f,
"msg": _(
"Bad image format, only jpeg, png, and gif are accepted"
"Bad image format, only jpeg, png, webp and gif are accepted"
),
},
)