Skip to content

Commit

Permalink
fix: unflatten form data into correct body format
Browse files Browse the repository at this point in the history
The format for bodies with traits dictates that the traits come in through their
own object. This becomes especially visible when using an SDK client compiled
with a newer version of OpenAPI generator, as they only process properties which
are defined in the API schema, which is not the case for flattened properties.

Fixes ory#93
  • Loading branch information
DASPRiD committed Mar 20, 2023
1 parent 40bc4ab commit ab0745e
Showing 1 changed file with 37 additions and 12 deletions.
49 changes: 37 additions & 12 deletions src/react-components/ory/helpers/user-auth-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,19 @@ import { formStyle } from "../../../theme"
import { FilterFlowNodes } from "./filter-flow-nodes"
import { SelfServiceFlow } from "./types"

export type UpdateBody =
| UpdateLoginFlowBody
| UpdateRegistrationFlowBody
| UpdateRecoveryFlowBody
| UpdateVerificationFlowBody
| UpdateSettingsFlowBody

export type UserAuthFormAdditionalProps = {
onSubmit?: ({
body,
event,
}: {
body:
| UpdateLoginFlowBody
| UpdateRegistrationFlowBody
| UpdateRecoveryFlowBody
| UpdateVerificationFlowBody
| UpdateSettingsFlowBody
body: UpdateBody
event?: React.FormEvent<HTMLFormElement>
}) => void
}
Expand All @@ -38,6 +40,34 @@ export interface UserAuthFormProps
className?: string
}

const traitRegexp = /^traits\.(.+)$/

const unflattenFormData = (formData: FormData): UpdateBody => {
const body : Record<string, string | object> = {}
const traits: Record<string, string> = {}

for (const [key, value] of formData) {
if (typeof value !== "string") {
continue
}

const match = traitRegexp.exec(key)

if (!match) {
body[key] = value
continue
}

traits[match[1]] = value
}

if (Object.keys(traits).length > 0) {
body.traits = traits
}

return body as unknown as UpdateBody
}

export const UserAuthForm = ({
flow,
children,
Expand Down Expand Up @@ -65,12 +95,7 @@ export const UserAuthForm = ({
const formData = new FormData(form)

// map the entire form data to JSON for the request body
let body = Object.fromEntries(formData) as unknown as
| UpdateLoginFlowBody
| UpdateRegistrationFlowBody
| UpdateRecoveryFlowBody
| UpdateVerificationFlowBody
| UpdateSettingsFlowBody
let body = unflattenFormData(formData)

// We need the method specified from the name and value of the submit button.
// when multiple submit buttons are present, the clicked one's value is used.
Expand Down

0 comments on commit ab0745e

Please sign in to comment.