All files / components/auth EmailVerification.tsx

92.98% Statements 53/57
78.12% Branches 25/32
83.33% Functions 5/6
94.64% Lines 53/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230              1x 1x 1x               1x 1x 1x 1x 1x                         1x 102x 102x 102x 102x 102x 102x 102x   102x 8x 8x 8x 8x   8x 8x         3x 3x     3x 3x           3x 2x       3x 3x 1x 2x 1x 1x   1x               6x       102x 3x 3x 3x 3x   3x 3x     1x   1x   1x 1x         2x       102x 3x                                     99x                                       69x                                                                                                                                                      
"use client";
 
/**
 * EmailVerification - Email verification step after signup
 * @see /tests/features/authentication/b2c-self-serve-signup.feature
 * @see JCN-4
 */
import { useState } from "react";
import { confirmSignUp, resendSignUpCode, autoSignIn } from "aws-amplify/auth";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  Loader2,
  AlertCircle,
  CheckCircle2,
  Mail,
  Clock,
} from "lucide-react";
 
interface EmailVerificationProps {
  email: string;
  onSuccess?: () => void;
}
 
export function EmailVerification({ email, onSuccess }: EmailVerificationProps) {
  const [code, setCode] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [isResending, setIsResending] = useState(false);
  const [error, setError] = useState("");
  const [expired, setExpired] = useState(false);
  const [success, setSuccess] = useState(false);
  const [resendSuccess, setResendSuccess] = useState(false);
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setExpired(false);
    setIsLoading(true);
 
    try {
      const { isSignUpComplete } = await confirmSignUp({
        username: email,
        confirmationCode: code,
      });
 
      Eif (isSignUpComplete) {
        setSuccess(true);
 
        // Auto sign-in after confirmation (silent - no logging)
        try {
          await autoSignIn();
        } catch {
          // Auto sign-in failed, user can sign in manually
        }
 
        // Small delay to show success state before redirect
        setTimeout(() => {
          onSuccess?.();
        }, 1500);
      }
    } catch (err: unknown) {
      if (err instanceof Error) {
        if (err.name === "CodeMismatchException") {
          setError("Invalid verification code. Please check and try again.");
        } else if (err.name === "ExpiredCodeException") {
          setExpired(true);
        } else if (err.name === "NotAuthorizedException") {
          // User might already be confirmed
          setError("This account has already been confirmed. Please sign in.");
        } else E{
          setError(err.message || "Verification failed. Please try again.");
        }
      } else E{
        setError("Verification failed. Please try again.");
      }
    } finally {
      setIsLoading(false);
    }
  };
 
  const handleResend = async () => {
    setError("");
    setExpired(false);
    setResendSuccess(false);
    setIsResending(true);
 
    try {
      await resendSignUpCode({
        username: email,
      });
      setResendSuccess(true);
      // Clear success message after 5 seconds
      setTimeout(() => setResendSuccess(false), 5000);
    } catch (err: unknown) {
      if (err instanceof Error) {
        setError(err.message || "Failed to resend code. Please try again.");
      } else E{
        setError("Failed to resend code. Please try again.");
      }
    } finally {
      setIsResending(false);
    }
  };
 
  if (success) {
    return (
      <Card className="w-full max-w-md mx-auto" data-testid="verification-success">
        <CardHeader className="text-center">
          <CheckCircle2 className="h-12 w-12 text-green-500 mx-auto mb-4" />
          <CardTitle>Email Verified!</CardTitle>
          <CardDescription>
            Your account has been confirmed. Redirecting to your dashboard...
          </CardDescription>
        </CardHeader>
        <CardFooter className="flex justify-center">
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <Loader2 className="h-4 w-4 animate-spin" />
            Setting up your account
          </div>
        </CardFooter>
      </Card>
    );
  }
 
  return (
    <Card className="w-full max-w-md mx-auto" data-testid="verification-form">
      <CardHeader className="text-center">
        <div className="flex items-center justify-center gap-2 mb-4">
          <Mail className="h-8 w-8 text-primary" />
        </div>
        <CardTitle>Check your email</CardTitle>
        <CardDescription>
          We sent a verification code to <strong>{email}</strong>
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit}>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="code">Verification Code</Label>
            <Input
              id="code"
              type="text"
              data-testid="verification-code"
              value={code}
              onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
              placeholder="Enter 6-digit code"
              maxLength={6}
              pattern="\d{6}"
              required
              disabled={isLoading}
              className="text-center text-2xl tracking-widest"
              aria-invalid={!!error}
              aria-describedby={error ? "code-error" : undefined}
            />
            <p className="text-xs text-muted-foreground text-center">
              Enter the 6-digit code from your email
            </p>
          </div>
          {error && (
            <Alert variant="destructive" data-testid="verification-error">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Verification Failed</AlertTitle>
              <AlertDescription id="code-error">{error}</AlertDescription>
            </Alert>
          )}
          {expired && (
            <Alert variant="destructive">
              <Clock className="h-4 w-4" />
              <AlertTitle>Code Expired</AlertTitle>
              <AlertDescription>
                This verification code has expired. Please request a new one.
              </AlertDescription>
            </Alert>
          )}
          {resendSuccess && (
            <Alert>
              <CheckCircle2 className="h-4 w-4" />
              <AlertTitle>Code Sent</AlertTitle>
              <AlertDescription>
                A new verification code has been sent to your email.
              </AlertDescription>
            </Alert>
          )}
        </CardContent>
        <CardFooter className="flex flex-col gap-3">
          <Button
            type="submit"
            className="w-full"
            disabled={isLoading || code.length !== 6}
            data-testid="verification-submit"
          >
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Verify Email
          </Button>
          <div className="text-sm text-center text-muted-foreground">
            Didn&apos;t receive the code?{" "}
            <Button
              type="button"
              variant="link"
              className="p-0 h-auto font-medium"
              onClick={handleResend}
              disabled={isResending}
              data-testid="verification-resend"
            >
              {isResending ? (
                <>
                  <Loader2 className="mr-1 h-3 w-3 animate-spin" />
                  Sending...
                </>
              ) : (
                "Resend code"
              )}
            </Button>
          </div>
        </CardFooter>
      </form>
    </Card>
  );
}