Skip to content

Commit 2e47749

Browse files
Don't allow SVG avatar uploads in the first place
1 parent 6475ad3 commit 2e47749

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

app/models/user/avatar.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,24 @@
11
module User::Avatar
22
extend ActiveSupport::Concern
33

4+
ALLOWED_AVATAR_CONTENT_TYPES = %w[ image/jpeg image/png image/gif image/webp ].freeze
5+
46
included do
57
has_one_attached :avatar do |attachable|
68
attachable.variant :thumb, resize_to_fill: [ 256, 256 ]
79
end
10+
11+
validate :avatar_content_type_allowed
812
end
913

1014
def avatar_thumbnail
1115
avatar.variable? ? avatar.variant(:thumb) : avatar
1216
end
17+
18+
private
19+
def avatar_content_type_allowed
20+
if avatar.attached? && !ALLOWED_AVATAR_CONTENT_TYPES.include?(avatar.content_type)
21+
errors.add(:avatar, "must be a JPEG, PNG, GIF, or WebP image")
22+
end
23+
end
1324
end

app/views/users/edit.html.erb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
<label class="avatar btn btn--circle input--file txt-xx-large center fill-white">
1616
<%= image_tag user_avatar_path(@user), aria: { hidden: "true" }, class: "avatar", size: 128, data: { upload_preview_target: "image" } %>
17-
<%= form.file_field :avatar, id: "file", class: "input", accept: "image/*",
17+
<%= form.file_field :avatar, id: "file", class: "input", accept: "image/jpeg, image/png, image/gif, image/webp",
1818
data: { upload_preview_target: "input", action: "upload-preview#previewImage" } %>
1919
<span class="for-screen-reader">Profile avatar for <%= @user.name %></span>
2020
</label>

test/models/user/avatar_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,17 @@ class User::AvatarTest < ActiveSupport::TestCase
1414
assert_not users(:david).avatar.variable?
1515
assert_equal users(:david).avatar.blob, users(:david).avatar_thumbnail.blob
1616
end
17+
18+
test "allows valid image content types" do
19+
users(:david).avatar.attach(io: File.open(file_fixture("moon.jpg")), filename: "test.jpg")
20+
21+
assert users(:david).valid?
22+
end
23+
24+
test "rejects SVG uploads" do
25+
users(:david).avatar.attach(io: File.open(file_fixture("avatar.svg")), filename: "avatar.svg")
26+
27+
assert_not users(:david).valid?
28+
assert_includes users(:david).errors[:avatar], "must be a JPEG, PNG, GIF, or WebP image"
29+
end
1730
end

0 commit comments

Comments
 (0)