Skip to content

Commit

Permalink
fix: ✨ Allow webhook with basic auth
Browse files Browse the repository at this point in the history
  • Loading branch information
baptisteArno committed Feb 15, 2022
1 parent b95d907 commit 93e8f90
Show file tree
Hide file tree
Showing 9 changed files with 38 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
IntegrationStepType,
LogicStepType,
Step,
StepIndices,
StepOptions,
TextBubbleStep,
Webhook,
Expand Down Expand Up @@ -44,7 +43,6 @@ type Props = {
onExpandClick: () => void
onStepChange: (updates: Partial<Step>) => void
onTestRequestClick: () => void
indices: StepIndices
}

export const SettingsPopoverContent = ({ onExpandClick, ...props }: Props) => {
Expand Down Expand Up @@ -87,13 +85,11 @@ export const StepSettings = ({
step,
onStepChange,
onTestRequestClick,
indices,
}: {
step: Step
webhook?: Webhook
onStepChange: (step: Partial<Step>) => void
onTestRequestClick: () => void
indices: StepIndices
}) => {
const handleOptionsChange = (options: StepOptions) => {
onStepChange({ options } as Partial<Step>)
Expand Down Expand Up @@ -210,7 +206,6 @@ export const StepSettings = ({
onOptionsChange={handleOptionsChange}
onWebhookChange={handleWebhookChange}
onTestRequestClick={onTestRequestClick}
indices={indices}
/>
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import {
Webhook,
ResponseVariableMapping,
WebhookStep,
StepIndices,
} from 'models'
import { DropdownList } from 'components/shared/DropdownList'
import { TableList, TableListItemProps } from 'components/shared/TableList'
Expand All @@ -39,15 +38,13 @@ type Props = {
onOptionsChange: (options: WebhookOptions) => void
onWebhookChange: (updates: Partial<Webhook>) => void
onTestRequestClick: () => void
indices: StepIndices
}

export const WebhookSettings = ({
step: { webhook, options },
step: { webhook, options, blockId, id: stepId },
onOptionsChange,
onWebhookChange,
onTestRequestClick,
indices,
}: Props) => {
const { typebot, save } = useTypebot()
const [isTestResponseLoading, setIsTestResponseLoading] = useState(false)
Expand Down Expand Up @@ -85,12 +82,11 @@ export const WebhookSettings = ({
await save()
const { data, error } = await executeWebhook(
typebot.id,
webhook.id,
convertVariableForTestToVariables(
options.variablesForTest,
typebot.variables
),
indices
{ blockId, stepId }
)
if (error) return toast({ title: error.name, description: error.message })
setTestResponse(JSON.stringify(data, undefined, 2))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,6 @@ export const StepNode = ({
onExpandClick={handleExpandClick}
onStepChange={handleStepChange}
onTestRequestClick={updateOptions}
indices={indices}
/>
)}
{isMediaBubbleStep(localStep) && (
Expand All @@ -230,7 +229,6 @@ export const StepNode = ({
step={localStep}
onStepChange={handleStepChange}
onTestRequestClick={updateOptions}
indices={indices}
/>
</SettingsModal>
</Popover>
Expand Down
2 changes: 1 addition & 1 deletion apps/builder/contexts/TypebotContext/actions/edges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { WritableDraft } from 'immer/dist/types/types-external'
import { generate } from 'short-uuid'
import { SetTypebot } from '../TypebotContext'
import { produce } from 'immer'
import { byId, isDefined, isNotDefined } from 'utils'
import { byId, isDefined } from 'utils'

export type EdgesActions = {
createEdge: (edge: Omit<Edge, 'id'>) => void
Expand Down
7 changes: 3 additions & 4 deletions apps/builder/services/integrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { sendRequest } from 'utils'
import { stringify } from 'qs'
import useSWR from 'swr'
import { fetcher } from './utils'
import { StepIndices, Variable, VariableForTest, WebhookResponse } from 'models'
import { Variable, VariableForTest, WebhookResponse } from 'models'

export const getGoogleSheetsConsentScreenUrl = (
redirectUrl: string,
Expand Down Expand Up @@ -68,12 +68,11 @@ export const useSheets = ({

export const executeWebhook = (
typebotId: string,
webhookId: string,
variables: Variable[],
{ blockIndex, stepIndex }: StepIndices
{ blockId, stepId }: { blockId: string; stepId: string }
) =>
sendRequest<WebhookResponse>({
url: `/api/typebots/${typebotId}/blocks/${blockIndex}/steps/${stepIndex}/executeWebhook`,
url: `${process.env.NEXT_PUBLIC_VIEWER_HOST}/api/typebots/${typebotId}/blocks/${blockId}/steps/${stepId}/executeWebhook`,
method: 'POST',
body: {
variables,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,26 @@ import { KeyValue, Typebot, Variable, Webhook, WebhookResponse } from 'models'
import { parseVariables } from 'bot-engine'
import { NextApiRequest, NextApiResponse } from 'next'
import got, { Method, Headers, HTTPError } from 'got'
import { methodNotAllowed } from 'utils'
import { byId, initMiddleware, methodNotAllowed } from 'utils'
import { stringify } from 'qs'
import { withSentry } from '@sentry/nextjs'
import Cors from 'cors'

const cors = initMiddleware(Cors())
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
await cors(req, res)
if (req.method === 'POST') {
const typebotId = req.query.typebotId.toString()
const blockIndex = Number(req.query.blockIndex)
const stepIndex = Number(req.query.stepIndex)
const blockId = req.query.blockId.toString()
const stepId = req.query.stepId.toString()
const variables = JSON.parse(req.body).variables as Variable[]
const typebot = await prisma.typebot.findUnique({
where: { id: typebotId },
})
const step = (typebot as unknown as Typebot).blocks[blockIndex].steps[
stepIndex
]
if (!('webhook' in step))
const step = (typebot as unknown as Typebot).blocks
.find(byId(blockId))
?.steps.find(byId(stepId))
if (!step || !('webhook' in step))
return res
.status(404)
.send({ statusCode: 404, data: { message: `Couldn't find webhook` } })
Expand All @@ -38,6 +41,19 @@ const executeWebhook = async (
statusCode: 400,
data: { message: `Webhook doesn't have url or method` },
}
const basicAuth: { username?: string; password?: string } = {}
const basicAuthHeaderIdx = webhook.headers.findIndex(
(h) =>
h.key?.toLowerCase() === 'authorization' &&
h.value?.toLowerCase().includes('basic')
)
if (basicAuthHeaderIdx !== -1) {
const [username, password] =
webhook.headers[basicAuthHeaderIdx].value?.slice(6).split(':') ?? []
basicAuth.username = username
basicAuth.password = password
webhook.headers.splice(basicAuthHeaderIdx, 1)
}
const headers = convertKeyValueTableToObject(webhook.headers, variables) as
| Headers
| undefined
Expand All @@ -51,6 +67,7 @@ const executeWebhook = async (
{
method: webhook.method as Method,
headers,
...basicAuth,
json:
contentType !== 'x-www-form-urlencoded' && webhook.body
? JSON.parse(parseVariables(variables)(webhook.body))
Expand Down
9 changes: 3 additions & 6 deletions packages/bot-engine/src/components/ChatBlock/ChatBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,20 @@ import { parseRetryStep, stepCanBeRetried } from 'services/inputs'
type ChatBlockProps = {
steps: PublicStep[]
startStepIndex: number
blockIndex: number
onScroll: () => void
onBlockEnd: (edgeId?: string) => void
}

export const ChatBlock = ({
steps,
startStepIndex,
blockIndex,
onScroll,
onBlockEnd,
}: ChatBlockProps) => {
const { typebot, updateVariableValue, createEdge, apiHost, isPreview } =
useTypebot()
const [displayedSteps, setDisplayedSteps] = useState<PublicStep[]>([])

const currentStepIndex = displayedSteps.length - 1

useEffect(() => {
const nextStep = steps[startStepIndex]
if (nextStep) setDisplayedSteps([...displayedSteps, nextStep])
Expand Down Expand Up @@ -65,8 +61,9 @@ export const ChatBlock = ({
step: currentStep,
context: {
apiHost,
typebotId: typebot.id,
indices: { blockIndex, stepIndex: currentStepIndex },
typebotId: typebot.typebotId,
blockId: currentStep.blockId,
stepId: currentStep.id,
variables: typebot.variables,
isPreview,
updateVariableValue,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ export const ConversationContainer = ({
key={displayedBlock.block.id + idx}
steps={displayedBlock.block.steps}
startStepIndex={displayedBlock.startStepIndex}
blockIndex={idx}
onScroll={autoScrollToBottom}
onBlockEnd={displayNextBlock}
/>
Expand Down
10 changes: 5 additions & 5 deletions packages/bot-engine/src/services/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ import { parseVariables, parseVariablesInObject } from './variable'

const safeEval = eval

type Indices = { blockIndex: number; stepIndex: number }
type IntegrationContext = {
apiHost: string
typebotId: string
indices: Indices
blockId: string
stepId: string
isPreview: boolean
variables: Variable[]
updateVariableValue: (variableId: string, value: string) => void
Expand Down Expand Up @@ -153,17 +153,17 @@ const parseCellValues = (
const executeWebhook = async (
step: WebhookStep,
{
indices,
blockId,
stepId,
variables,
updateVariableValue,
typebotId,
apiHost,
}: IntegrationContext
) => {
if (!step.webhook) return step.outgoingEdgeId
const { blockIndex, stepIndex } = indices
const { data, error } = await sendRequest({
url: `${apiHost}/api/typebots/${typebotId}/blocks/${blockIndex}/steps/${stepIndex}/executeWebhook`,
url: `${apiHost}/api/typebots/${typebotId}/blocks/${blockId}/steps/${stepId}/executeWebhook`,
method: 'POST',
body: {
variables,
Expand Down

4 comments on commit 93e8f90

@vercel
Copy link

@vercel vercel bot commented on 93e8f90 Feb 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

docs – ./apps/docs

docs-typebot-io.vercel.app
docs-git-main-typebot-io.vercel.app
docs.typebot.io

@vercel
Copy link

@vercel vercel bot commented on 93e8f90 Feb 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

viewer-v2 – ./apps/viewer

typebot-viewer.vercel.app
viewer-v2-git-main-typebot-io.vercel.app
viewer-v2-typebot-io.vercel.app

@vercel
Copy link

@vercel vercel bot commented on 93e8f90 Feb 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

builder-v2 – ./apps/builder

builder-v2-git-main-typebot-io.vercel.app
app.typebot.io
builder-v2-typebot-io.vercel.app

@vercel
Copy link

@vercel vercel bot commented on 93e8f90 Feb 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.