Skip to content

Commit 9b316e8

Browse files
Check that the file the user chose has a MIME type of image/* (#28467)
* Check that the file the user chose has a MIME type of `image/*` Signed-off-by: Michael Telatynski <[email protected]> * i18n Signed-off-by: Michael Telatynski <[email protected]> * Optional Signed-off-by: Michael Telatynski <[email protected]> * Improve coverage Signed-off-by: Michael Telatynski <[email protected]> * DRY Signed-off-by: Michael Telatynski <[email protected]> * Iterate Signed-off-by: Michael Telatynski <[email protected]> * Improve coverage Signed-off-by: Michael Telatynski <[email protected]> * Update src/components/views/settings/AvatarSetting.tsx Co-authored-by: Florian Duros <[email protected]> * prettier Signed-off-by: Michael Telatynski <[email protected]> --------- Signed-off-by: Michael Telatynski <[email protected]> Co-authored-by: Florian Duros <[email protected]>
1 parent 72a2773 commit 9b316e8

File tree

5 files changed

+110
-6
lines changed

5 files changed

+110
-6
lines changed

src/components/views/elements/MiniAvatarUploader.tsx

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { useTimeout } from "../../../hooks/useTimeout";
1717
import { chromeFileInputFix } from "../../../utils/BrowserWorkarounds";
1818
import AccessibleButton from "./AccessibleButton";
1919
import Spinner from "./Spinner";
20+
import { getFileChanged } from "../settings/AvatarSetting.tsx";
2021

2122
export const AVATAR_SIZE = "52px";
2223

@@ -72,11 +73,12 @@ const MiniAvatarUploader: React.FC<IProps> = ({
7273
onClick?.(ev);
7374
}}
7475
onChange={async (ev): Promise<void> => {
75-
if (!ev.target.files?.length) return;
7676
setBusy(true);
77-
const file = ev.target.files[0];
78-
const { content_uri: uri } = await cli.uploadContent(file);
79-
await setAvatarUrl(uri);
77+
const file = getFileChanged(ev);
78+
if (file) {
79+
const { content_uri: uri } = await cli.uploadContent(file);
80+
await setAvatarUrl(uri);
81+
}
8082
setBusy(false);
8183
}}
8284
accept="image/*"

src/components/views/settings/AvatarSetting.tsx

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import { chromeFileInputFix } from "../../../utils/BrowserWorkarounds";
1919
import { useId } from "../../../utils/useId";
2020
import AccessibleButton from "../elements/AccessibleButton";
2121
import BaseAvatar from "../avatars/BaseAvatar";
22+
import Modal from "../../../Modal.tsx";
23+
import ErrorDialog from "../dialogs/ErrorDialog.tsx";
2224

2325
interface MenuProps {
2426
trigger: ReactNode;
@@ -103,6 +105,18 @@ interface IProps {
103105
placeholderName: string;
104106
}
105107

108+
export function getFileChanged(e: React.ChangeEvent<HTMLInputElement>): File | null {
109+
if (!e.target.files?.length) return null;
110+
const file = e.target.files[0];
111+
if (file.type.startsWith("image/")) return file;
112+
113+
Modal.createDialog(ErrorDialog, {
114+
title: _t("upload_failed_title"),
115+
description: _t("upload_file|not_image"),
116+
});
117+
return null;
118+
}
119+
106120
/**
107121
* Component for setting or removing an avatar on something (eg. a user or a room)
108122
*/
@@ -139,7 +153,10 @@ const AvatarSetting: React.FC<IProps> = ({
139153

140154
const onFileChanged = useCallback(
141155
(e: React.ChangeEvent<HTMLInputElement>) => {
142-
if (e.target.files) onChange?.(e.target.files[0]);
156+
const file = getFileChanged(e);
157+
if (file) {
158+
onChange?.(file);
159+
}
143160
},
144161
[onChange],
145162
);

src/i18n/strings/en_EN.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3742,6 +3742,7 @@
37423742
"error_files_too_large": "These files are <b>too large</b> to upload. The file size limit is %(limit)s.",
37433743
"error_some_files_too_large": "Some files are <b>too large</b> to be uploaded. The file size limit is %(limit)s.",
37443744
"error_title": "Upload Error",
3745+
"not_image": "The file you have chosen is not a valid image file.",
37453746
"title": "Upload files",
37463747
"title_progress": "Upload files (%(current)s of %(total)s)",
37473748
"upload_all_button": "Upload all",
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Copyright 2024 New Vector Ltd.
3+
4+
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
5+
Please see LICENSE files in the repository root for full details.
6+
*/
7+
8+
import React from "react";
9+
import { render } from "jest-matrix-react";
10+
import userEvent from "@testing-library/user-event";
11+
import { mocked } from "jest-mock";
12+
13+
import MiniAvatarUploader from "../../../../../src/components/views/elements/MiniAvatarUploader.tsx";
14+
import { stubClient, withClientContextRenderOptions } from "../../../../test-utils";
15+
16+
const BASE64_GIF = "R0lGODlhAQABAAAAACw=";
17+
const AVATAR_FILE = new File([Uint8Array.from(atob(BASE64_GIF), (c) => c.charCodeAt(0))], "avatar.gif", {
18+
type: "image/gif",
19+
});
20+
21+
describe("<MiniAvatarUploader />", () => {
22+
it("calls setAvatarUrl when a file is uploaded", async () => {
23+
const cli = stubClient();
24+
mocked(cli.uploadContent).mockResolvedValue({ content_uri: "mxc://example.com/1234" });
25+
26+
const setAvatarUrl = jest.fn();
27+
const user = userEvent.setup();
28+
29+
const { container, findByText } = render(
30+
<MiniAvatarUploader hasAvatar={false} noAvatarLabel="Upload" setAvatarUrl={setAvatarUrl} isUserAvatar />,
31+
withClientContextRenderOptions(cli),
32+
);
33+
34+
await findByText("Upload");
35+
await user.upload(container.querySelector("input")!, AVATAR_FILE);
36+
37+
expect(cli.uploadContent).toHaveBeenCalledWith(AVATAR_FILE);
38+
expect(setAvatarUrl).toHaveBeenCalledWith("mxc://example.com/1234");
39+
});
40+
});

test/unit-tests/components/views/settings/AvatarSetting-test.tsx

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
66
Please see LICENSE files in the repository root for full details.
77
*/
88
import React from "react";
9-
import { render, screen } from "jest-matrix-react";
9+
import { render, screen, fireEvent } from "jest-matrix-react";
1010
import userEvent from "@testing-library/user-event";
1111

1212
import AvatarSetting from "../../../../../src/components/views/settings/AvatarSetting";
@@ -16,6 +16,9 @@ const BASE64_GIF = "R0lGODlhAQABAAAAACw=";
1616
const AVATAR_FILE = new File([Uint8Array.from(atob(BASE64_GIF), (c) => c.charCodeAt(0))], "avatar.gif", {
1717
type: "image/gif",
1818
});
19+
const GENERIC_FILE = new File([Uint8Array.from(atob(BASE64_GIF), (c) => c.charCodeAt(0))], "not-avatar.doc", {
20+
type: "application/msword",
21+
});
1922

2023
describe("<AvatarSetting />", () => {
2124
beforeEach(() => {
@@ -70,4 +73,45 @@ describe("<AvatarSetting />", () => {
7073

7174
expect(onChange).toHaveBeenCalledWith(AVATAR_FILE);
7275
});
76+
77+
it("should noop when selecting no file", async () => {
78+
const onChange = jest.fn();
79+
80+
render(
81+
<AvatarSetting
82+
placeholderId="blee"
83+
placeholderName="boo"
84+
avatar="mxc://example.org/my-avatar"
85+
avatarAltText="Avatar of Peter Fox"
86+
onChange={onChange}
87+
/>,
88+
);
89+
90+
const fileInput = screen.getByAltText("Upload");
91+
// Can't use userEvent.upload here as it doesn't support uploading invalid files
92+
fireEvent.change(fileInput, { target: { files: [] } });
93+
94+
expect(onChange).not.toHaveBeenCalled();
95+
});
96+
97+
it("should show error if user tries to use non-image file", async () => {
98+
const onChange = jest.fn();
99+
100+
render(
101+
<AvatarSetting
102+
placeholderId="blee"
103+
placeholderName="boo"
104+
avatar="mxc://example.org/my-avatar"
105+
avatarAltText="Avatar of Peter Fox"
106+
onChange={onChange}
107+
/>,
108+
);
109+
110+
const fileInput = screen.getByAltText("Upload");
111+
// Can't use userEvent.upload here as it doesn't support uploading invalid files
112+
fireEvent.change(fileInput, { target: { files: [GENERIC_FILE] } });
113+
114+
expect(onChange).not.toHaveBeenCalled();
115+
await expect(screen.findByRole("heading", { name: "Upload Failed" })).resolves.toBeInTheDocument();
116+
});
73117
});

0 commit comments

Comments
 (0)