All files / components/auth InvitationSignupForm.tsx

89.61% Statements 69/77
74% Branches 37/50
88.88% Functions 8/9
89.61% Lines 69/77

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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344                  1x 1x 1x 1x               1x 1x 1x 1x 1x                       1x             316x 316x 316x 316x 316x 316x   316x 10x     10x 1x   9x     9x     9x 1x   8x     316x 11x 11x   11x 1x 1x     10x 10x 2x 2x     8x   8x       8x                           6x 6x     1x 1x   1x               7x       316x 2x 2x 2x   2x 2x         1x 1x     1x 1x           1x         1x 1x 1x               2x       316x 1x                                     315x 21x                                   12x                                                               294x                                                                 131x                           136x                                                                             1x 4x                                          
"use client";
 
/**
 * InvitationSignupForm - Signup form for invited organisation owners
 * @see /docs/requirements/jcn-5-organisation-tenant-creation/mini-prd.md
 * @see JCN-5
 *
 * NOTE: Organisation users cannot use social login - email/password only
 */
import { useState } from "react";
import Link from "next/link";
import { signUp, confirmSignUp, 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, Building2, CheckCircle2 } from "lucide-react";
 
interface InvitationSignupFormProps {
  email: string;
  organisationName: string;
  invitationToken: string;
  tenantId: string;
  onSuccess?: () => void;
}
 
type Step = "password" | "verify" | "success";
 
