All files / src/viewmodels/profile useChangePasswordViewModel.ts

94% Statements 47/50
88.88% Branches 16/18
100% Functions 7/7
93.47% Lines 43/46

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 1201x 1x 1x 1x 1x                                                     1x 18x 18x         18x 18x 18x 18x   18x   15x 15x 15x 15x         18x   6x           6x 1x     6x 1x     15x 6x 3x 3x     3x         3x 3x 3x   3x 3x 1x 1x         1x   2x 2x 1x   1x         2x   3x       18x                    
import { useState, useCallback } from 'react';
import { changePassword } from '@/services/profileService';
import { ApiError } from '@/services/api';
import { useAuth } from '@/contexts/AuthContext';
import { validatePassword } from '@/utils/validators';
 
export interface ChangePasswordFormData {
  currentPassword: string;
  newPassword: string;
  confirmPassword: string;
}
 
export interface ChangePasswordFormErrors {
  currentPassword?: string | null;
  newPassword?: string | null;
  confirmPassword?: string | null;
}
 
export interface ChangePasswordViewModel {
  formData: ChangePasswordFormData;
  errors: ChangePasswordFormErrors;
  isLoading: boolean;
  apiError: string | null;
  successMessage: string | null;
  updateField: <K extends keyof ChangePasswordFormData>(
    field: K,
    value: string,
  ) => void;
  handleSubmit: () => Promise<boolean>;
}
 
export function useChangePasswordViewModel(): ChangePasswordViewModel {
  const { token } = useAuth();
  const [formData, setFormData] = useState<ChangePasswordFormData>({
    currentPassword: '',
    newPassword: '',
    confirmPassword: '',
  });
  const [errors, setErrors] = useState<ChangePasswordFormErrors>({});
  const [isLoading, setIsLoading] = useState(false);
  const [apiError, setApiError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
 
  const updateField = useCallback(
    <K extends keyof ChangePasswordFormData>(field: K, value: string) => {
      setFormData((prev) => ({ ...prev, [field]: value }));
      setErrors((prev) => ({ ...prev, [field]: null }));
      setApiError(null);
      setSuccessMessage(null);
    },
    [],
  );
 
  const handleSubmit = useCallback(async (): Promise<boolean> => {
    // Client-side validation
    const newErrors: ChangePasswordFormErrors = {
      currentPassword: !formData.currentPassword ? 'Current password is required.' : null,
      newPassword: validatePassword(formData.newPassword),
      confirmPassword: !formData.confirmPassword ? 'Please confirm your new password.' : null,
    };
 
    if (!newErrors.confirmPassword && formData.newPassword !== formData.confirmPassword) {
      newErrors.confirmPassword = 'Passwords do not match.';
    }
 
    if (!newErrors.newPassword && formData.currentPassword === formData.newPassword) {
      newErrors.newPassword = 'New password must be different from current password.';
    }
 
    const hasErrors = Object.values(newErrors).some((e) => e != null);
    if (hasErrors) {
      setErrors(newErrors);
      return false;
    }
 
    Iif (!token) {
      setApiError('You must be logged in to change your password.');
      return false;
    }
 
    setIsLoading(true);
    setApiError(null);
    setSuccessMessage(null);
 
    try {
      await changePassword(formData.currentPassword, formData.newPassword, token);
      setSuccessMessage('Password changed successfully.');
      setFormData({
        currentPassword: '',
        newPassword: '',
        confirmPassword: '',
      });
      return true;
    } catch (err) {
      if (err instanceof ApiError) {
        if (err.status === 401 || err.status === 403) {
          setErrors((prev) => ({ ...prev, currentPassword: 'Current password is incorrect.' }));
        } else {
          setApiError(err.message);
        }
      } else E{
        setApiError('An unexpected error occurred. Please try again.');
      }
      return false;
    } finally {
      setIsLoading(false);
    }
  }, [formData, token]);
 
  return {
    formData,
    errors,
    isLoading,
    apiError,
    successMessage,
    updateField,
    handleSubmit,
  };
}