All files / src/pages PasswordResetPage.tsx

100% Statements 47/47
100% Branches 40/40
100% Functions 7/7
100% Lines 47/47

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                                        43x 43x 43x     43x 43x 43x     43x 43x 43x 43x     43x 43x 43x     43x 43x     43x 9x 1x       43x 8x 8x 8x 8x   8x 2x 2x   6x 1x 1x     5x 5x 5x               2x 1x   1x     4x 1x 3x 1x   2x 2x     5x       43x                             43x                                                     7x                                                     1x                       1x                      
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useSearchParams } from 'react-router-dom';
import Seo from '../components/Seo';
import { PageWrapper } from '../components/PageWrapper';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import Link from '@mui/material/Link';
import CircularProgress from '@mui/material/CircularProgress';
import AlertMessage from '../components/AlertMessage';
import { useLanguageStore } from '../stores/useLanguageStore';
import { resetPassword } from '../services/authService';
import { getErrorMessage } from '../utils/errorUtils';
import { logError } from '../utils/logger';
import PasswordWithConfirmation from '../components/PasswordWithConfirmation';
import { isStrongPassword } from '../utils/validation';
 
export default function PasswordResetPage() {
  const { t } = useTranslation('passwordReset');
  const navigate = useNavigate();
  const lang = useLanguageStore.getState().lang;
 
  // Récupère token & email depuis l'URL
  const [searchParams] = useSearchParams();
  const token = searchParams.get('token') ?? '';
  const emailFromUrl = searchParams.get('email') ?? '';
 
  // états des champs
  const [email] = useState(emailFromUrl);
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [touched, setTouched] = useState(false);
 
  // UI
  const [loading, setLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
 
  // Valide format & match
  const pwStrong = isStrongPassword(password);
  const pwsMatch = password === confirmPassword;
 
  // Si on arrive sans token ou email, on renvoie vers login
  useEffect(() => {
    if (!token || !email) {
      navigate('/login', { replace: true });
    }
  }, [token, email, navigate]);
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg(null);
    setSuccessMsg(null);
    setTouched(true);
 
    if (!pwStrong) {
      setErrorMsg(t('errors.passwordNotStrong'));
      return;
    }
    if (!pwsMatch) {
      setErrorMsg(t('errors.passwordsDontMatch'));
      return;
    }
 
    setLoading(true);
    try {
      const { status } = await resetPassword(
        token,
        email,
        password,
        confirmPassword,
        lang
      );
 
      if (status >= 200 && status < 300) {
        setSuccessMsg(t('passwordReset.successMessage'));
      } else {
        throw new Error('Unexpected status');
      }
    } catch (err: any) {
      if (err.response && err.response.data?.code) {
        setErrorMsg(getErrorMessage(t, err.response.data.code));
      } else if (err.isAxiosError) {
        setErrorMsg(getErrorMessage(t, 'network_error'));
      } else {
        logError('PasswordResetPage:handleSubmit', err);
        setErrorMsg(getErrorMessage(t, 'generic_error'));
      }
    } finally {
      setLoading(false);
    }
  };
 
  return (
    <>
      <Seo title={t('seo.title')} description={t('seo.description')} />
      <PageWrapper disableCard>
        <Box
          component="form"
          onSubmit={handleSubmit}
          sx={{
            maxWidth: 400,
            mx: 'auto',
            mt: { xs: 1, sm: 4, md: 8 },
            p: 4,
            borderRadius: 2,
            boxShadow: 3,
            backgroundColor: 'background.paper',
            border: (theme) => `1px solid ${theme.palette.divider}`,
          }}
        >
          <Typography variant="h4" gutterBottom align="center">
            {t('passwordReset.title')}
          </Typography>
          <Typography variant="body1" align="center" sx={{ mb: 2 }}>
            {t('passwordReset.description')}
          </Typography>
 
          {(errorMsg || successMsg) && (
            <Box aria-live="polite" sx={{ mb: 2 }}>
              <AlertMessage
                message={errorMsg ?? successMsg!}
                severity={successMsg ? 'success' : 'error'}
              />
            </Box>
          )}
 
          {!successMsg && (
            <Stack spacing={2}>
              <PasswordWithConfirmation
                password={password}
                onPasswordChange={setPassword}
                confirmPassword={confirmPassword}
                onConfirmChange={setConfirmPassword}
                touched={touched}
                onBlur={() => setTouched(true)}
              />
 
              <Button
                type="submit"
                variant="contained"
                fullWidth
                disabled={
                  loading ||
                  !pwStrong ||
                  !pwsMatch
                }
                startIcon={
                  loading
                    ? <CircularProgress color="inherit" size={16} />
                    : undefined
                }
              >
                {loading
                  ? `${t('passwordReset.buttonLoading')}…`
                  : t('passwordReset.button')}
              </Button>
 
              <Box sx={{ textAlign: 'center', mt: 1 }}>
                <Link
                  component="button"
                  variant="body2"
                  onClick={() => navigate('/login')}
                >
                  {t('passwordReset.backToLogin')}
                </Link>
              </Box>
            </Stack>
          )}
 
          {successMsg && (
            <Box sx={{ textAlign: 'center', mt: 2 }}>
              <Button
                variant="outlined"
                onClick={() => navigate('/login')}
              >
                {t('passwordReset.goToLogin')}
              </Button>
            </Box>
          )}
        </Box>
      </PageWrapper>
    </>
  );
}