8000 Show an error when an uploaded JSON file is not valid by Ahmed-Manai · Pull Request #55498 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1245,6 +1245,7 @@ attributeConsumingServiceName=Attribute Consuming Service Name
invalidJsonError=Unable to save user profile, the provided information is not valid JSON: {{error}}
invalidJsonClientProfilesError=Unable to save client profiles, the provided information is not valid JSON: {{error}}
invalidJsonClientPoliciesError=Unable to save client policies, the provided information is not valid JSON: {{error}}
invalidJsonFile=The file is not valid JSON: {{error}}
promptHelp=Specifies whether the Authorization Server prompts the End-User for re-authentication and consent.
deleteBtn=Delete
defaultLocale=Default locale
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ export type FileUploadFormProps = Omit<FileUploadProps, "onChange"> & {
extension: string;
onChange: (value: string) => void;
helpText?: string;
/** Shown instead of the help text, with the field marked as invalid. */
errorText?: string;
unWrap?: boolean;
language?: string;
previewMaxLength?: number;
Expand All @@ -45,6 +47,7 @@ export const FileUploadForm = ({
id,
onChange,
helpText = "helpFileUpload",
errorText,
unWrap = false,
previewMaxLength = 102400, // 100KB
language,
Expand Down Expand Up @@ -126,11 +129,17 @@ export const FileUploadForm = ({
setFileUpload((prev) => ({ ...prev, isLoading: false }))
}
isLoading={fileUpload.isLoading}
validated={errorText ? "error" : rest.validated}
dropzoneProps={{
accept: { "application/text": [extension] },
}}
/>
)}
{unWrap && errorText && (
<HelperText>
<HelperTextItem variant="error">{errorText}</HelperTextItem>
</HelperText>
)}
{!unWrap && (
<FormGroup label={t("resourceFile")} fieldId={id + "-filename"}>
<FileUpload
Expand All @@ -151,6 +160,7 @@ export const FileUploadForm = ({
setFileUpload((prev) => ({ ...prev, isLoading: false }))
}
isLoading={fileUpload.isLoading}
validated={errorText ? "error" : rest.validated}
hideDefaultPreview
>
{!rest.hideDefaultPreview &&
Expand All @@ -173,7 +183,11 @@ export const FileUploadForm = ({
</FileUpload>
<FormHelperText>
<HelperText>
<HelperTextItem>{t(helpText)}</HelperTextItem>
{errorText ? (
<HelperTextItem variant="error">{errorText}</HelperTextItem>
) : (
<HelperTextItem>{t(helpText)}</HelperTextItem>
)}
</HelperText>
</FormHelperText>
</FormGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,49 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FileUploadForm, FileUploadFormProps } from "./FileUploadForm";

export type JsonFileUploadProps = Omit<
FileUploadFormProps,
"onChange" | "language" | "extension"
"onChange" | "language" | "extension" | "errorText"
> & {
onChange: (obj: object) => void;
/** Called with the parse error when the content is not valid JSON, and with undefined once it is. */
onParseError?: (error?: string) => void;
};

export const JsonFileUpload = ({ onChange, ...props }: JsonFileUploadProps) => {
export const JsonFileUpload = ({
onChange,
onParseError,
...props
}: JsonFileUploadProps) => {
const { t } = useTranslation();
const [error, setError] = useState<string>();

const updateError = (message?: string) => {
setError(message);
onParseError?.(message);
};

const handleChange = (value: string) => {
if (value.trim() === "") {
updateError(undefined);
onChange({});
return;
}

let parsed: object;
try {
onChange(JSON.parse(value));
} catch {
parsed = JSON.parse(value);
} catch (parseError) {
onChange({});
console.warn("Invalid json, ignoring value using {}");
updateError(
parseError instanceof Error ? parseError.message : String(parseError),
Comment thread
Ahmed-Manai marked this conversation as resolved.
Resolved
);
return;
}

updateError(undefined);
onChange(parsed);
};

return (
Expand All @@ -23,6 +52,7 @@ export const JsonFileUpload = ({ onChange, ...props }: JsonFileUploadProps) => {
language="json"
extension=".json"
>
errorText={error && t("invalidJsonFile", { error })}
/>
);
};
3 changes: 3 additions & 0 deletions js/apps/admin-ui/src/realm/add/NewRealmForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export default function NewRealmForm({ onClose }: NewRealmFormProps) {
const { refresh, whoAmI } = useWhoAmI();
const { addAlert, addError } = useAlerts();
const [realm, setRealm] = useState<RealmRepresentation>();
const [jsonError, setJsonError] = useState<string>();

const form = useForm<RealmRepresentation>({
mode: "onChange",
Expand Down Expand Up @@ -72,6 +73,7 @@ export default function NewRealmForm({ onClose }: NewRealmFormProps) {
formState={formState}
allowInvalid
allowNonDirty
isDisabled={!!jsonError}
key="confirm"
>
{t("create")}
Expand All @@ -98,6 +100,7 @@ export default function NewRealmForm({ onClose }: NewRealmFormProps) {
id="kc-realm-filename"
allowEditingUploadedText
>
>
/>
<TextControl
name="realm"
Expand Down
18 changes: 17 additions & 1 deletion js/apps/admin-ui/test/masthead/realm.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { test } from "@playwright/test";
import { expect, test } from "@playwright/test";
import { v4 as uuid } from "uuid";
import adminClient from "../utils/AdminClient.ts";
import { DEFAULT_REALM } from "../utils/constants.ts";
Expand Down Expand Up @@ -72,6 +72,22 @@ test.describe.serial("Realm tests", () => {
await assertNotificationMessage(page, "Realm created successfully");
});

test("should show an error for a resource file that is not valid JSON", async ({
page,
}) => {
const editor = page.locator(".w-tc-editor-text");
const error = page.getByText("The file is not valid JSON:");

await editor.fill('{"realm": "broken",');
await expect(error).toBeVisible();
await expect(page.getByTestId("create")).toBeDisabled();

await editor.fill('{"realm": "fixed"}');
await expect(error).toBeHidden();
await expect(page.getByTestId("realm")).toHaveValue("fixed");
await expect(page.getByTestId("create")).toBeEnabled();
});

test("CRUD test of Disabled realm", async ({ page }) => {
await fillRealmName(page, testDisabledName);
await clickCreateRealmForm(page);
Expand Down
0