Skip to content

Commit

Permalink
Merge pull request #252 from atls/feat/overwrite-sdk
Browse files Browse the repository at this point in the history
feat/overwrite-sdk
  • Loading branch information
TorinAsakura authored Oct 30, 2023
2 parents 70def6e + f35feb6 commit 8a10281
Show file tree
Hide file tree
Showing 14 changed files with 110 additions and 50 deletions.
8 changes: 8 additions & 0 deletions packages/identity-integration/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# NextJS Custom Workshop

## BREAKING CHANGE 0.0.16

- Необходим глобальный провайдер `KratosClientProvider`. По умолчанию он предоставляет
стандартный клиент `kratos`, однако его можно будет изменять/расширять по потребности в
проекте, а также URL редиректа для некоторых ошибок.
- Добавлена кастомизация URL для редиректа в случае ошибок, например пользователь уже авторизован.
- Расширен конструктов класса `KratosClient`

## BREAKING CHANGE 0.0.14

- Обновлены пакеты `ory/kratos-client`, `ory/integrations`, `nextjs`
Expand Down
6 changes: 4 additions & 2 deletions packages/identity-integration/src/flows/error.flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useState } from 'react'
import { useEffect } from 'react'

import { ErrorProvider } from '../providers'
import { kratos } from '../sdk'
import { useKratosClient } from '../providers'

