Files
otunes/apps/mobile/components/auth-form.tsx
T

200 lines
6.0 KiB
TypeScript

import { useAuthActions, useConvexAuth } from "@convex-dev/auth/react"
import { Link, useRouter } from "expo-router"
import { useQuery } from "convex/react"
import { useEffect, useState } from "react"
import {
KeyboardAvoidingView,
Platform,
Pressable,
StyleSheet,
Text,
View,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { Button, Card, Input } from "@/components/ui/primitives"
import { useServerConfig } from "@/contexts/server-config"
import { api } from "@otunes/convex/_generated/api"
import { spacing, useThemeColors } from "@/lib/theme"
type AuthFlow = "signIn" | "signUp"
const copy: Record<
AuthFlow,
{
title: string
description: string
submit: string
switchPrompt: string
switchLabel: string
switchHref: "/signin" | "/signup"
}
> = {
signIn: {
title: "Welcome back",
description: "Sign in to your oTunes account to keep listening.",
submit: "Sign in",
switchPrompt: "Don't have an account?",
switchLabel: "Sign up",
switchHref: "/signup",
},
signUp: {
title: "Create your account",
description: "Sign up to start building your oTunes library.",
submit: "Sign up",
switchPrompt: "Already have an account?",
switchLabel: "Sign in",
switchHref: "/signin",
},
}
export function AuthForm({ flow }: { flow: AuthFlow }) {
const { signIn } = useAuthActions()
const auth = useConvexAuth()
const router = useRouter()
const colors = useThemeColors()
const { config } = useServerConfig()
const appSettings = useQuery(api.users.getAppSettings)
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (auth.isAuthenticated) {
router.replace("/(app)/(tabs)/home")
}
}, [auth.isAuthenticated, router])
const text = copy[flow]
const accountCreationDisabled = appSettings?.disableAccountCreation ?? false
const signupsDisabled = flow === "signUp" && accountCreationDisabled
const hideSignUpLink = flow === "signIn" && accountCreationDisabled
async function handleSubmit() {
if (signupsDisabled) return
setError(null)
setSubmitting(true)
const formData = new FormData()
formData.set("flow", flow)
formData.set("email", email.trim())
formData.set("password", password)
if (flow === "signUp") {
formData.set("name", name.trim())
}
try {
await signIn("password", formData)
} catch {
setError(
flow === "signIn"
? "Invalid email or password."
: "Could not create account. Try a different email."
)
setSubmitting(false)
}
}
return (
<SafeAreaView style={[styles.safe, { backgroundColor: colors.background }]}>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.container}
>
<Card>
<View style={styles.header}>
<Text style={[styles.title, { color: colors.foreground }]}>{text.title}</Text>
<Text style={[styles.description, { color: colors.mutedForeground }]}>
{text.description}
</Text>
{config ? (
<Text style={[styles.server, { color: colors.mutedForeground }]}>
Server: {config.hostname}
</Text>
) : null}
</View>
{signupsDisabled ? (
<Text style={{ color: colors.mutedForeground }}>
New account registration is currently disabled. Contact an administrator if you need
access.
</Text>
) : (
<View style={styles.form}>
{flow === "signUp" ? (
<Input
value={name}
onChangeText={setName}
placeholder="Name"
autoComplete="name"
/>
) : null}
<Input
value={email}
onChangeText={setEmail}
placeholder="Email"
autoCapitalize="none"
keyboardType="email-address"
autoComplete="email"
/>
<Input
value={password}
onChangeText={setPassword}
placeholder="Password"
secureTextEntry
autoComplete={flow === "signIn" ? "current-password" : "new-password"}
/>
{error ? <Text style={{ color: colors.destructive }}>{error}</Text> : null}
<Button title={text.submit} loading={submitting} onPress={() => void handleSubmit()} />
{!hideSignUpLink ? (
<View style={styles.switchRow}>
<Text style={{ color: colors.mutedForeground }}>{text.switchPrompt} </Text>
<Link href={text.switchHref} asChild>
<Pressable>
<Text style={{ color: colors.foreground, fontWeight: "600" }}>
{text.switchLabel}
</Text>
</Pressable>
</Link>
</View>
) : null}
</View>
)}
</Card>
<Link href="/server" asChild>
<Pressable style={styles.changeServer}>
<Text style={{ color: colors.mutedForeground }}>Change server</Text>
</Pressable>
</Link>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
safe: { flex: 1 },
container: {
flex: 1,
justifyContent: "center",
padding: spacing.xl,
gap: spacing.lg,
},
header: { gap: spacing.xs },
title: { fontSize: 22, fontWeight: "700" },
description: { fontSize: 14, lineHeight: 20 },
server: { fontSize: 13, marginTop: spacing.xs },
form: { gap: spacing.md },
switchRow: {
flexDirection: "row",
justifyContent: "center",
flexWrap: "wrap",
},
changeServer: {
alignItems: "center",
padding: spacing.md,
},
})