fix: Add escaping special characters before JSON.parse (#9293)

* Add escaping special characters before JSON.parse
This commit is contained in:
Rishabh Rathod 2021-11-25 16:22:40 +05:30 committed by GitHub
parent 5d7f68a031
commit d7cdf6f84b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 28 additions and 5 deletions

View File

@ -36,7 +36,8 @@
"react/jsx-fragments": "error",
"react/jsx-no-useless-fragment": "error",
"sort-destructure-keys/sort-destructure-keys": ["error", {"caseSensitive": false}],
"no-console": "warn"
"no-console": "warn",
"no-debugger": "warn"
},
"settings": {
"import/resolver": {

View File

@ -36,6 +36,7 @@ import { ValidationTypes } from "constants/WidgetValidation";
import derivedProperties from "./parseDerivedProperties";
import { DSLWidget } from "widgets/constants";
import { entityDefinitions } from "utils/autocomplete/EntityDefinitions";
import { escapeSpecialChars } from "../../WidgetUtils";
const LIST_WIDGEY_PAGINATION_HEIGHT = 36;
class ListWidget extends BaseWidget<ListWidgetProps<WidgetProps>, WidgetState> {
@ -446,15 +447,16 @@ class ListWidget extends BaseWidget<ListWidgetProps<WidgetProps>, WidgetState> {
) {
const { jsSnippets } = getDynamicBindings(propertyValue);
const listItem = this.props.listData?.[itemIndex] || {};
const stringifiedListItem = JSON.stringify(listItem);
const escapedStringifiedListItem = escapeSpecialChars(
stringifiedListItem,
);
const newPropertyValue = jsSnippets.reduce(
(prev: string, next: string) => {
if (next.indexOf("currentItem") > -1) {
return (
prev +
`{{((currentItem) => { ${next}})(JSON.parse('${JSON.stringify(
listItem,
)}'))}}`
`{{((currentItem) => { ${next}})(JSON.parse('${escapedStringifiedListItem}'))}}`
);
}
return prev + `{{${next}}}`;

View File

@ -1,5 +1,6 @@
import { ButtonVariantTypes } from "components/constants";
import { getTheme, ThemeMode } from "selectors/themeSelectors";
import { escapeSpecialChars } from "./WidgetUtils";
import {
getCustomTextColor,
getCustomBackgroundColor,
@ -121,4 +122,13 @@ describe("validate widget utils button style functions", () => {
const result6 = getCustomHoverColor(theme, ButtonVariantTypes.TERTIARY);
expect(result6).toStrictEqual(expected6);
});
it("validate escaping special characters", () => {
const testString = `a\nb\nc
hello! how are you?
`;
const result = escapeSpecialChars(testString);
const expectedResult = "a\nb\nc\nhello! how are you?\n";
expect(result).toStrictEqual(expectedResult);
});
});

View File

@ -140,3 +140,13 @@ export const getCustomBorderColor = (
? backgroundColor
: "none";
};
export const escapeSpecialChars = (stringifiedJSONObject: string) => {
return stringifiedJSONObject
.replace(/\\n/g, "\\\\n") // new line char
.replace(/\\b/g, "\\\\b") //
.replace(/\\t/g, "\\\\t") // tab
.replace(/\\f/g, "\\\\f") //
.replace(/\\/g, "\\\\") //
.replace(/\\r/g, "\\\\r"); //
};