feat(auth): add stepped auth and password recovery flows
This commit is contained in:
@@ -1,250 +1,24 @@
|
||||
import React, { useEffect, useMemo, useState } from "react"
|
||||
import { useNavigate, Link } from "react-router-dom"
|
||||
import { Button } from "../components/ui/button"
|
||||
import { Input } from "../components/ui/input"
|
||||
import { Outlet } from "react-router-dom"
|
||||
import { Command } from "lucide-react"
|
||||
|
||||
import { SettingsMenu } from "../components/SettingsMenu"
|
||||
import { AlertTriangle, ArrowLeft, ArrowRight, Command, Eye, EyeOff, Loader2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { useTranslation } from "../hooks/useTranslation"
|
||||
import { loginWithOtp, loginWithPassword, sendOtp, startGoogleLogin } from "../api/users"
|
||||
import { ApiError } from "../api/client"
|
||||
import { setSessionTokens } from "../lib/session"
|
||||
|
||||
type AuthStep = "mobile" | "password" | "otp"
|
||||
type AuthMode = "login" | "register"
|
||||
type CooldownKey = "otpSend" | "passwordLogin" | "otpLogin"
|
||||
|
||||
type Cooldowns = Record<CooldownKey, number>
|
||||
|
||||
const PERSIAN_DIGITS = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"]
|
||||
|
||||
const toPersianDigits = (value: string) =>
|
||||
value.replace(/\d/g, (digit) => PERSIAN_DIGITS[Number.parseInt(digit, 10)] ?? digit)
|
||||
|
||||
const GoogleIcon = () => (
|
||||
<svg aria-hidden="true" className="h-5 w-5" viewBox="0 0 24 24">
|
||||
<path
|
||||
d="M21.805 10.023h-9.72v3.955h5.57c-.24 1.272-.96 2.35-2.042 3.07v2.548h3.3c1.933-1.78 3.042-4.4 3.042-7.506 0-.692-.062-1.357-.15-2.067Z"
|
||||
fill="#4285F4"
|
||||
/>
|
||||
<path
|
||||
d="M12.085 22c2.79 0 5.13-.925 6.84-2.504l-3.3-2.548c-.924.617-2.103.986-3.54.986-2.705 0-4.99-1.823-5.807-4.28H2.87v2.626A10.33 10.33 0 0 0 12.085 22Z"
|
||||
fill="#34A853"
|
||||
/>
|
||||
<path
|
||||
d="M6.278 13.654A6.214 6.214 0 0 1 5.95 11.7c0-.68.117-1.34.328-1.954V7.12H2.87A10.31 10.31 0 0 0 1.75 11.7c0 1.65.39 3.218 1.12 4.58l3.408-2.626Z"
|
||||
fill="#FBBC05"
|
||||
/>
|
||||
<path
|
||||
d="M12.085 5.466c1.52 0 2.882.522 3.955 1.55l2.966-2.966C17.21 2.387 14.874 1.4 12.085 1.4A10.33 10.33 0 0 0 2.87 7.12l3.408 2.626c.818-2.457 3.103-4.28 5.807-4.28Z"
|
||||
fill="#EA4335"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
|
||||
export default function Auth() {
|
||||
const navigate = useNavigate()
|
||||
const { t, lang } = useTranslation()
|
||||
const isRtl = lang === "fa"
|
||||
|
||||
const [step, setStep] = useState<AuthStep>("mobile")
|
||||
const [mode, setMode] = useState<AuthMode>("login")
|
||||
const [mobile, setMobile] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [otpCode, setOtpCode] = useState("")
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const [cooldowns, setCooldowns] = useState<Cooldowns>({
|
||||
otpSend: 0,
|
||||
passwordLogin: 0,
|
||||
otpLogin: 0,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (!Object.values(cooldowns).some((value) => value > 0)) {
|
||||
return
|
||||
}
|
||||
|
||||
const timer = window.setInterval(() => {
|
||||
setCooldowns((current) => ({
|
||||
otpSend: Math.max(0, current.otpSend - 1),
|
||||
passwordLogin: Math.max(0, current.passwordLogin - 1),
|
||||
otpLogin: Math.max(0, current.otpLogin - 1),
|
||||
}))
|
||||
}, 1000)
|
||||
|
||||
return () => window.clearInterval(timer)
|
||||
}, [cooldowns])
|
||||
|
||||
const localizeDigits = (value: string) => (isRtl ? toPersianDigits(value) : value)
|
||||
|
||||
const formatCooldown = (seconds: number) => {
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const remainingSeconds = seconds % 60
|
||||
const base = minutes > 0
|
||||
? `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
: `${remainingSeconds}s`
|
||||
|
||||
return localizeDigits(base)
|
||||
}
|
||||
|
||||
const setCooldown = (key: CooldownKey, seconds: number) => {
|
||||
setCooldowns((current) => ({
|
||||
...current,
|
||||
[key]: Math.max(current[key], seconds),
|
||||
}))
|
||||
}
|
||||
|
||||
const handleTokenResponse = (access: string, refresh: string) => {
|
||||
setSessionTokens(access, refresh)
|
||||
toast.success(t.login.toasts.successLogin)
|
||||
navigate("/profile")
|
||||
}
|
||||
|
||||
const handleThrottleError = (error: unknown, key: CooldownKey) => {
|
||||
if (!(error instanceof ApiError) || error.code !== "throttled") {
|
||||
return false
|
||||
}
|
||||
|
||||
const seconds = Math.max(1, error.retryAfterSeconds ?? 0)
|
||||
const formattedTime = formatCooldown(seconds)
|
||||
|
||||
setCooldown(key, seconds)
|
||||
|
||||
const throttleCopy = t.login.throttle
|
||||
const message =
|
||||
key === "otpSend"
|
||||
? throttleCopy.otpSendMessage(formattedTime)
|
||||
: key === "passwordLogin"
|
||||
? throttleCopy.passwordLoginMessage(formattedTime)
|
||||
: throttleCopy.otpLoginMessage(formattedTime)
|
||||
|
||||
toast.error(message, {
|
||||
description: throttleCopy.countdownLabel(formattedTime),
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const handleSendOtp = async (selectedMode: AuthMode) => {
|
||||
if (!mobile) {
|
||||
toast.error(t.login.toasts.enterMobile)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
await sendOtp(mobile, selectedMode)
|
||||
setCooldowns((current) => ({ ...current, otpSend: 0 }))
|
||||
setMode(selectedMode)
|
||||
setStep("otp")
|
||||
toast.success(t.login.toasts.verifySent)
|
||||
} catch (error) {
|
||||
if (!handleThrottleError(error, "otpSend")) {
|
||||
toast.error(error instanceof Error ? error.message : t.login.toasts.failedOtp)
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePasswordLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!mobile || !password) {
|
||||
toast.error(t.login.toasts.fillAll)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const data = await loginWithPassword(mobile, password)
|
||||
setCooldowns((current) => ({ ...current, passwordLogin: 0 }))
|
||||
handleTokenResponse(data.access, data.refresh)
|
||||
} catch (error) {
|
||||
if (!handleThrottleError(error, "passwordLogin")) {
|
||||
toast.error(error instanceof Error ? error.message : t.login.toasts.invalidCreds)
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleOtpVerify = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!mobile || !otpCode) {
|
||||
toast.error(t.login.toasts.enterOtp)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const data = await loginWithOtp(mobile, otpCode)
|
||||
setCooldowns((current) => ({ ...current, otpLogin: 0 }))
|
||||
handleTokenResponse(data.access, data.refresh)
|
||||
} catch (error) {
|
||||
if (!handleThrottleError(error, "otpLogin")) {
|
||||
toast.error(error instanceof Error ? error.message : t.login.toasts.invalidOtp)
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const activeCooldownMessage = useMemo(() => {
|
||||
const throttleCopy = t.login.throttle
|
||||
|
||||
if (step === "mobile" && cooldowns.otpSend > 0) {
|
||||
const formatted = formatCooldown(cooldowns.otpSend)
|
||||
return {
|
||||
title: throttleCopy.title,
|
||||
description: throttleCopy.otpSendMessage(formatted),
|
||||
}
|
||||
}
|
||||
|
||||
if (step === "password" && cooldowns.passwordLogin > 0) {
|
||||
const formatted = formatCooldown(cooldowns.passwordLogin)
|
||||
return {
|
||||
title: throttleCopy.title,
|
||||
description: throttleCopy.passwordLoginMessage(formatted),
|
||||
}
|
||||
}
|
||||
|
||||
if (step === "otp" && cooldowns.otpLogin > 0) {
|
||||
const formatted = formatCooldown(cooldowns.otpLogin)
|
||||
return {
|
||||
title: throttleCopy.title,
|
||||
description: throttleCopy.otpLoginMessage(formatted),
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}, [cooldowns, formatCooldown, step, t.login.throttle])
|
||||
|
||||
const otpCooldownLabel =
|
||||
cooldowns.otpSend > 0 ? t.login.throttle.countdownLabel(formatCooldown(cooldowns.otpSend)) : null
|
||||
const passwordCooldownLabel =
|
||||
cooldowns.passwordLogin > 0
|
||||
? t.login.throttle.countdownLabel(formatCooldown(cooldowns.passwordLogin))
|
||||
: null
|
||||
const otpLoginCooldownLabel =
|
||||
cooldowns.otpLogin > 0 ? t.login.throttle.countdownLabel(formatCooldown(cooldowns.otpLogin)) : null
|
||||
|
||||
const BackIcon = isRtl ? ArrowRight : ArrowLeft
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<div className="container relative min-h-screen flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0 bg-white dark:bg-slate-950 transition-colors">
|
||||
<div className="container relative min-h-screen grid flex-col items-center justify-center bg-white transition-colors lg:max-w-none lg:grid-cols-2 lg:px-0 dark:bg-slate-950">
|
||||
<div className="absolute inset-e-4 top-4 z-50 md:inset-e-8 md:top-8">
|
||||
<SettingsMenu />
|
||||
</div>
|
||||
|
||||
<div className="relative hidden h-full flex-col bg-slate-900 dark:bg-slate-900/50 p-10 text-white lg:flex border-e border-slate-200 dark:border-slate-800">
|
||||
<div className="relative z-20 flex items-center text-lg font-medium gap-2">
|
||||
<div className="relative hidden h-full flex-col border-e border-slate-200 bg-slate-900 p-10 text-white dark:border-slate-800 dark:bg-slate-900/50 lg:flex">
|
||||
<div className="relative z-20 flex items-center gap-2 text-lg font-medium">
|
||||
<Command className="h-6 w-6" />
|
||||
{t.title || "Qlockify"}
|
||||
</div>
|
||||
|
||||
<div className="relative z-20 mt-auto">
|
||||
<blockquote className="space-y-2">
|
||||
<p className="text-lg">"{t.login.brandingQuote}"</p>
|
||||
@@ -252,176 +26,9 @@ export default function Auth() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-8 lg:p-8 flex h-screen items-center justify-center">
|
||||
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-87.5">
|
||||
<div className="flex flex-col space-y-2 text-center text-slate-900 dark:text-slate-50">
|
||||
<div className="flex justify-center lg:hidden mb-4">
|
||||
<Command className="h-8 w-8" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
{step === "mobile" && t.login.welcome(t.title)}
|
||||
{step === "password" && t.login.enterPassword}
|
||||
{step === "otp" && t.login.verifyNumber}
|
||||
</h1>
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400">
|
||||
{step === "mobile" && t.login.enterMobileDesc}
|
||||
{step === "password" && t.login.signInDesc}
|
||||
{step === "otp" && t.login.sentCodeDesc(mobile)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{activeCooldownMessage && (
|
||||
<div className="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-start text-amber-900 shadow-sm dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-100">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">{activeCooldownMessage.title}</p>
|
||||
<p className="text-sm">{activeCooldownMessage.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-6">
|
||||
{step === "mobile" && (
|
||||
<div className="grid gap-4">
|
||||
<Input
|
||||
id="mobile"
|
||||
placeholder={t.login.mobilePlaceholder}
|
||||
type="tel"
|
||||
dir="ltr"
|
||||
value={mobile}
|
||||
onChange={(e) => setMobile(e.target.value)}
|
||||
maxLength={11}
|
||||
disabled={loading}
|
||||
className={`h-11 ${isRtl ? "text-end" : "text-start"}`}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (!mobile) {
|
||||
toast.error(t.login.toasts.enterMobile)
|
||||
return
|
||||
}
|
||||
setStep("password")
|
||||
}}
|
||||
className="w-full h-11"
|
||||
>
|
||||
{t.login.continueWithPassword}
|
||||
</Button>
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t border-slate-200 dark:border-slate-800" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-white dark:bg-slate-950 px-2 text-slate-500 dark:text-slate-400 transition-colors">
|
||||
{t.login.orContinueWith}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={startGoogleLogin}
|
||||
disabled={loading}
|
||||
className="h-11 w-full"
|
||||
>
|
||||
<GoogleIcon />
|
||||
<span className="ms-3">{t.login.continueWithGoogle}</span>
|
||||
</Button>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleSendOtp("login")}
|
||||
disabled={loading || cooldowns.otpSend > 0}
|
||||
className="h-11"
|
||||
>
|
||||
{loading && mode === "login" && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{cooldowns.otpSend > 0 ? otpCooldownLabel : t.login.otpLogin}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleSendOtp("register")}
|
||||
disabled={loading || cooldowns.otpSend > 0}
|
||||
className="h-11"
|
||||
>
|
||||
{loading && mode === "register" && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{cooldowns.otpSend > 0 ? otpCooldownLabel : t.login.register}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "password" && (
|
||||
<form onSubmit={handlePasswordLogin} autoComplete="off" className="grid gap-4">
|
||||
<div className="relative w-full" dir="ltr">
|
||||
<Input
|
||||
id="password"
|
||||
placeholder={t.login.passwordPlaceholder}
|
||||
type={showPassword ? "text" : "password"}
|
||||
autoComplete="new-password"
|
||||
dir="ltr"
|
||||
name="some-random-name-to-disable-auto-complete-on-browser"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={loading}
|
||||
className={`h-11 pr-10 ${isRtl ? "text-end" : "text-start"}`}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
tabIndex={-1}
|
||||
onClick={() => setShowPassword((prev) => !prev)}
|
||||
className="absolute inset-y-0 right-0 flex cursor-pointer items-center pr-3 text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-300"
|
||||
>
|
||||
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
|
||||
</button>
|
||||
</div>
|
||||
<Button type="submit" className="w-full h-11" disabled={loading || cooldowns.passwordLogin > 0}>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{passwordCooldownLabel || t.login.signIn}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={() => setStep("mobile")} className="text-sm text-slate-500 dark:text-slate-400">
|
||||
<BackIcon className="me-2 h-4 w-4" /> {t.login.back}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === "otp" && (
|
||||
<form onSubmit={handleOtpVerify} className="grid gap-4">
|
||||
<Input
|
||||
id="otp"
|
||||
placeholder={t.login.otpPlaceholder}
|
||||
type="text"
|
||||
dir="ltr"
|
||||
value={otpCode}
|
||||
onChange={(e) => setOtpCode(e.target.value)}
|
||||
maxLength={6}
|
||||
disabled={loading}
|
||||
className="h-11 text-center tracking-widest text-lg"
|
||||
/>
|
||||
<Button type="submit" className="w-full h-11" disabled={loading || cooldowns.otpLogin > 0}>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{otpLoginCooldownLabel || t.login.verifyAndContinue}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={() => setStep("mobile")} className="text-sm text-slate-500 dark:text-slate-400">
|
||||
<BackIcon className="me-2 h-4 w-4" /> {t.login.back}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 text-center text-sm text-slate-500 dark:text-slate-400">
|
||||
{t.loginTerms?.prefix}
|
||||
<Link
|
||||
to="/terms"
|
||||
className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
|
||||
>
|
||||
{t.loginTerms?.link}
|
||||
</Link>
|
||||
{t.loginTerms?.suffix}
|
||||
</div>
|
||||
<div className="flex h-screen items-center justify-center p-8 lg:p-8">
|
||||
<div className="mx-auto flex w-full max-w-[26rem] flex-col justify-center">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user