Skip to content

Commit

Permalink
♻️ (auth) Make sure new users have an email
Browse files Browse the repository at this point in the history
Also fix after-auth redirections

Closes #323
  • Loading branch information
baptisteArno committed Feb 18, 2023
1 parent 0e1fa4e commit 0831dcf
Show file tree
Hide file tree
Showing 7 changed files with 48 additions and 8 deletions.
24 changes: 24 additions & 0 deletions apps/builder/src/features/auth/components/SignInError.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Alert } from '@chakra-ui/react'

type Props = {
error: string
}
const errors: Record<string, string> = {
Signin: 'Try signing with a different account.',
OAuthSignin: 'Try signing with a different account.',
OAuthCallback: 'Try signing with a different account.',
OAuthCreateAccount: 'Email not found. Try signing with a different provider.',
EmailCreateAccount: 'Try signing with a different account.',
Callback: 'Try signing with a different account.',
OAuthAccountNotLinked:
'To confirm your identity, sign in with the same account you used originally.',
CredentialsSignin:
'Sign in failed. Check the details you provided are correct.',
default: 'An error occurred. Please try again.',
}

export const SignInError = ({ error }: Props) => (
<Alert status="error" variant="solid" rounded="md">
{errors[error] ?? errors[error]}
</Alert>
)
10 changes: 8 additions & 2 deletions apps/builder/src/features/auth/components/SignInForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { useRouter } from 'next/router'
import { BuiltInProviderType } from 'next-auth/providers'
import { useToast } from '@/hooks/useToast'
import { TextLink } from '@/components/TextLink'
import { SignInError } from './SignInError'

