All files / components/auth B2CSignupForm.tsx

96.72% Statements 59/61
87.87% Branches 29/33
100% Functions 6/6
98.33% Lines 59/60

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              1x 1x 1x 1x               1x 1x 1x 1x 1x           1x 668x 668x 668x 668x 668x 668x 668x   668x 15x 15x 1x 1x   14x 14x     668x 15x 15x 15x   15x 1x     14x 1x 1x     13x 13x 5x 5x     8x   8x 8x                     2x   1x 1x   1x         4x 4x   1x 3x 1x 2x 1x   1x           6x       668x   668x                                         253x 253x                               182x                               191x                                                                                                  
"use client";
 
/**
 * B2CSignupForm - Self-serve signup form for B2C users
 * @see /tests/features/authentication/b2c-self-serve-signup.feature
 * @see JCN-4
 */
import { useState } from "react";
import { signUp } from "aws-amplify/auth";
import { validatePassword, validateEmail } from "@/lib/validation";
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, Mail } from "lucide-react";
 
interface B2CSignupFormProps {
  onSuccess?: (email: string) => void;
}
 
export function B2CSignupForm({ onSuccess }: B2CSignupFormProps) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [localEmailError, setLocalEmailError] = useState("");
  const [localPasswordError, setLocalPasswordError] = useState("");
 
  const handleEmailValidation = (emailValue: string) => {
    const result = validateEmail(emailValue);
    if (!result.valid) {
      setLocalEmailError(result.error!);
      return false;
    }
    setLocalEmailError("");
    return true;
  };
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setLocalPasswordError("");
 
    if (!handleEmailValidation(email)) {
      return;
    }
 
    if (password !== confirmPassword) {
      setLocalPasswordError("Passwords do not match");
      return;
    }
 
    const passwordResult = validatePassword(password);
    if (!passwordResult.valid) {
      setLocalPasswordError(passwordResult.error!);
      return;
    }
 
    setIsLoading(true);
 
    try {
      const { isSignUpComplete, nextStep } = await signUp({
        username: email,
        password,
        options: {
          userAttributes: {
            email,
          },
          autoSignIn: true,
        },
      });
 
      if (nextStep.signUpStep === "CONFIRM_SIGN_UP") {
        // User needs to verify email
        onSuccess?.(email);
      } else Eif (isSignUpComplete) {
        // Unlikely for email verification flow, but handle it
        onSuccess?.(email);
      }
    } catch (err: unknown) {
 
      // Handle specific Cognito errors
      if (err instanceof Error) {
        if (err.name === "UsernameExistsException") {
          // Generic message to avoid email enumeration (JCN-18)
          setError("Unable to create account. If you already have an account, please sign in.");
        } else if (err.name === "InvalidPasswordException") {
          setLocalPasswordError("Password does not meet requirements");
        } else if (err.name === "InvalidParameterException") {
          setError("Invalid input. Please check your email and password.");
        } else {
          setError(err.message || "An error occurred during signup. Please try again.");
        }
      } else E{
        setError("An error occurred during signup. Please try again.");
      }
    } finally {
      setIsLoading(false);
    }
  };
 
  const displayError = error || localEmailError || localPasswordError;
 
  return (
    <Card className="w-full max-w-md mx-auto" data-testid="signup-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>Create your account</CardTitle>
        <CardDescription>
          Sign up to start managing your pre-owned goods
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit}>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              data-testid="signup-email"
              value={email}
              onChange={(e) => {
                setEmail(e.target.value);
                Iif (localEmailError) handleEmailValidation(e.target.value);
              }}
              placeholder="you@example.com"
              required
              disabled={isLoading}
              aria-invalid={!!localEmailError}
              aria-describedby={localEmailError ? "email-error" : undefined}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="password">Password</Label>
            <Input
              id="password"
              type="password"
              data-testid="signup-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Create a secure password"
              required
              disabled={isLoading}
              minLength={8}
              aria-invalid={!!localPasswordError}
              aria-describedby="password-requirements"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="confirmPassword">Confirm Password</Label>
            <Input
              id="confirmPassword"
              type="password"
              data-testid="signup-confirm-password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              placeholder="Confirm your password"
              required
              disabled={isLoading}
              aria-invalid={!!localPasswordError}
            />
          </div>
          {displayError && (
            <Alert variant="destructive" data-testid="signup-error">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Error</AlertTitle>
              <AlertDescription id="email-error">
                {displayError}
              </AlertDescription>
            </Alert>
          )}
          <div
            id="password-requirements"
            className="rounded-md bg-muted p-3 text-sm text-muted-foreground"
          >
            <p className="font-medium mb-1">Password requirements:</p>
            <ul className="list-disc list-inside space-y-1">
              <li>At least 8 characters</li>
              <li>One uppercase letter</li>
              <li>One lowercase letter</li>
              <li>One number</li>
              <li>One symbol (!@#$%^&*)</li>
            </ul>
          </div>
        </CardContent>
        <CardFooter className="flex flex-col gap-4">
          <Button type="submit" className="w-full" disabled={isLoading} data-testid="signup-submit">
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Create Account
          </Button>
          <p className="text-sm text-center text-muted-foreground">
            Already have an account?{" "}
            <a
              href="/signin"
              className="text-primary hover:underline font-medium"
            >
              Sign in
            </a>
          </p>
        </CardFooter>
      </form>
    </Card>
  );
}