export function InvitationSignupForm({
  email,
  organisationName,
  invitationToken,
  tenantId,
  onSuccess,
}: InvitationSignupFormProps) {
  const [step, setStep] = useState<Step>("password");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [verificationCode, setVerificationCode] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
 
  const validatePassword = (pwd: string) => {
    Iif (pwd.length < 8) {
      return "Password must be at least 8 characters";
    }
    if (!/[A-Z]/.test(pwd)) {
      return "Password must contain an uppercase letter";
    }
    Iif (!/[a-z]/.test(pwd)) {
      return "Password must contain a lowercase letter";
    }
    Iif (!/[0-9]/.test(pwd)) {
      return "Password must contain a number";
    }
    if (!/[^A-Za-z0-9]/.test(pwd)) {
      return "Password must contain a symbol (e.g., !@#$%^&*)";
    }
    return null;
  };
 
  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
 
    if (password !== confirmPassword) {
      setError("Passwords do not match");
      return;
    }
 
    const passwordError = validatePassword(password);
    if (passwordError) {
      setError(passwordError);
      return;
    }
 
    setIsLoading(true);
 
    try {
      // Sign up with custom attributes for org user
      // Note: invitation_token is NOT stored in Cognito - it was already validated
      // when loading the invite page. We only need tenant_id and role.
      const { nextStep } = await signUp({
        username: email,
        password,
        options: {
          userAttributes: {
            email,
            "custom:user_type": "org",
            "custom:tenant_id": tenantId,
            "custom:role": "owner",
          },
          autoSignIn: true,
        },
      });
 
      Eif (nextStep.signUpStep === "CONFIRM_SIGN_UP") {
        setStep("verify");
      }
    } catch (err: unknown) {
      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 E{
          setError(err.message || "Failed to create account. Please try again.");
        }
      } else E{
        setError("Failed to create account. Please try again.");
      }
    } finally {
      setIsLoading(false);
    }
  };
 
  const handleVerificationSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setIsLoading(true);
 
    try {
      const { isSignUpComplete } = await confirmSignUp({
        username: email,
        confirmationCode: verificationCode,
      });
 
      Eif (isSignUpComplete) {
        setStep("success");
 
        // 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
        setTimeout(() => {
          onSuccess?.();
        }, 2000);
      }
    } catch (err: unknown) {
      if (err instanceof Error) {
        if (err.name === "CodeMismatchException") {
          setError("Invalid verification code. Please check and try again.");
        } else E{
          setError(err.message || "Verification failed. Please try again.");
        }
      } else E{
        setError("Verification failed. Please try again.");
      }
    } finally {
      setIsLoading(false);
    }
  };
 
  if (step === "success") {
    return (
      <Card className="w-full max-w-md mx-auto">
        <CardHeader className="text-center">
          <CheckCircle2 className="h-12 w-12 text-green-500 mx-auto mb-4" />
          <CardTitle>Account Created!</CardTitle>
          <CardDescription>
            Welcome to {organisationName}. You are now the organisation owner.
          </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" />
            Redirecting to dashboard...
          </div>
        </CardFooter>
      </Card>
    );
  }
 
  if (step === "verify") {
    return (
      <Card className="w-full max-w-md mx-auto">
        <CardHeader className="text-center">
          <Building2 className="h-8 w-8 text-primary mx-auto mb-4" />
          <CardTitle>Verify your email</CardTitle>
          <CardDescription>
            We sent a verification code to <strong>{email}</strong>
          </CardDescription>
        </CardHeader>
        <form onSubmit={handleVerificationSubmit}>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="code">Verification Code</Label>
              <Input
                id="code"
                type="text"
                data-testid="invite-verification-code"
                value={verificationCode}
                onChange={(e) => setVerificationCode(e.target.value.replace(/\D/g, ""))}
                placeholder="Enter 6-digit code"
                maxLength={6}
                required
                disabled={isLoading}
                className="text-center text-2xl tracking-widest"
              />
            </div>
            {error && (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertTitle>Error</AlertTitle>
                <AlertDescription>{error}</AlertDescription>
              </Alert>
            )}
          </CardContent>
          <CardFooter>
            <Button
              type="submit"
              className="w-full"
              disabled={isLoading || verificationCode.length !== 6}
              data-testid="invite-verification-submit"
            >
              {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Verify Email
            </Button>
          </CardFooter>
        </form>
      </Card>
    );
  }
 
  return (
    <Card className="w-full max-w-md mx-auto" data-testid="invitation-signup">
      <CardHeader className="text-center">
        <div className="flex items-center justify-center gap-2 mb-4">
          <Building2 className="h-8 w-8 text-primary" />
        </div>
        <CardTitle>Join {organisationName}</CardTitle>
        <CardDescription>
          Complete your account setup to become an owner of {organisationName}
        </CardDescription>
      </CardHeader>
      <form onSubmit={handlePasswordSubmit} data-testid="invitation-form">
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              value={email}
              disabled
              className="bg-muted"
            />
            <p className="text-xs text-muted-foreground">
              Your email is set by the invitation
            </p>
          </div>
          <div className="space-y-2">
            <Label htmlFor="password">Password</Label>
            <Input
              id="password"
              type="password"
              data-testid="invite-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Create a secure password"
              required
              disabled={isLoading}
              minLength={8}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="confirmPassword">Confirm Password</Label>
            <Input
              id="confirmPassword"
              type="password"
              data-testid="invite-confirm-password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              placeholder="Confirm your password"
              required
              disabled={isLoading}
            />
          </div>
          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>Error</AlertTitle>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}
          <div 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>
          <Button type="submit" className="w-full" disabled={isLoading} data-testid="invite-submit">
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Complete Signup
          </Button>
        </CardFooter>
      </form>
    </Card>
  );
}
 
interface InvitationErrorProps {
  type: "expired" | "invalid";
}
 
export function InvitationError({ type }: InvitationErrorProps) {
  return (
    <Card className="w-full max-w-md mx-auto" data-testid={type === "expired" ? "invitation-expired" : "invitation-invalid"}>
      <CardHeader className="text-center">
        <AlertCircle className="h-12 w-12 text-destructive mx-auto mb-4" />
        <CardTitle>
          {type === "expired" ? "Invitation Expired" : "Invalid Invitation"}
        </CardTitle>
        <CardDescription>
          {type === "expired"
            ? "This invitation link has expired. Please contact your administrator to request a new invitation."
            : "This invitation link is invalid or has already been used. Please contact your administrator if you believe this is an error."}
        </CardDescription>
      </CardHeader>
      <CardFooter className="flex justify-center gap-4">
        <Button variant="outline" asChild>
          <Link href="/">Go Home</Link>
        </Button>
      </CardFooter>
    </Card>
  );
}