feat: implement login functionality with error handling and session management
This commit is contained in:
@@ -6,8 +6,11 @@ import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { Eye, EyeOff } from "lucide-react"
|
||||
import { AlertCircle, Eye, EyeOff } from "lucide-react"
|
||||
import { loginSchema, LoginValues } from "@/lib/validations"
|
||||
import { loginUser } from "@/lib/api/auth"
|
||||
import { AuthApiError } from "@/lib/api/http"
|
||||
import { persistSession } from "@/lib/auth/session"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
@@ -41,6 +44,7 @@ export default function LoginPage() {
|
||||
const router = useRouter()
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const [remember, setRemember] = useState(false)
|
||||
const [authError, setAuthError] = useState<string | null>(null)
|
||||
|
||||
const form = useForm<LoginValues>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
@@ -48,8 +52,14 @@ export default function LoginPage() {
|
||||
})
|
||||
|
||||
const onSubmit = form.handleSubmit(async (values) => {
|
||||
console.log(values)
|
||||
router.push("/dashboard")
|
||||
setAuthError(null)
|
||||
try {
|
||||
const result = await loginUser({ identifier: values.email, password: values.password })
|
||||
persistSession(result, remember)
|
||||
router.push("/dashboard")
|
||||
} catch (err) {
|
||||
setAuthError(err instanceof AuthApiError ? err.message : "Something went wrong. Please try again.")
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
@@ -79,6 +89,13 @@ export default function LoginPage() {
|
||||
</div>
|
||||
|
||||
<form onSubmit={onSubmit} noValidate className="mt-10 space-y-6" aria-describedby="form-errors" aria-live="polite">
|
||||
{authError && (
|
||||
<div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0" />
|
||||
<span>{authError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FieldGroup className="space-y-5">
|
||||
<Field data-invalid={!!form.formState.errors.email}>
|
||||
<FieldLabel htmlFor="email" className="text-sm font-semibold text-foreground">
|
||||
|
||||
Reference in New Issue
Block a user