feat: Add button to send orphaned password confirmation email

This commit is contained in:
gpt-engineer-app[bot]
2025-10-14 15:57:53 +00:00
parent 1f206ceecf
commit 4ce2c266eb
3 changed files with 58 additions and 214 deletions

View File

@@ -1,159 +0,0 @@
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { reverifyPasswordAuth } from "@/lib/identityService";
import { toast } from "sonner";
import { Loader2, AlertCircle } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
interface PasswordVerificationDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onSuccess: () => void;
defaultEmail?: string;
}
export function PasswordVerificationDialog({
open,
onOpenChange,
onSuccess,
defaultEmail = "",
}: PasswordVerificationDialogProps) {
const [email, setEmail] = useState(defaultEmail);
const [password, setPassword] = useState("");
const [isVerifying, setIsVerifying] = useState(false);
const [showResetOption, setShowResetOption] = useState(false);
const handleVerify = async (e: React.FormEvent) => {
e.preventDefault();
if (!email || !password) {
toast.error("Please enter both email and password");
return;
}
setIsVerifying(true);
setShowResetOption(false);
try {
const result = await reverifyPasswordAuth(email, password);
if (result.success) {
if (result.needsEmailConfirmation) {
toast.success("Password Verified!", {
description: "Check your email for a confirmation link to complete activation.",
duration: 8000,
});
} else {
toast.success("Password Verified!", {
description: "Your password authentication has been activated.",
});
}
onOpenChange(false);
onSuccess();
} else {
setShowResetOption(true);
toast.error("Verification Failed", {
description: result.error || "Unable to verify password. Try the password reset option below.",
});
}
} catch (error: any) {
setShowResetOption(true);
toast.error("Verification Error", {
description: error.message || "An unexpected error occurred.",
});
} finally {
setIsVerifying(false);
}
};
const handlePasswordReset = () => {
onOpenChange(false);
// Navigate or trigger password reset flow
window.location.href = `/auth?email=${encodeURIComponent(email)}&message=reset-password`;
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Verify Password Access</DialogTitle>
<DialogDescription>
Enter your email and password to activate password authentication for your account.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleVerify}>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="verify-email">Email</Label>
<Input
id="verify-email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="your@email.com"
disabled={isVerifying}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="verify-password">Password</Label>
<Input
id="verify-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter your password"
disabled={isVerifying}
required
/>
</div>
{showResetOption && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
Can't remember your password?{" "}
<Button
type="button"
variant="link"
className="h-auto p-0 text-sm"
onClick={handlePasswordReset}
>
Reset it here
</Button>
</AlertDescription>
</Alert>
)}
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isVerifying}
>
Cancel
</Button>
<Button type="submit" disabled={isVerifying}>
{isVerifying && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Verify Password
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}

View File

