Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(validation): add validation for all routes #1854

Merged
merged 5 commits into from
Mar 20, 2024
Merged
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
6 changes: 3 additions & 3 deletions src/__tests__/RouteSelector.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ describe("Tests for RouteSelector", () => {
render(
<MemoryRouter
initialEntries={[
"/sites/site-name/media/my-room/mediaDirectory/my-directory-name",
"/sites/site-name/media/images/mediaDirectory/images%2Fmy%20directory%20name",
]}
>
<LoggedInContextProvider>
Expand Down Expand Up @@ -617,7 +617,7 @@ describe("Tests for RouteSelector", () => {
render(
<MemoryRouter
initialEntries={[
"/sites/site-name/folders/my-folder/subfolders/my-subfolder",
"/sites/site-name/folders/my-folder/subfolders/my%20subfolder",
]}
>
<LoggedInContextProvider>
Expand Down Expand Up @@ -693,7 +693,7 @@ describe("Tests for RouteSelector", () => {
render(
<MemoryRouter
initialEntries={[
"/sites/site-name/folders/my-folder/subfolders/my-subfolder/editPage/my-file",
"/sites/site-name/folders/my-folder/subfolders/my%20subfolder/editPage/my-file",
]}
>
<LoggedInContextProvider>
Expand Down
47 changes: 39 additions & 8 deletions src/layouts/Media/Media.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,12 @@ import {
} from "features/FeatureTour/FeatureTourSequence"
import { MediaData } from "types/directory"
import { MediaFolderTypes, MediaLabels, SelectedMediaDto } from "types/media"
import { DEFAULT_RETRY_MSG, useErrorToast, useSuccessToast } from "utils"
import {
DEFAULT_RETRY_MSG,
specialCharactersRegexTest,
useErrorToast,
useSuccessToast,
} from "utils"

import { CreateButton } from "../components"
import { SiteEditLayout } from "../layouts"
Expand Down Expand Up @@ -259,7 +264,7 @@ export const Media = (): JSX.Element => {
setSelectedMedia([])
onCreateMediaFolderModalClose()
},
onSuccess: (data, variables, context) => {
onSuccess: (data, variables) => {
if (variables.selectedPages.length === 0) {
successToast({
id: "create-directory-success",
Expand All @@ -280,7 +285,7 @@ export const Media = (): JSX.Element => {
`${url}%2F${encodeURIComponent(variables.newDirectoryName)}`
)
},
onError: (err, variables, context) => {
onError: () => {
errorToast({
id: "create-directory-error",
description: `Your ${singularDirectoryLabel} could not be created successfully. ${DEFAULT_RETRY_MSG}`,
Expand All @@ -296,15 +301,15 @@ export const Media = (): JSX.Element => {
setSelectedMedia([])
onMoveModalClose()
},
onSuccess: (data, variables, context) => {
onSuccess: (data, variables) => {
successToast({
id: "move-multiple-media-success",
description: `Successfully moved ${
variables.items.length === 1 ? singularMediaLabel : pluralMediaLabel
}!`,
})
},
onError: (err, variables, context) => {
onError: (err, variables) => {
errorToast({
id: "move-multiple-media-error",
description: `Your ${
Expand All @@ -318,7 +323,7 @@ export const Media = (): JSX.Element => {
mutate: deleteMultipleMedia,
isLoading: isDeleteMultipleMediaLoading,
} = useDeleteMultipleMediaHook(params, {
onSettled: (data, error, variables, context) => {
onSettled: (data, error, variables) => {
if (variables.length === 1) {
setSelectedMedia(
selectedMedia.filter((selectedData) =>
Expand All @@ -333,15 +338,15 @@ export const Media = (): JSX.Element => {
if (individualMedia) setIndividualMedia(null)
onDeleteModalClose()
},
onSuccess: (data, variables, context) => {
onSuccess: (data, variables) => {
successToast({
id: "delete-multiple-media-success",
description: `Successfully deleted ${
variables.length === 1 ? singularMediaLabel : pluralMediaLabel
}!`,
})
},
onError: (err, variables, context) => {
onError: (err, variables) => {
errorToast({
id: "delete-multiple-media-error",
description: `Your ${
Expand Down Expand Up @@ -724,16 +729,42 @@ export const Media = (): JSX.Element => {
path={[`${path}/editMediaSettings/:fileName`]}
component={MediaSettingsScreen}
onClose={() => history.goBack()}
validate={{
fileName: (value) => {
const encodedName = value.split(".").slice(0, -1).join(".")
return !specialCharactersRegexTest.test(encodedName)
},
}}
/>
<ProtectedRouteWithProps
path={[`${path}/deleteDirectory/:mediaDirectoryName`]}
component={DeleteWarningScreen}
onClose={() => history.goBack()}
validate={{
mediaDirectoryName: (value) => {
// NOTE: This value is prepended with either `files|images/`
// and nested directories are separated by `/` as well.
const decodedValues = decodeURIComponent(value).split("/")
return decodedValues.every(
(val) => !specialCharactersRegexTest.test(val)
)
},
}}
/>
<ProtectedRouteWithProps
path={[`${path}/editDirectorySettings/:mediaDirectoryName`]}
component={DirectorySettingsScreen}
onClose={() => history.goBack()}
validate={{
mediaDirectoryName: (value) => {
// NOTE: This value is prepended with either `files|images/`
// and nested directories are separated by `/` as well.
const decodedValues = decodeURIComponent(value).split("/")
return decodedValues.every(
(val) => !specialCharactersRegexTest.test(val)
)
},
}}
/>
</Switch>
</>
Expand Down
21 changes: 18 additions & 3 deletions src/layouts/ResourceRoom/ResourceRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,20 @@ import { useErrorToast, useSuccessToast } from "utils/toasts"

import { DirectoryData, DirectoryInfoProps } from "types/directory"
import { ResourceRoomRouteParams } from "types/resources"
import { DEFAULT_RETRY_MSG, deslugifyDirectory } from "utils"
import {
DEFAULT_RETRY_MSG,
deslugifyDirectory,
resourceCategoryRegexTest,
} from "utils"

import { ResourceRoomNameUpdateProps } from "../../types/directory"
import { SiteEditLayout } from "../layouts"

import { CategoryCard, ResourceBreadcrumb } from "./components"

const INVALID_CHAR_MESSAGE =
"Please ensure that you only use alphanumeric characters with dashes and space!"

const EmptyResourceRoom = () => {
const params = useParams<ResourceRoomRouteParams>()
const { siteName } = params
Expand Down Expand Up @@ -142,6 +149,10 @@ const EmptyResourceRoom = () => {
placeholder="Resource room name"
{...register("newDirectoryName", {
required: "Please enter resource room name",
pattern: {
value: resourceCategoryRegexTest,
message: INVALID_CHAR_MESSAGE,
},
})}
/>
<FormErrorMessage>
Expand Down Expand Up @@ -375,10 +386,14 @@ const ResourceRoomContent = ({
>
<FormLabel>Resource room title</FormLabel>
<Input
placeholder="New resource room name"
placeholder="New resource oom name"
{...register("newDirectoryName", {
required:
"Please ensure that you have entered a resource room name!",
pattern: {
value: resourceCategoryRegexTest,
message: INVALID_CHAR_MESSAGE,
},
})}
/>
<FormErrorMessage>
Expand All @@ -394,7 +409,7 @@ const ResourceRoomContent = ({
<Button
type="submit"
isLoading={isUpdateResourceRoomNameLoading}
isDisabled={isWriteDisabled}
isDisabled={isWriteDisabled || !!errors.newDirectoryName}
>
Save
</Button>
Expand Down
49 changes: 44 additions & 5 deletions src/routing/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Box, Center, Spinner } from "@chakra-ui/react"
import { useGrowthBook } from "@growthbook/growthbook-react"
import axios from "axios"
import _ from "lodash"
import _, { identity } from "lodash"
import { useEffect } from "react"
import { Redirect, Route, RouteProps, useLocation } from "react-router-dom"

Expand All @@ -12,6 +12,8 @@ import { getSiteNameAttributeFromPath } from "utils/growthbook"

import { GBAttributes } from "types/featureFlags"

import { WithValidator } from "./types"

// axios settings
axios.defaults.withCredentials = true

Expand All @@ -25,7 +27,7 @@ export const ProtectedRoute = ({
children,
component: WrappedComponent,
...rest
}: RouteProps): JSX.Element => {
}: WithValidator<RouteProps>): JSX.Element => {
const {
displayedName,
isLoading,
Expand All @@ -35,8 +37,27 @@ export const ProtectedRoute = ({
contactNumber,
} = useLoginContext()
const growthbook = useGrowthBook()

const currPath = useLocation().pathname
const siteNameFromPath = getSiteNameAttributeFromPath(currPath)
const { validate } = rest

const validateParams = (
params: Record<string, string | undefined> | undefined
) => {
return _.entries(params)
.map(([key, value]) => {
// NOTE: There's no provided validation function
// so we will assume it's valid
if (!validate?.[key]) return true

// NOTE: If the value is falsy, we will return true as there's nothing to validate
if (!value) return true

return validate[key](value)
})
.every(identity)
}

useEffect(() => {
if (growthbook) {
Expand Down Expand Up @@ -75,7 +96,19 @@ export const ProtectedRoute = ({
}

if (displayedName && children) {
return <Route {...rest}>{children}</Route>
return (
<Route {...rest}>
{({ match }) => {
const isValid = validateParams(match?.params)

if (!isValid) {
return <Redirect to="/not-found" />
}

return <>{children}</>
}}
</Route>
)
}

if (displayedName && WrappedComponent) {
Expand All @@ -84,11 +117,17 @@ export const ProtectedRoute = ({
{...rest}
render={(props) => {
const { match } = props
const { params } = match
const isValid = validateParams(match?.params)

if (!isValid) {
return <Redirect to="/not-found" />
}

const newMatch = {
...match,
decodedParams: getDecodedParams(prune(params)),
decodedParams: getDecodedParams(prune(match.params)),
}

return <WrappedComponent {...rest} {...props} match={newMatch} />
}}
/>
Expand Down
5 changes: 4 additions & 1 deletion src/routing/ProtectedRouteWithProps.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ import { RouteProps as BaseRouteProps } from "react-router-dom"
import FallbackComponent from "components/FallbackComponent"

import { ProtectedRoute } from "./ProtectedRoute"
import { WithValidator } from "./types"

type RouteProps = {
component?: () => JSX.Element
onClose: () => void
} & BaseRouteProps

export const ProtectedRouteWithProps = (props: RouteProps): JSX.Element => {
export const ProtectedRouteWithProps = (
props: WithValidator<RouteProps>
): JSX.Element => {
return (
<Sentry.ErrorBoundary fallback={FallbackComponent}>
<ProtectedRoute {...props} />
Expand Down
Loading
Loading