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

Fix: hide the code input if the email was changed since the last sending #30

Merged
merged 2 commits into from
Dec 25, 2024
Merged
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
108 changes: 73 additions & 35 deletions src/widget/Login/ui/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { useCallback, useRef, useState } from 'react'

import { browserSupportsWebAuthn, startAuthentication } from '@simplewebauthn/browser'
import {
browserSupportsWebAuthn,
startAuthentication,
} from '@simplewebauthn/browser'
import { useMutation } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { CSSTransition } from 'react-transition-group'
Expand All @@ -19,7 +22,9 @@ import { Typography } from '~/shared/ui'

const emailSchema = z.string().email()

const codeSchema = z.string().regex(/^\d{6}$/, { message: 'Код должен содержать ровно 6 цифр' })
const codeSchema = z
.string()
.regex(/^\d{6}$/, { message: 'Код должен содержать ровно 6 цифр' })

export const LoginWidget = () => {
const { t } = useCustomTranslation()
Expand All @@ -28,36 +33,38 @@ export const LoginWidget = () => {

const hintRef = useRef(null)

const { showPromiseToast, dismissAllToasts, showErrorToast, showInfoToast } = useToast()
const { showPromiseToast, dismissAllToasts, showErrorToast, showInfoToast } =
useToast()

const codeInputVisibility = new Map([
const codeInputHeight = new Map([
[true, '40px'],
[false, '0px'],
])

const [email, setEmail] = useState<string>('')
const [code, setCode] = useState<string>('')

const { tryLoginPromise, confirmLoginPromise, loadingState, mutationState } = useOTPLogin({
onCodeSuccess: () => {
setTimeout(() => {
dismissAllToasts()
return navigate(Routes.HOME)
}, 700)
},
onCodeError(error) {
if (error instanceof Error) {
return showErrorToast(error.message)
}
return showErrorToast(t('oopsSomethingWentWrong'))
},
onLoginError(error) {
if (error instanceof Error) {
return showErrorToast(error.message)
}
return showErrorToast(t('oopsSomethingWentWrong'))
},
})
const { tryLoginPromise, confirmLoginPromise, loadingState, mutationState } =
useOTPLogin({
onCodeSuccess: () => {
setTimeout(() => {
dismissAllToasts()
return navigate(Routes.HOME)
}, 700)
},
onCodeError(error) {
if (error instanceof Error) {
return showErrorToast(error.message)
}
return showErrorToast(t('oopsSomethingWentWrong'))
},
onLoginError(error) {
if (error instanceof Error) {
return showErrorToast(error.message)
}
return showErrorToast(t('oopsSomethingWentWrong'))
},
})

const verifyLoginChallenge = useMutation({
mutationFn: authService.verifyAuthentication,
Expand All @@ -68,11 +75,21 @@ export const LoginWidget = () => {

const passkeysMutation = useAuthenticateViaPasskeys({
loginIfNoCredentials: (email: string) => {
console.info(`[LoginWidget:passkeysMutation] No credentials for: ${email}`)
console.info(
`[LoginWidget:passkeysMutation] No credentials for: ${email}`,
)
},
})

const isEmailSent = mutationState.loginMutation.isSuccess && !!mutationState.loginMutation.data
const isEmailSent =
mutationState.loginMutation.isSuccess && !!mutationState.loginMutation.data

const isEmailWasChangedSinceSending = mutationState.loginMutation.variables
?.email
? email !== mutationState.loginMutation.variables?.email
: false

const codeInputShouldBeShown = isEmailSent && !isEmailWasChangedSinceSending

const processEmailValue = useCallback(() => {
const safeParse = emailSchema.safeParse(email)
Expand Down Expand Up @@ -112,7 +129,14 @@ export const LoginWidget = () => {
success: t('codeSent'),
error: t('failedToSendCode'),
})
}, [code, confirmLoginPromise, isEmailSent, processEmailValue, showPromiseToast, t])
}, [
code,
confirmLoginPromise,
isEmailSent,
processEmailValue,
showPromiseToast,
t,
])

const loginPasskeys = useCallback(async () => {
const emailValue = processEmailValue()
Expand All @@ -122,7 +146,8 @@ export const LoginWidget = () => {
const challengeOpts = response.data.options

const isCredentialExist =
challengeOpts.allowCredentials && challengeOpts.allowCredentials.length > 0
challengeOpts.allowCredentials &&
challengeOpts.allowCredentials.length > 0

if (!isCredentialExist) {
return showInfoToast(t('noAddedDeviceForFastLogin'))
Expand Down Expand Up @@ -155,7 +180,9 @@ export const LoginWidget = () => {
/>
<div
className="overflow-hidden duration-300"
style={{ height: `${codeInputVisibility.get(mutationState.loginMutation.isSuccess)}` }}
style={{
height: `${codeInputHeight.get(codeInputShouldBeShown)}`,
}}
>
<input
type="text"
Expand All @@ -168,18 +195,27 @@ export const LoginWidget = () => {
</div>
<LoginButton
labelKey={'loginWithCode'}
onClick={isEmailSent ? confirmLoginOTP : loginOTP}
isDisabled={passkeysMutation.isPending || verifyLoginChallenge.isPending}
isLoading={loadingState.isTryLoginLoading || loadingState.isConfirmLoginLoading}
onClick={codeInputShouldBeShown ? confirmLoginOTP : loginOTP}
isDisabled={
passkeysMutation.isPending || verifyLoginChallenge.isPending
}
isLoading={
loadingState.isTryLoginLoading || loadingState.isConfirmLoginLoading
}
classNames="bg-violet20 border-violet"
/>

{!isEmailSent && browserSupportsWebAuthn() && (
<LoginButton
labelKey={'fastLogin'}
onClick={loginPasskeys}
isDisabled={loadingState.isTryLoginLoading || loadingState.isConfirmLoginLoading}
isLoading={passkeysMutation.isPending || verifyLoginChallenge.isPending}
isDisabled={
loadingState.isTryLoginLoading ||
loadingState.isConfirmLoginLoading
}
isLoading={
passkeysMutation.isPending || verifyLoginChallenge.isPending
}
classNames="border-violet"
/>
)}
Expand All @@ -193,7 +229,9 @@ export const LoginWidget = () => {
unmountOnExit
>
<div ref={hintRef} className="w-[350px] px-12">
<Typography classNames="text-black/75 text-center">{t('loginViaCodeHint')}</Typography>
<Typography classNames="text-black/75 text-center">
{t('loginViaCodeHint')}
</Typography>
</div>
</CSSTransition>
</div>
Expand Down
Loading