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 | 1x 306x 306x 306x 306x 306x 306x 306x 306x 306x 306x 306x 306x 306x 143x 143x 306x 2x 1x 1x 1x 1x 1x 1x 1x 306x 306x 3x 303x 303x 306x 21x 21x 3x 6x 3x 9x 306x 69x | /**
* ResetPasswordForm Component (TDD - GREEN Phase)
* Story 1.2.2a: Reset Password Confirmation
*
* Implements password reset confirmation with code verification
* Following patterns from Story 1.2.1 (i18n Foundation)
*/
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useForm } from 'react-hook-form';
import { useNavigate, useSearchParams } from 'react-router-dom';
import {
Box,
TextField,
Button,
Typography,
Link,
Alert,
CircularProgress,
IconButton,
InputAdornment,
LinearProgress,
} from '@mui/material';
import { ArrowBack, Visibility, VisibilityOff } from '@mui/icons-material';
import { BATbernLoader } from '@components/shared/BATbernLoader';
import { useResetPassword, type ResetPasswordError } from '@/hooks/useResetPassword';
import { authService } from '@/services/auth/authService';
import {
calculatePasswordStrength,
getPasswordStrengthColor,
getPasswordStrengthValue,
type PasswordStrength,
} from '@/utils/passwordStrength';
interface ResetPasswordFormData {
code: string;
newPassword: string;
confirmPassword: string;
}
export const ResetPasswordForm: React.FC = () => {
const { t } = useTranslation(['auth', 'validation']);
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const email = searchParams.get('email') || '';
const codeFromUrl = searchParams.get('code') || '';
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const [passwordStrength, setPasswordStrength] = useState<PasswordStrength | null>(null);
const [isAutoLoggingIn, setIsAutoLoggingIn] = useState(false);
const { mutate: resetPassword, isPending, isError, isSuccess, error } = useResetPassword();
const {
register,
handleSubmit,
watch,
formState: { errors, isValid },
} = useForm<ResetPasswordFormData>({
mode: 'onChange',
defaultValues: {
code: codeFromUrl,
},
});
const newPassword = watch('newPassword');
// Calculate password strength using utility
useEffect(() => {
const { strength } = calculatePasswordStrength(newPassword);
setPasswordStrength(strength);
}, [newPassword]);
const onSubmit = async (data: ResetPasswordFormData) => {
resetPassword(
{
email,
code: data.code,
newPassword: data.newPassword,
},
{
onSuccess: async () => {
// Attempt auto-login after successful password reset
try {
setIsAutoLoggingIn(true);
const signInResult = await authService.signIn({
email,
password: data.newPassword,
rememberMe: false, // Don't persist session for auto-login
});
Iif (signInResult.success && signInResult.user) {
// Auto-login successful - redirect to dashboard after short delay
setTimeout(() => {
navigate('/dashboard', { replace: true });
}, 1500);
} else {
// Auto-login failed - redirect to login with success message
setTimeout(() => {
navigate('/login', {
state: { message: t('auth:reset.successMessage') },
});
}, 2000);
}
} catch (error) {
// Auto-login failed - redirect to login with success message
console.error('[ResetPasswordForm] Auto-login error:', error);
setTimeout(() => {
navigate('/login', {
state: { message: t('auth:reset.successMessage') },
});
}, 2000);
} finally {
setIsAutoLoggingIn(false);
}
},
}
);
};
const handleRequestNewCode = () => {
navigate('/auth/forgot-password');
};
// Show success state
if (isSuccess) {
return (
<Box sx={{ maxWidth: 400, mx: 'auto', mt: 8, textAlign: 'center' }}>
<Alert severity="success" sx={{ mb: 3 }}>
{t('auth:reset.successMessage')}
</Alert>
<Typography variant="body2" color="text.secondary">
{isAutoLoggingIn
? t('auth:reset.loggingIn', 'Logging you in...')
: t('auth:reset.redirecting')}
</Typography>
<BATbernLoader size={64} />
</Box>
);
}
// Get error info
const resetPasswordError = error as ResetPasswordError | undefined;
const errorType = resetPasswordError?.type;
const getErrorMessage = () => {
Iif (!errorType) return null;
switch (errorType) {
case 'invalidCode':
return t('auth:reset.errors.invalidCode');
case 'expiredCode':
return t('auth:reset.errors.expiredCode');
case 'invalidPassword':
return t('auth:reset.errors.invalidPassword');
case 'rateLimitExceeded':
return t('auth:reset.errors.rateLimitExceeded');
default:
return t('auth:reset.errors.networkError');
}
};
return (
<Box sx={{ maxWidth: 400, mx: 'auto', mt: 8 }}>
<Link
href="/login"
sx={{
display: 'flex',
alignItems: 'center',
mb: 2,
textDecoration: 'none',
color: 'primary.main',
}}
>
<ArrowBack sx={{ mr: 1 }} />
{t('auth:reset.backToLogin')}
</Link>
<Typography variant="h4" align="center" gutterBottom data-testid="reset-password-title">
{t('auth:reset.title')}
</Typography>
<Typography variant="body2" align="center" color="text.secondary" sx={{ mb: 3 }}>
{t('auth:reset.subtitle')}
</Typography>
{isError && (
<Alert
severity="error"
sx={{ mb: 2 }}
action={
errorType === 'expiredCode' ? (
<Button color="inherit" size="small" onClick={handleRequestNewCode}>
{t('auth:reset.requestNewCode')}
</Button>
) : undefined
}
>
{getErrorMessage()}
</Alert>
)}
<Box component="form" onSubmit={handleSubmit(onSubmit)}>
<TextField
label={t('auth:reset.emailLabel')}
type="email"
fullWidth
margin="normal"
value={email}
disabled
InputProps={{
readOnly: true,
}}
/>
<TextField
{...register('code', {
required: t('auth:reset.errors.invalidCode'),
pattern: {
value: /^\d{6}$/,
message: t('auth:reset.errors.invalidCode'),
},
})}
label={t('auth:reset.codeLabel')}
type="text"
fullWidth
margin="normal"
error={!!errors.code}
helperText={errors.code?.message}
disabled={isPending}
inputProps={{
maxLength: 6,
inputMode: 'numeric',
pattern: '[0-9]*',
}}
/>
<TextField
{...register('newPassword', {
required: t('auth:reset.errors.invalidPassword'),
minLength: {
value: 8,
message: t('auth:reset.errors.invalidPassword'),
},
pattern: {
value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
message: t('auth:reset.errors.invalidPassword'),
},
})}
label={t('auth:reset.newPasswordLabel')}
type={showPassword ? 'text' : 'password'}
fullWidth
margin="normal"
error={!!errors.newPassword}
helperText={errors.newPassword?.message}
disabled={isPending}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label={t(showPassword ? 'login.hidePassword' : 'login.showPassword')}
onClick={() => setShowPassword(!showPassword)}
edge="end"
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
{newPassword && passwordStrength && (
<Box sx={{ mt: 1, mb: 2 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
<Typography variant="caption" color="text.secondary">
Password strength:
</Typography>
<Typography
variant="caption"
color={`${getPasswordStrengthColor(passwordStrength)}.main`}
>
{t(`auth:reset.passwordStrength.${passwordStrength}`)}
</Typography>
</Box>
<LinearProgress
variant="determinate"
value={getPasswordStrengthValue(passwordStrength)}
color={getPasswordStrengthColor(passwordStrength)}
sx={{ height: 6, borderRadius: 1 }}
/>
</Box>
)}
<TextField
{...register('confirmPassword', {
required: t('auth:reset.errors.passwordMismatch'),
validate: (value) => value === newPassword || t('auth:reset.errors.passwordMismatch'),
})}
label={t('auth:reset.confirmPasswordLabel')}
type={showConfirmPassword ? 'text' : 'password'}
fullWidth
margin="normal"
error={!!errors.confirmPassword}
helperText={errors.confirmPassword?.message}
disabled={isPending}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label={t(showConfirmPassword ? 'login.hidePassword' : 'login.showPassword')}
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
edge="end"
>
{showConfirmPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
<Alert severity="info" icon="ℹ️" sx={{ mt: 2, mb: 2 }}>
<Typography variant="body2">{t('auth:reset.passwordRequirements')}</Typography>
</Alert>
<Button
type="submit"
fullWidth
variant="contained"
size="large"
disabled={isPending || !isValid}
sx={{ mt: 2, mb: 2 }}
startIcon={isPending ? <CircularProgress size={20} /> : null}
data-testid="reset-password-submit"
>
{isPending ? t('common:actions.loading') : t('auth:reset.submitButton')}
</Button>
</Box>
</Box>
);
};
|