'use client'; import { useState } from 'react'; import { toast } from 'sonner'; import { Loader2, KeyRound } from 'lucide-react'; import { createClient } from '@/lib/supabase/client'; import { useAuth } from '@/hooks/use-auth'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Card, CardContent, CardHeader, CardTitle, CardDescription, } from '@/components/ui/card'; const MIN_PASSWORD = 8; export function PasswordForm() { const { profile } = useAuth(); const supabase = createClient(); const [current, setCurrent] = useState(''); const [next, setNext] = useState(''); const [confirm, setConfirm] = useState(''); const [saving, setSaving] = useState(false); const [confirmError, setConfirmError] = useState(null); const onSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!profile?.email) { toast.error('Cannot change password without a current email'); return; } if (next.length < MIN_PASSWORD) { setConfirmError(`Password must be at least ${MIN_PASSWORD} characters`); return; } if (next !== confirm) { setConfirmError('New password and confirmation do not match'); return; } setConfirmError(null); setSaving(true); try { // Supabase doesn't expose a "verify password without issuing a // session" API, so we re-authenticate with the provided current // password. If it matches, the session refreshes silently; if it // doesn't, we abort before calling updateUser. const { error: signInError } = await supabase.auth.signInWithPassword({ email: profile.email, password: current, }); if (signInError) { toast.error('Current password is incorrect'); return; } const { error: updateError } = await supabase.auth.updateUser({ password: next, }); if (updateError) { toast.error(`Password update failed: ${updateError.message}`); return; } setCurrent(''); setNext(''); setConfirm(''); toast.success('Password updated'); } catch (err) { const msg = err instanceof Error ? err.message : 'Unknown error'; toast.error(msg); } finally { setSaving(false); } }; return ( Password Use at least {MIN_PASSWORD} characters. You will stay signed in on this device after changing it.
setCurrent(e.target.value)} autoComplete="current-password" disabled={saving} required />
setNext(e.target.value)} autoComplete="new-password" minLength={MIN_PASSWORD} disabled={saving} required />
setConfirm(e.target.value)} autoComplete="new-password" minLength={MIN_PASSWORD} disabled={saving} required />
{confirmError && (

{confirmError}

)}
); }