@@ -17,17 +17,16 @@ import {
checkDisconnectSafety, checkDisconnectSafety,
disconnectIdentity, disconnectIdentity,
connectIdentity, connectIdentity,
hasOrphanedPassword hasOrphanedPassword,
triggerOrphanedPasswordConfirmation
} from '@/lib/identityService'; } from '@/lib/identityService';
import type { UserIdentity, OAuthProvider } from '@/types/identity'; import type { UserIdentity, OAuthProvider } from '@/types/identity';
import { PasswordVerificationDialog } from '@/components/auth/PasswordVerificationDialog';
import { toast as sonnerToast } from 'sonner'; import { toast as sonnerToast } from 'sonner';
export function SecurityTab() { export function SecurityTab() {
const { user } = useAuth(); const { user } = useAuth();
const { toast } = useToast(); const { toast } = useToast();
const navigate = useNavigate(); const navigate = useNavigate();
const [passwordDialogOpen, setPasswordDialogOpen] = useState(false); const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
const [verificationDialogOpen, setVerificationDialogOpen] = useState(false);
const [identities, setIdentities] = useState<UserIdentity[]>([]); const [identities, setIdentities] = useState<UserIdentity[]>([]);
const [loadingIdentities, setLoadingIdentities] = useState(true); const [loadingIdentities, setLoadingIdentities] = useState(true);
const [disconnectingProvider, setDisconnectingProvider] = useState<OAuthProvider | null>(null); const [disconnectingProvider, setDisconnectingProvider] = useState<OAuthProvider | null>(null);
@@ -48,6 +47,13 @@ export function SecurityTab() {
const isOrphaned = await hasOrphanedPassword(); const isOrphaned = await hasOrphanedPassword();
setShowOrphanedPasswordOption(isOrphaned); setShowOrphanedPasswordOption(isOrphaned);
if (isOrphaned) {
sonnerToast.info("Password Authentication Needs Activation", {
description: "Click 'Send Confirmation Email' below to complete your password setup.",
duration: 10000,
});
}
if (isOrphaned) { if (isOrphaned) {
sonnerToast.info("Password Authentication Needs Activation", { sonnerToast.info("Password Authentication Needs Activation", {
description: "Click 'Verify Password Access' to complete your password setup.", description: "Click 'Verify Password Access' to complete your password setup.",
@@ -187,17 +193,25 @@ export function SecurityTab() {
setPasswordSetupProvider('google' as OAuthProvider); setPasswordSetupProvider('google' as OAuthProvider);
}; };
const handleVerifyExistingPassword = () => { const handleSendConfirmationEmail = async () => {
setVerificationDialogOpen(true); setAddingPassword(true);
};
const handleVerificationSuccess = async () => { const result = await triggerOrphanedPasswordConfirmation();
// Don't reload identities immediately - user needs to confirm email first
toast({ if (result.success) {
title: "Email Confirmation Required", sonnerToast.success("Confirmation Email Sent!", {
description: "Check your email and click the confirmation link to activate password authentication.", description: "Check your email for a confirmation link to activate your password authentication.",
duration: 0, // Persistent duration: 15000,
}); });
} else {
toast({
title: "Failed to Send Email",
description: result.error,
variant: "destructive"
});
}
setAddingPassword(false);
}; };
// Get connected accounts with identity data // Get connected accounts with identity data
@@ -236,13 +250,6 @@ export function SecurityTab() {
/> />
)} )}
<PasswordVerificationDialog
open={verificationDialogOpen}
onOpenChange={setVerificationDialogOpen}
onSuccess={handleVerificationSuccess}
defaultEmail={user?.email}
/>
<div className="space-y-8"> <div className="space-y-8">
{/* Password Section - Conditional based on auth method */} {/* Password Section - Conditional based on auth method */}
<div className="space-y-4"> <div className="space-y-4">
@@ -282,10 +289,21 @@ export function SecurityTab() {
{showOrphanedPasswordOption && ( {showOrphanedPasswordOption && (
<Button <Button
variant="outline" variant="outline"
onClick={handleVerifyExistingPassword} onClick={handleSendConfirmationEmail}
disabled={addingPassword}
className="w-full" className="w-full"
> >
Already have a password? Verify Access {addingPassword ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Sending Email...
</>
) : (
<>
<Key className="w-4 h-4 mr-2" />
Send Confirmation Email
</>
)}
</Button> </Button>
)} )}
</> </>

View File

@@ -290,57 +290,42 @@ export async function hasOrphanedPassword(): Promise<boolean> {
} }
/** /**
* Re-verify password authentication by signing in and triggering email confirmation * Trigger email confirmation for orphaned password
* This creates the missing email identity through Supabase's confirmation flow * Direct trigger without requiring password re-entry
*/ */
export async function reverifyPasswordAuth( export async function triggerOrphanedPasswordConfirmation(): Promise<IdentityOperationResult> {
email: string,
password: string
): Promise<IdentityOperationResult> {
try { try {
// Step 1: Verify credentials by signing in const { data: { user } } = await supabase.auth.getUser();
console.log('[IdentityService] Verifying password credentials');
const { data: authData, error: signInError } = await supabase.auth.signInWithPassword({
email,
password
});
if (signInError) { if (!user?.email) {
return { return {
success: false, success: false,
error: 'Invalid email or password' error: 'No email found for current user'
}; };
} }
// Step 2: Trigger email confirmation to create identity console.log('[IdentityService] Triggering email confirmation for orphaned password');
console.log('[IdentityService] Credentials verified, triggering email confirmation');
const { error: updateError } = await supabase.auth.updateUser({ const { error } = await supabase.auth.updateUser({
email: email // Re-confirming email triggers identity creation email: user.email
}); });
if (updateError) throw updateError; if (error) throw error;
// Step 3: Sign out so user can confirm email await logIdentityChange(user.id, 'orphaned_password_confirmation_triggered', {
console.log('[IdentityService] Signing out to complete email confirmation'); method: 'manual_button_click'
await supabase.auth.signOut(); });
// Step 4: Log the verification
if (authData.user) {
await logIdentityChange(authData.user.id, 'password_verified', {
method: 'orphaned_password_recovery'
});
}
return { return {
success: true, success: true,
needsEmailConfirmation: true, needsEmailConfirmation: true,
email email: user.email
}; };
} catch (error: any) { } catch (error: any) {
console.error('[IdentityService] Failed to verify password:', error); console.error('[IdentityService] Failed to trigger confirmation:', error);
return { return {
success: false, success: false,
error: error.message || 'Failed to verify password authentication' error: error.message || 'Failed to trigger email confirmation'
}; };
} }
} }