export interface ErrorErrorProps {
returnToUrl?: string
Expand All @@ -20,14 +20,16 @@ export const ErrorFlow: FC<PropsWithChildren<ErrorErrorProps>> = ({ children, re
const [loading, setLoading] = useState<boolean>(true)
const router = useRouter()

const { kratosClient } = useKratosClient()

const { id } = router.query

useEffect(() => {
if (!router.isReady || error) {
return
}

kratos
kratosClient
.getFlowError({ id: String(id) })
.then(({ data }) => {
setError(data)
Expand Down
15 changes: 9 additions & 6 deletions packages/identity-integration/src/flows/handle-errors.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ export const handleFlowError = <S>(
router: NextRouter,
flowType: 'login' | 'registration' | 'settings' | 'recovery' | 'verification',
onResetFlow: Dispatch<SetStateAction<S | undefined>>,
onErrorRedirectUrl: string,
onError?: (error: any) => void
) =>
async (error: AxiosError<any>) => {
const redirectToSettings = onErrorRedirectUrl

switch (error.response?.data.error?.id) {
case 'session_aal2_required':
window.location.href = error.response?.data.redirect_browser_to
Expand All @@ -23,7 +26,7 @@ export const handleFlowError = <S>(
if (error.response?.data?.redirect_browser_to) {
window.location.href = error.response.data.redirect_browser_to
} else {
await router.push('/profile/settings')
await router.push(redirectToSettings)
}

return
Expand All @@ -38,7 +41,7 @@ export const handleFlowError = <S>(

onResetFlow(undefined)

await router.push(flowType === 'settings' ? '/profile/settings' : '/auth/' + flowType)
await router.push(flowType === 'settings' ? redirectToSettings : '/auth/' + flowType)

return
case 'self_service_flow_expired':
Expand All @@ -48,7 +51,7 @@ export const handleFlowError = <S>(

onResetFlow(undefined)

await router.push(flowType === 'settings' ? '/profile/settings' : '/auth/' + flowType)
await router.push(flowType === 'settings' ? redirectToSettings : '/auth/' + flowType)

return
case 'security_csrf_violation':
Expand All @@ -58,13 +61,13 @@ export const handleFlowError = <S>(

onResetFlow(undefined)

await router.push(flowType === 'settings' ? '/profile/settings' : '/auth/' + flowType)
await router.push(flowType === 'settings' ? redirectToSettings : '/auth/' + flowType)

return
case 'security_identity_mismatch':
onResetFlow(undefined)

await router.push(flowType === 'settings' ? '/profile/settings' : '/auth/' + flowType)
await router.push(flowType === 'settings' ? redirectToSettings : '/auth/' + flowType)

return
case 'browser_location_change_required':
Expand All @@ -77,7 +80,7 @@ export const handleFlowError = <S>(
case 410:
onResetFlow(undefined)

await router.push(flowType === 'settings' ? '/profile/settings' : '/auth/' + flowType)
await router.push(flowType === 'settings' ? redirectToSettings : '/auth/' + flowType)

return
}
Expand Down
15 changes: 8 additions & 7 deletions packages/identity-integration/src/flows/login.flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { FlowProvider } from '../providers'
import { ValuesProvider } from '../providers'
import { ValuesStore } from '../providers'
import { SubmitProvider } from '../providers'
import { kratos } from '../sdk'
import { useKratosClient } from '../providers'
import { handleFlowError } from './handle-errors.util'

export interface LoginFlowProps {
Expand All @@ -33,6 +33,7 @@ export const LoginFlow: FC<PropsWithChildren<LoginFlowProps>> = ({
const [loading, setLoading] = useState<boolean>(true)
const values = useMemo(() => new ValuesStore(), [])
const router = useRouter()
const { kratosClient, returnToSettingsUrl } = useKratosClient()

const { return_to: returnTo, flow: flowId, refresh, aal } = router.query

Expand All @@ -42,18 +43,18 @@ export const LoginFlow: FC<PropsWithChildren<LoginFlowProps>> = ({
}

if (flowId) {
kratos
kratosClient
.getLoginFlow({ id: String(flowId) }, { withCredentials: true })
.then(({ data }) => {
setFlow(data)
})
.catch(handleFlowError(router, 'login', setFlow, onError))
.catch(handleFlowError(router, 'login', setFlow, returnToSettingsUrl, onError))
.finally(() => setLoading(false))

return
}

kratos
kratosClient
.createBrowserLoginFlow(
{
refresh: Boolean(refresh),
Expand All @@ -65,7 +66,7 @@ export const LoginFlow: FC<PropsWithChildren<LoginFlowProps>> = ({
.then(({ data }) => {
setFlow(data)
})
.catch(handleFlowError(router, 'login', setFlow, onError))
.catch(handleFlowError(router, 'login', setFlow, returnToSettingsUrl, onError))
.finally(() => setLoading(false))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [flowId, router, router.isReady, aal, refresh, returnTo, flow, onError])
Expand All @@ -85,7 +86,7 @@ export const LoginFlow: FC<PropsWithChildren<LoginFlowProps>> = ({
...(override || {}),
}

kratos
kratosClient
.updateLoginFlow(
{ flow: String(flow?.id), updateLoginFlowBody: body },
{ withCredentials: true }
Expand All @@ -97,7 +98,7 @@ export const LoginFlow: FC<PropsWithChildren<LoginFlowProps>> = ({
router.push(returnToUrl ?? '/')
}
})
.catch(handleFlowError(router, 'login', setFlow))
.catch(handleFlowError(router, 'login', setFlow, returnToSettingsUrl))
.catch((error: AxiosError<KratosLoginFlow>) => {
if (error.response?.status === 400) {
setFlow(error.response?.data)
Expand Down
8 changes: 5 additions & 3 deletions packages/identity-integration/src/flows/logout.flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useRouter } from 'next/router'
import { useState } from 'react'
import { useEffect } from 'react'

import { kratos } from '../sdk'
import { useKratosClient } from '../providers'

interface LogoutFlowProps {
returnToUrl?: string
Expand All @@ -17,6 +17,7 @@ interface LogoutFlowProps {
export const LogoutFlow: FC<PropsWithChildren<LogoutFlowProps>> = ({ children, returnToUrl }) => {
const [logoutToken, setLogoutToken] = useState<string>('')
const router = useRouter()
const { kratosClient } = useKratosClient()

const { return_to: returnTo } = router.query

Expand All @@ -25,7 +26,7 @@ export const LogoutFlow: FC<PropsWithChildren<LogoutFlowProps>> = ({ children, r
return
}

kratos
kratosClient
.createBrowserLogoutFlow(
{ returnTo: returnTo?.toString() ?? returnToUrl },
{ withCredentials: true }
Expand All @@ -47,10 +48,11 @@ export const LogoutFlow: FC<PropsWithChildren<LogoutFlowProps>> = ({ children, r

useEffect(() => {
if (logoutToken) {
kratos
kratosClient
.updateLogoutFlow({ token: logoutToken }, { withCredentials: true })
.then(() => router.reload())
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [logoutToken, router])

// eslint-disable-next-line react/jsx-no-useless-fragment
Expand Down
16 changes: 9 additions & 7 deletions packages/identity-integration/src/flows/recovery.flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { FlowProvider } from '../providers'
import { ValuesProvider } from '../providers'
import { ValuesStore } from '../providers'
import { SubmitProvider } from '../providers'
import { kratos } from '../sdk'
import { useKratosClient } from '../providers'
import { handleFlowError } from './handle-errors.util'

export interface RecoveryFlowProps {
Expand All @@ -33,6 +33,7 @@ export const RecoveryFlow: FC<PropsWithChildren<RecoveryFlowProps>> = ({
const [loading, setLoading] = useState<boolean>(true)
const values = useMemo(() => new ValuesStore(), [])
const router = useRouter()
const { kratosClient, returnToSettingsUrl } = useKratosClient()

const { return_to: returnTo, flow: flowId, refresh, aal } = router.query

Expand All @@ -42,18 +43,18 @@ export const RecoveryFlow: FC<PropsWithChildren<RecoveryFlowProps>> = ({
}

if (flowId) {
kratos
kratosClient
.getRecoveryFlow({ id: String(flowId) }, { withCredentials: true })
.then(({ data }) => {
setFlow(data)
})
.catch(handleFlowError(router, 'recovery', setFlow, onError))
.catch(handleFlowError(router, 'recovery', setFlow, returnToSettingsUrl, onError))
.finally(() => setLoading(false))

return
}

kratos
kratosClient
.createBrowserRecoveryFlow(
{ returnTo: returnTo?.toString() ?? returnToUrl },
{
Expand All @@ -63,7 +64,7 @@ export const RecoveryFlow: FC<PropsWithChildren<RecoveryFlowProps>> = ({
.then(({ data }) => {
setFlow(data)
})
.catch(handleFlowError(router, 'recovery', setFlow, onError))
.catch(handleFlowError(router, 'recovery', setFlow, returnToSettingsUrl, onError))
.catch((error: AxiosError<KratosRecoveryFlow>) => {
if (error.response?.status === 400) {
setFlow(error.response?.data)
Expand Down Expand Up @@ -93,15 +94,15 @@ export const RecoveryFlow: FC<PropsWithChildren<RecoveryFlowProps>> = ({
...(override || {}),
}

kratos
kratosClient
.updateRecoveryFlow(
{ flow: String(flow?.id), updateRecoveryFlowBody: body },
{ withCredentials: true }
)
.then(({ data }) => {
setFlow(data)
})
.catch(handleFlowError(router, 'recovery', setFlow))
.catch(handleFlowError(router, 'recovery', setFlow, returnToSettingsUrl))
.catch((error: AxiosError<KratosRecoveryFlow>) => {
if (error.response?.status === 400) {
setFlow(error.response?.data)
Expand All @@ -114,6 +115,7 @@ export const RecoveryFlow: FC<PropsWithChildren<RecoveryFlowProps>> = ({
})
.finally(() => setSubmitting(false))
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[router, flow, values, setSubmitting]
)

Expand Down
15 changes: 8 additions & 7 deletions packages/identity-integration/src/flows/registration.flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { FlowProvider } from '../providers'
import { ValuesProvider } from '../providers'
import { ValuesStore } from '../providers'
import { SubmitProvider } from '../providers'
import { kratos } from '../sdk'
import { useKratosClient } from '../providers'
import { handleFlowError } from './handle-errors.util'

export interface RegistrationFlowProps {
Expand All @@ -37,6 +37,7 @@ export const RegistrationFlow: FC<PropsWithChildren<RegistrationFlowProps>> = ({
const [loading, setLoading] = useState<boolean>(true)
const values = useMemo(() => new ValuesStore(), [])
const router = useRouter()
const { kratosClient, returnToSettingsUrl } = useKratosClient()

const { return_to: returnTo, flow: flowId, refresh, aal } = router.query

Expand All @@ -46,18 +47,18 @@ export const RegistrationFlow: FC<PropsWithChildren<RegistrationFlowProps>> = ({
}

if (flowId) {
kratos
kratosClient
.getRegistrationFlow({ id: String(flowId) }, { withCredentials: true })
.then(({ data }) => {
setFlow(data)
})
.catch(handleFlowError(router, 'registration', setFlow, onError))
.catch(handleFlowError(router, 'registration', setFlow, returnToSettingsUrl, onError))
.finally(() => setLoading(false))

return
}

kratos
kratosClient
.createBrowserRegistrationFlow(
{ returnTo: returnTo?.toString() ?? returnToUrl },
{
Expand All @@ -67,7 +68,7 @@ export const RegistrationFlow: FC<PropsWithChildren<RegistrationFlowProps>> = ({
.then(({ data }) => {
setFlow(data)
})
.catch(handleFlowError(router, 'registration', setFlow, onError))
.catch(handleFlowError(router, 'registration', setFlow, returnToSettingsUrl, onError))
.finally(() => setLoading(false))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [flowId, router, router.isReady, aal, refresh, returnTo, flow, onError])
Expand Down Expand Up @@ -104,7 +105,7 @@ export const RegistrationFlow: FC<PropsWithChildren<RegistrationFlowProps>> = ({
...(override || {}),
}

kratos
kratosClient
.updateRegistrationFlow(
{ flow: String(flow?.id), updateRegistrationFlowBody: body },
{ withCredentials: true }
Expand All @@ -119,7 +120,7 @@ export const RegistrationFlow: FC<PropsWithChildren<RegistrationFlowProps>> = ({
router.push(returnToUrl ?? '/')
}
})
.catch(handleFlowError(router, 'registration', setFlow))
.catch(handleFlowError(router, 'registration', setFlow, returnToSettingsUrl))
.catch((error: AxiosError<KratosRegistrationFlow>) => {
if (error.response?.status === 400) {
setFlow(error.response?.data)
Expand Down
Loading

0 comments on commit 8a10281

Please sign in to comment.