All files / app/(dashboard)/settings/verification/phone page.tsx

80.56% Statements 257/319
61.53% Branches 24/39
87.5% Functions 7/8
80.56% Lines 257/319

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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 3991x                                       1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   26x 26x 26x   26x 26x 26x 26x 26x 26x 26x   26x 26x   26x 4x   4x                 4x                 4x   4x   4x 4x 4x 4x 4x   4x   4x       4x 4x 4x 4x 4x 4x 4x           4x 4x 4x 4x   26x 1x   1x                 1x   1x   1x 1x 1x 1x 1x   1x   1x       1x 1x 1x 1x 1x     1x   1x 1x           1x 1x 1x 1x   26x 1x   1x   1x 1x 1x 1x 1x   1x   1x       1x 1x 1x 1x 1x 1x           1x 1x 1x 1x   26x 1x 1x 1x 1x     1x   26x 26x   26x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x   1x   25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x   25x 25x 25x 25x     25x 25x   25x 25x 25x 26x 26x 26x 26x 17x 8x 26x 26x 26x 26x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 306x 306x 306x 306x 306x 306x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x   17x                                           17x 17x 4x 4x   4x   13x 13x   13x   17x 17x   8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 2x 2x   2x   6x   8x   8x 8x 8x 8x 8x 8x 8x   8x 8x 8x   26x 26x   26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x   26x  
'use client';
 
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Phone, Loader2, ShieldCheck, CheckCircle2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { useToast } from '@/hooks/use-toast';
import { Turnstile } from '@/components/auth/Turnstile';
 
const TURNSTILE_SITE_KEY = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;
 
// Common country codes
const COUNTRY_CODES = [
  { code: '+91', country: 'IN', name: 'India', maxLength: 10 },
  { code: '+1', country: 'US', name: 'United States', maxLength: 10 },
  { code: '+44', country: 'GB', name: 'United Kingdom', maxLength: 10 },
  { code: '+971', country: 'AE', name: 'UAE', maxLength: 9 },
  { code: '+65', country: 'SG', name: 'Singapore', maxLength: 8 },
  { code: '+61', country: 'AU', name: 'Australia', maxLength: 9 },
  { code: '+49', country: 'DE', name: 'Germany', maxLength: 11 },
  { code: '+33', country: 'FR', name: 'France', maxLength: 9 },
  { code: '+81', country: 'JP', name: 'Japan', maxLength: 10 },
  { code: '+86', country: 'CN', name: 'China', maxLength: 11 },
  { code: '+82', country: 'KR', name: 'South Korea', maxLength: 10 },
  { code: '+966', country: 'SA', name: 'Saudi Arabia', maxLength: 9 },
  { code: '+974', country: 'QA', name: 'Qatar', maxLength: 8 },
  { code: '+60', country: 'MY', name: 'Malaysia', maxLength: 10 },
  { code: '+977', country: 'NP', name: 'Nepal', maxLength: 10 },
  { code: '+880', country: 'BD', name: 'Bangladesh', maxLength: 10 },
  { code: '+92', country: 'PK', name: 'Pakistan', maxLength: 10 },
  { code: '+94', country: 'LK', name: 'Sri Lanka', maxLength: 9 },
];
 
