feat(mobile): enhance TOTP modal handling and invitation confirmation

- Added a new function to validate authentication codes in the auth module.
- Updated the useTOTPModalWrapper to include a dismiss option for better modal management.
- Integrated the TOTP modal wrapper into the invitation confirmation dialog for improved user experience.
- Refactored the Invitations screen to utilize the updated TOTP modal handling.

These changes improve the security and usability of the invitation process by ensuring proper two-factor authentication handling.

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-04-02 17:49:32 +08:00
parent 331861f5e8
commit 9be249dba7
9 changed files with 242 additions and 37 deletions
@@ -31,6 +31,7 @@ import { usePresentUserProfileModal, useTOTPModalWrapper } from "~/modules/profi
import { UserAvatar } from "~/modules/user/UserAvatar"
import { Queries } from "~/queries"
const numberFormatter = new Intl.NumberFormat("en-US")
export const SettingInvitations = () => {
const { t } = useTranslation("settings")
const invitations = useAuthQuery(Queries.invitations.list())
@@ -66,7 +67,7 @@ export const SettingInvitations = () => {
<Trans
ns="settings"
values={{
limitation: limitation.data,
limitation: numberFormatter.format(limitation.data ?? 0),
}}
i18nKey="invitation.limitationMessage"
/>
@@ -1,6 +1,7 @@
import { cn, withOpacity } from "@follow/utils"
import { useCallback } from "react"
import { Text, TouchableOpacity, View } from "react-native"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { CheckLineIcon } from "@/src/icons/check_line"
import { CloseCuteReIcon } from "@/src/icons/close_cute_re"
@@ -98,9 +99,15 @@ export const HeaderSubmitTextButton = ({
}
export const HeaderCloseOnly = () => {
const insets = useSafeAreaInsets()
return (
<StackScreenHeaderPortal>
<UINavigationHeaderActionButton className="absolute left-4 top-4">
<UINavigationHeaderActionButton
className="absolute left-4"
style={{
top: insets.top + 16,
}}
>
<HeaderCloseButton />
</UINavigationHeaderActionButton>
</StackScreenHeaderPortal>
@@ -10,7 +10,7 @@ import {
useRef,
useState,
} from "react"
import type { LayoutChangeEvent } from "react-native"
import type { LayoutChangeEvent, StyleProp, ViewStyle } from "react-native"
import { Alert, StyleSheet, TouchableOpacity, View } from "react-native"
import type { AnimatedProps } from "react-native-reanimated"
import Animated, {
@@ -402,11 +402,13 @@ export const UINavigationHeaderActionButton = ({
onPress,
disabled,
className,
style,
}: {
children: ReactNode
onPress?: () => void
disabled?: boolean
className?: string
style?: StyleProp<ViewStyle>
}) => {
return (
<TouchableOpacity
@@ -414,6 +416,7 @@ export const UINavigationHeaderActionButton = ({
className={cn("p-2", className)}
onPress={onPress}
disabled={disabled}
style={style}
>
{children}
</TouchableOpacity>
+6
View File
@@ -98,3 +98,9 @@ export const useAuthProviders = () => {
queryFn: async () => (await getProviders()).data,
})
}
export function isAuthCodeValid(authCode: string) {
return (
authCode.length === 6 && !Array.from(authCode).some((c) => Number.isNaN(Number.parseInt(c)))
)
}
@@ -187,30 +187,36 @@ const ModalScreenStackItems: FC<{
screenOptions={rootModalRoute.screenOptions}
{...modalScreenOptions}
>
<ScreenStack style={StyleSheet.absoluteFill}>
<WrappedScreenItem
screenId={rootModalRoute.id}
screenOptions={rootModalRoute.screenOptions}
>
<ResolveView
comp={rootModalRoute.Component}
element={rootModalRoute.element}
props={rootModalRoute.props}
/>
</WrappedScreenItem>
{routes.slice(1).map((route) => {
return (
<WrappedScreenItem
stackPresentation={"push"}
key={route.id}
screenId={route.id}
screenOptions={route.screenOptions}
>
<ResolveView comp={route.Component} element={route.element} props={route.props} />
</WrappedScreenItem>
)
})}
</ScreenStack>
<SafeAreaProvider>
<ScreenStack style={StyleSheet.absoluteFill}>
<WrappedScreenItem
screenId={rootModalRoute.id}
screenOptions={rootModalRoute.screenOptions}
>
<ResolveView
comp={rootModalRoute.Component}
element={rootModalRoute.element}
props={rootModalRoute.props}
/>
</WrappedScreenItem>
{routes.slice(1).map((route) => {
return (
<WrappedScreenItem
stackPresentation={"push"}
key={route.id}
screenId={route.id}
screenOptions={route.screenOptions}
>
<ResolveView
comp={route.Component}
element={route.element}
props={route.props}
/>
</WrappedScreenItem>
)
})}
</ScreenStack>
</SafeAreaProvider>
</WrappedScreenItem>
</ModalScreenItemOptionsContext.Provider>
)
@@ -0,0 +1,181 @@
import { useMutation } from "@tanstack/react-query"
import type { FC } from "react"
import { useEffect, useRef, useState } from "react"
import { Keyboard, Modal, StyleSheet, Text, useWindowDimensions, View } from "react-native"
import type { OtpInputRef } from "react-native-otp-entry"
import { OtpInput } from "react-native-otp-entry"
import Animated, { FadeIn, FadeOut, useSharedValue, withSpring } from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { useColor } from "react-native-uikit-colors"
import { isAuthCodeValid, twoFactor } from "@/src/lib/auth"
import { toast } from "@/src/lib/toast"
import { accentColor } from "@/src/theme/colors"
export const OTPWindow: FC<{
onSuccess: (token: string) => void
}> = ({ onSuccess }) => {
const otpInputRef = useRef<OtpInputRef>(null)
const label = useColor("label")
const tertiaryLabel = useColor("tertiaryLabel")
const secondaryBackground = useColor("gray5")
const tertiaryBackground = useColor("gray6")
const submitMutation = useMutation({
onError(error) {
toast.error(`Failed to verify: ${error.message}`)
},
onSuccess(data) {
onSuccess(data.token)
},
onSettled() {
setOpen(false)
},
mutationFn: async ({ code }: { code: string }) => {
const { data, error } = await twoFactor.verifyTotp({ code })
if (!data || error) {
const errorMessage = error?.message ?? "Invalid TOTP code"
toast.error(errorMessage)
throw new Error(errorMessage)
}
return data
},
})
const windowScaleValue = useSharedValue(0.9)
const windowOpacityValue = useSharedValue(0)
const [open, setOpen] = useState(false)
useEffect(() => {
setOpen(true)
}, [])
useEffect(() => {
if (open) {
windowScaleValue.value = withSpring(1, { stiffness: 100, damping: 10 })
windowOpacityValue.value = withSpring(1, { stiffness: 100, damping: 10 })
} else {
windowOpacityValue.value = withSpring(0, { stiffness: 100, damping: 10 })
windowScaleValue.value = withSpring(0.9, { stiffness: 100, damping: 10 })
}
}, [open, windowOpacityValue, windowScaleValue])
const { height } = useWindowDimensions()
const insets = useSafeAreaInsets()
const [nextHeight, setNextHeight] = useState(height - insets.top)
useEffect(() => {
const sub = [
Keyboard.addListener("keyboardDidShow", () => {
const metrics = Keyboard.metrics()
if (!metrics) return
setNextHeight(height - metrics.height)
}),
Keyboard.addListener("keyboardWillHide", () => {
setNextHeight(height - insets.top)
}),
]
return () => sub.forEach((listener) => listener.remove())
}, [height, insets.top])
return (
<Modal transparent animationType="fade" visible={open} onRequestClose={() => setOpen(false)}>
<Animated.View exiting={FadeOut} entering={FadeIn} style={StyleSheet.absoluteFillObject}>
<View className={"flex-1 bg-black/50"} />
</Animated.View>
<View className={"flex-1"}>
{/* Window */}
<View style={{ height: nextHeight }} className="pt-safe items-center justify-center">
<Animated.View
className="bg-system-background mx-5 overflow-hidden rounded-3xl"
style={[
styles.window,
{
transform: [{ scale: windowScaleValue }],
opacity: windowOpacityValue,
},
]}
>
<View className="px-6 pb-1 pt-6">
<Text className="text-label mb-1 text-center text-lg font-medium">
Verification Required
</Text>
<Text className="text-secondary-label text-center text-base">
Please enter the code from your authenticator app.
</Text>
</View>
<View className="px-4 py-5">
<OtpInput
disabled={submitMutation.isPending}
ref={otpInputRef}
numberOfDigits={6}
autoFocus
focusColor={"#00000000"}
theme={{
containerStyle: { marginVertical: 8 },
pinCodeTextStyle: {
color: label,
fontSize: 22,
fontWeight: "500",
},
placeholderTextStyle: { color: tertiaryLabel },
filledPinCodeContainerStyle: {
borderColor: "transparent",
backgroundColor: secondaryBackground,
},
pinCodeContainerStyle: {
borderColor: "transparent",
backgroundColor: tertiaryBackground,
borderRadius: 12,
aspectRatio: 1,
width: 45,
marginHorizontal: 4,
},
focusedPinCodeContainerStyle: {
borderColor: accentColor,
borderWidth: 2,
},
}}
onFilled={(code) => {
if (isAuthCodeValid(code)) {
submitMutation.mutate({ code })
}
}}
/>
</View>
<View className="border-non-opaque-separator border-t-hairline flex-row px-4 py-2">
<View className="flex-1 items-center">
<Text
className="text-accent px-5 py-2 text-base font-medium"
onPress={() => {
setOpen(false)
}}
suppressHighlighting
>
Cancel
</Text>
</View>
</View>
</Animated.View>
</View>
</View>
</Modal>
)
}
const styles = StyleSheet.create({
window: {
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.15,
shadowRadius: 10,
elevation: 5,
maxWidth: 400,
},
})
@@ -8,13 +8,14 @@ import { useWhoami } from "@/src/store/user/hooks"
export const useTOTPModalWrapper = <T extends { TOTPCode?: string }>(
callback: (input: T) => Promise<any>,
options?: { force?: boolean },
options?: { force?: boolean; dismiss?: () => any },
) => {
const user = useWhoami()
const navigation = useNavigation()
return useCallback(
async (input: T) => {
const presentTOTPModal = () => {
options?.dismiss?.()
if (!user?.twoFactorEnabled) {
toast.error("You need to enable two-factor authentication to perform this action.")
@@ -53,6 +54,6 @@ export const useTOTPModalWrapper = <T extends { TOTPCode?: string }>(
}
}
},
[callback, navigation, options?.force, user?.twoFactorEnabled],
[callback, navigation, options, user?.twoFactorEnabled],
)
}
@@ -31,6 +31,8 @@ import { queryClient } from "@/src/lib/query-client"
import { toast } from "@/src/lib/toast"
import { accentColor } from "@/src/theme/colors"
import { useTOTPModalWrapper } from "../hooks/useTOTPModalWrapper"
const invitationQueryKey = ["invitations"]
const useInvitationsQuery = () => {
return useQuery({
@@ -184,6 +186,10 @@ const ConfirmGenerateDialog: DialogComponent = () => {
},
})
const confirm = useTOTPModalWrapper(() => newInvitation.mutateAsync({}), {
dismiss,
})
return (
<View>
<Text>
@@ -196,7 +202,7 @@ const ConfirmGenerateDialog: DialogComponent = () => {
<Dialog.DialogConfirm
onPress={() => {
newInvitation.mutateAsync({})
confirm({})
}}
/>
</View>
+1 -7
View File
@@ -7,7 +7,7 @@ import { OtpInput } from "react-native-otp-entry"
import { useColor } from "react-native-uikit-colors"
import { HeaderCloseOnly } from "@/src/components/layouts/header/HeaderElements"
import { twoFactor } from "@/src/lib/auth"
import { isAuthCodeValid, twoFactor } from "@/src/lib/auth"
import { useNavigation } from "@/src/lib/navigation/hooks"
import type { NavigationControllerView } from "@/src/lib/navigation/types"
import { queryClient } from "@/src/lib/query-client"
@@ -15,12 +15,6 @@ import { toast } from "@/src/lib/toast"
import { whoamiQueryKey } from "@/src/store/user/hooks"
import { accentColor } from "@/src/theme/colors"
function isAuthCodeValid(authCode: string) {
return (
authCode.length === 6 && !Array.from(authCode).some((c) => Number.isNaN(Number.parseInt(c)))
)
}
export const TwoFactorAuthScreen: NavigationControllerView = () => {
const label = useColor("label")
const tertiaryLabel = useColor("tertiaryLabel")