type Props = {
defaultEmail?: string
Expand All @@ -48,8 +49,10 @@ export const SignInForm = ({
!isLoadingProviders && Object.keys(providers ?? {}).length === 0

useEffect(() => {
if (status === 'authenticated')
router.replace({ pathname: '/typebots', query: router.query })
if (status === 'authenticated') {
router.replace(router.query.callbackUrl?.toString() ?? '/typebots')
return
}
;(async () => {
const providers = await getProviders()
setProviders(providers ?? undefined)
Expand Down Expand Up @@ -131,6 +134,9 @@ export const SignInForm = ({
</HStack>
</>
)}
{router.query.error && (
<SignInError error={router.query.error.toString()} />
)}
</Stack>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { stringify } from 'qs'
import { BuiltInProviderType } from 'next-auth/providers'
import { GoogleLogo } from '@/components/GoogleLogo'
import { AzureAdLogo, FacebookLogo, GitlabLogo } from './logos'
import { omit } from 'utils'

type Props = {
providers:
Expand All @@ -28,7 +29,9 @@ export const SocialLoginButtons = ({ providers }: Props) => {
const handleSignIn = async (provider: string) => {
setAuthLoading(provider)
await signIn(provider, {
callbackUrl: `/typebots?${stringify(query)}`,
callbackUrl:
query.callbackUrl?.toString() ??
`/typebots?${stringify(omit(query, 'error', 'callbackUrl'))}`,
})
setTimeout(() => setAuthLoading(undefined), 3000)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import {
import { useAutoSave } from '@/hooks/useAutoSave'
import { createWebhookQuery } from '@/features/blocks/integrations/webhook/queries/createWebhookQuery'
import { duplicateWebhookQuery } from '@/features/blocks/integrations/webhook/queries/duplicateWebhookQuery'
import { useSession } from 'next-auth/react'

const autoSaveTimeout = 10000

Expand Down Expand Up @@ -103,7 +104,8 @@ export const TypebotProvider = ({
children: ReactNode
typebotId: string
}) => {
const router = useRouter()
const { status } = useSession()
const { push } = useRouter()
const { showToast } = useToast()

const { typebot, publishedTypebot, webhooks, isReadOnly, isLoading, mutate } =
Expand Down Expand Up @@ -246,15 +248,15 @@ export const TypebotProvider = ({
}, [localTypebot])

useEffect(() => {
if (isLoading) return
if (status !== 'authenticated' || isLoading) return
if (!typebot) {
showToast({ status: 'info', description: "Couldn't find typebot" })
router.replace('/typebots')
push('/typebots')
return
}
setLocalTypebot({ ...typebot })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isLoading])
}, [status, isLoading])

const updateLocalTypebot = (updates: UpdateTypebotPayload) =>
localTypebot && setLocalTypebot({ ...localTypebot, ...updates })
Expand Down
2 changes: 1 addition & 1 deletion apps/builder/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const { ToastContainer, toast } = createStandaloneToast(customTheme)
const App = ({
Component,
pageProps: { session, ...pageProps },
}: AppProps<{ session: Session }>) => {
}: AppProps<{ session?: Session }>) => {
useRouterProgressBar()
const { query, pathname, isReady } = useRouter()

Expand Down
3 changes: 3 additions & 0 deletions apps/builder/src/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,9 @@ const handler = (req: NextApiRequest, res: NextApiResponse) => {
session: {
strategy: 'database',
},
pages: {
signIn: '/signin',
},
callbacks: {
session: async ({ session, user }) => {
const userFromDb = user as User
Expand Down
2 changes: 2 additions & 0 deletions apps/builder/src/pages/api/auth/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
export function CustomAdapter(p: PrismaClient): Adapter {
return {
createUser: async (data: Omit<AdapterUser, 'id'>) => {
if (!data.email)
throw Error('Provider did not forward email but it is required')
const user = { id: createId(), email: data.email as string }
const { invitations, workspaceInvitations } = await getNewUserInvitations(
p,
Expand Down

4 comments on commit 0831dcf

@vercel
Copy link

@vercel vercel bot commented on 0831dcf Feb 18, 2023

Choose a reason for hiding this comment

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

@vercel
Copy link

@vercel vercel bot commented on 0831dcf Feb 18, 2023

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-git-main-typebot-io.vercel.app
docs.typebot.io
docs-typebot-io.vercel.app

@vercel
Copy link

@vercel vercel bot commented on 0831dcf Feb 18, 2023

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-typebot-io.vercel.app
app.typebot.io
builder-v2-git-main-typebot-io.vercel.app

@vercel
Copy link

@vercel vercel bot commented on 0831dcf Feb 18, 2023

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

bot.viralsangat.com
bot.winglabs.com.br
carsalesenquiry.com
chat.marius.digital
chatbot.matthesv.de
chatbot.repplai.com
demo.botscientis.us
demo.wemakebots.xyz
forms.webisharp.com
kbsub.wpwakanda.com
live.botscientis.us
mentoria.omelhor.vc
nutrisamirbayde.com
order.maitempah.com
quest.wpwakanda.com
support.wawplus.com
survey1.digienge.io
surveys.essiell.com
test.botscientis.us
test.reventepro.com
typebot.stillio.com
wordsandimagery.com
88584434.therpm.club
92109660.therpm.club
abbonamento.bwell.it
bium.gratirabbit.com
bot.ansuraniphone.my
bot.barrettamario.it
bot.cotemeuplano.com
bot.leadbooster.help
bot.mycompay.reviews
chat.hayurihijab.com
chatbee.agfunnel.com
click.sevenoways.com
connect.growthguy.in
forms.bonanza.design
hello.advergreen.com
kuiz.sistemniaga.com
offer.botscientis.us
sellmycarglasgow.com
talkbot.agfunnel.com
tenorioadvogados.com
uppity.wpwakanda.com
abutton.wpwakanda.com
acelera.maxbot.com.br
aidigitalmarketing.kr
bbutton.wpwakanda.com
bot.coachayongzul.com
bot.digitalpointer.id
bot.eikju.photography
bot.incusservices.com
bot.meuesocial.com.br
bot.mycompany.reviews
bot.outstandbrand.com
bot.robertohairlab.it
help.atlasoutfittersk9.com
herbalife.barrettamario.it
homepageonly.wpwakanda.com
liveconvert.kandalearn.com
mainmenu1one.wpwakanda.com
tarian.theiofoundation.org
ted.meujalecobrasil.com.br
type.dericsoncalari.com.br
bot.pinpointinteractive.com
bot.polychromes-project.com
bot.seidinembroseanchetu.it
chatbot.berbelanjabiz.trade
designguide.techyscouts.com
liveconvert2.kandalearn.com
presente.empresarias.com.mx
sell.sellthemotorhome.co.uk
anamnese.odontopavani.com.br
austin.channelautomation.com
bot.marketingplusmindset.com
bot.seidibergamoseanchetu.it
desabafe.sergiolimajr.com.br
download.venturemarketing.in
piazzatorre.barrettamario.it
type.cookieacademyonline.com
bot.brigadeirosemdrama.com.br
forms.escoladeautomacao.com.br
onboarding.libertydreamcare.ie
type.talitasouzamarques.com.br
agendamento.sergiolimajr.com.br
anamnese.clinicamegasjdr.com.br
bookings.littlepartymonkeys.com
bot.comercializadoraomicron.com
elevateyourmind.groovepages.com
viewer-v2-typebot-io.vercel.app
yourfeedback.comebackreward.com
gerador.verificadordehospedes.com
personal-trainer.barrettamario.it
preagendamento.sergiolimajr.com.br
studiotecnicoimmobiliaremerelli.it
download.thailandmicespecialist.com
register.thailandmicespecialist.com
bot.studiotecnicoimmobiliaremerelli.it
pesquisa.escolamodacomproposito.com.br
anamnese.clinicaramosodontologia.com.br
viewer-v2-git-main-typebot-io.vercel.app

Please sign in to comment.