export default function PhoneVerificationPage() {
  const router = useRouter();
  const { toast } = useToast();
 
  const [step, setStep] = useState<'phone' | 'otp' | 'success'>('phone');
  const [countryCode, setCountryCode] = useState('+91');
  const [phone, setPhone] = useState('');
  const [otp, setOtp] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [maskedPhone, setMaskedPhone] = useState('');
  const [captchaToken, setCaptchaToken] = useState<string | null>(null);
 
  const selectedCountry = COUNTRY_CODES.find((c) => c.code === countryCode) || COUNTRY_CODES[0];
  const phoneMaxLength = selectedCountry.maxLength;
 
  const handleSendOTP = async (e: React.FormEvent) => {
    e.preventDefault();
 
    if (!phone || phone.length < phoneMaxLength - 2) {
      toast({
        title: 'Invalid phone number',
        description: `Please enter a valid ${phoneMaxLength}-digit phone number`,
        variant: 'destructive',
      });
      return;
    }
 
    if (TURNSTILE_SITE_KEY && !captchaToken) {
      toast({
        title: 'CAPTCHA required',
        description: 'Please complete the security check',
        variant: 'destructive',
      });
      return;
    }
 
    setIsLoading(true);
 
    try {
      // Use /update endpoint for authenticated users (dashboard)
      const response = await fetch('/api/auth/phone/update', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone, countryCode, captchaToken }),
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        throw new Error(data.error || 'Failed to send OTP');
      }
 
      setMaskedPhone(data.phone_masked);
      setStep('otp');
      toast({
        title: 'OTP Sent',
        description: `Verification code sent to ${data.phone_masked}`,
      });
    } catch (error) {
      toast({
        title: 'Error',
        description: error instanceof Error ? error.message : 'Failed to send OTP',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };
 
  const handleVerifyOTP = async (e: React.FormEvent) => {
    e.preventDefault();
 
    if (!otp || otp.length !== 6) {
      toast({
        title: 'Invalid OTP',
        description: 'Please enter the 6-digit code',
        variant: 'destructive',
      });
      return;
    }
 
    setIsLoading(true);
 
    try {
      // Use /verify-update endpoint for authenticated users (dashboard)
      const response = await fetch('/api/auth/phone/verify-update', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone, countryCode, token: otp }),
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        throw new Error(data.error || 'Verification failed');
      }
 
      setStep('success');
      toast({
        title: 'Phone Verified!',
        description: 'Your phone number has been verified successfully',
      });
 
      // Redirect after a short delay with hard navigation to ensure fresh data
      setTimeout(() => {
        window.location.href = '/dashboard';
      }, 2000);
    } catch (error) {
      toast({
        title: 'Verification Failed',
        description: error instanceof Error ? error.message : 'Invalid or expired OTP',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };
 
  const handleResendOTP = async () => {
    setIsLoading(true);
 
    try {
      // Use /update endpoint for authenticated users (dashboard) with isResend flag
      const response = await fetch('/api/auth/phone/update', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone, countryCode, isResend: true }),
      });
 
      const data = await response.json();
 
      if (!response.ok) {
        throw new Error(data.error || 'Failed to resend OTP');
      }
 
      setOtp(''); // Clear previous OTP
      toast({
        title: 'OTP Resent',
        description: `New code sent to ${data.phone_masked}`,
      });
    } catch (error) {
      toast({
        title: 'Error',
        description: error instanceof Error ? error.message : 'Failed to resend OTP',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };
 
  const handleGoBack = () => {
    if (step === 'otp') {
      setStep('phone');
      setOtp('');
    } else {
      router.push('/dashboard');
    }
  };
 
  const isCaptchaRequired = !!TURNSTILE_SITE_KEY;
  const canSubmitPhone = phone.length >= phoneMaxLength - 2 && (!isCaptchaRequired || captchaToken);
 
  if (step === 'success') {
    return (
      <div className="space-y-6">
        <Card className="border-green-500/30 bg-green-500/10 dark:border-green-400/30 dark:bg-green-400/10">
          <CardContent className="pt-6 text-center">
            <CheckCircle2 className="mx-auto mb-4 h-16 w-16 text-green-500" />
            <h2 className="text-2xl font-bold text-green-700 dark:text-green-400">
              Phone Verified!
            </h2>
            <p className="mt-2 text-green-600 dark:text-green-500">
              Your phone number has been verified successfully.
            </p>
            <p className="mt-4 text-sm text-muted-foreground">Redirecting to dashboard...</p>
          </CardContent>
        </Card>
      </div>
    );
  }
 
  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" onClick={handleGoBack}>
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div>
          <h1 className="text-2xl font-bold">Phone Verification</h1>
          <p className="text-muted-foreground">Verify your phone number with OTP</p>
        </div>
      </div>
 
      <Alert>
        <Phone className="h-4 w-4" />
        <AlertTitle>Secure OTP Verification</AlertTitle>
        <AlertDescription>
          We&apos;ll send a one-time password to your phone number. This helps verify your identity
          and secure your account.
        </AlertDescription>
      </Alert>
 
      <Card>
        <CardHeader>
          <CardTitle>
            {step === 'phone' ? 'Enter Phone Number' : 'Enter Verification Code'}
          </CardTitle>
          <CardDescription>
            {step === 'phone'
              ? 'Enter your mobile number'
              : `Enter the 6-digit code sent to ${maskedPhone}`}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {step === 'phone' ? (
            <form onSubmit={handleSendOTP} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="phone">Phone Number</Label>
                <div className="flex gap-2">
                  <Select value={countryCode} onValueChange={setCountryCode} disabled={isLoading}>
                    <SelectTrigger className="w-[110px]">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {COUNTRY_CODES.map((country) => (
                        <SelectItem key={country.code} value={country.code}>
                          <span className="flex items-center gap-2">
                            <span className="text-muted-foreground">{country.country}</span>
                            <span>{country.code}</span>
                          </span>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <Input
                    id="phone"
                    type="tel"
                    inputMode="numeric"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value.replace(/\D/g, ''))}
                    placeholder={selectedCountry.code === '+91' ? '9876543210' : 'Phone number'}
                    maxLength={phoneMaxLength}
                    disabled={isLoading}
                    className="flex-1"
                  />
                </div>
              </div>
 
              {isCaptchaRequired && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <ShieldCheck className="h-4 w-4" />
                    <span>Security verification</span>
                  </div>
                  <Turnstile
                    siteKey={TURNSTILE_SITE_KEY}
                    onVerify={setCaptchaToken}
                    onExpire={() => setCaptchaToken(null)}
                    theme="auto"
                    className="flex justify-center"
                  />
                  {captchaToken && (
                    <p className="flex items-center justify-center gap-1 text-center text-xs text-green-600">
                      <ShieldCheck className="h-3 w-3" />
                      Verified
                    </p>
                  )}
                </div>
              )}
 
              <Button type="submit" className="w-full" disabled={isLoading || !canSubmitPhone}>
                {isLoading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Sending OTP...
                  </>
                ) : (
                  <>
                    <Phone className="mr-2 h-4 w-4" />
                    Send OTP
                  </>
                )}
              </Button>
            </form>
          ) : (
            <form onSubmit={handleVerifyOTP} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="otp">Verification Code</Label>
                <Input
                  id="otp"
                  type="text"
                  inputMode="numeric"
                  pattern="[0-9]*"
                  maxLength={6}
                  value={otp}
                  onChange={(e) => setOtp(e.target.value.replace(/\D/g, ''))}
                  placeholder="000000"
                  className="text-center text-2xl tracking-widest"
                  disabled={isLoading}
                  autoComplete="one-time-code"
                />
              </div>
 
              <Button type="submit" className="w-full" disabled={isLoading || otp.length !== 6}>
                {isLoading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Verifying...
                  </>
                ) : (
                  'Verify & Continue'
                )}
              </Button>
 
              <div className="text-center">
                <button
                  type="button"
                  onClick={handleResendOTP}
                  disabled={isLoading}
                  className="text-sm text-primary hover:underline disabled:opacity-50"
                >
                  Didn&apos;t receive code? Resend
                </button>
              </div>
            </form>
          )}
        </CardContent>
      </Card>
 
      <Card>
        <CardHeader>
          <CardTitle>Why verify your phone?</CardTitle>
        </CardHeader>
        <CardContent>
          <ul className="space-y-2">
            <li className="flex items-center gap-2 text-sm">
              <CheckCircle2 className="h-4 w-4 text-green-500" />
              <span>Get the &quot;Phone Verified&quot; badge on your profile</span>
            </li>
            <li className="flex items-center gap-2 text-sm">
              <CheckCircle2 className="h-4 w-4 text-green-500" />
              <span>Increase trust with potential clients</span>
            </li>
            <li className="flex items-center gap-2 text-sm">
              <CheckCircle2 className="h-4 w-4 text-green-500" />
              <span>Enable phone-based login for faster access</span>
            </li>
          </ul>
        </CardContent>
      </Card>
    </div>
  );
}