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 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 | 1x 137x 1x 25x 25x 1x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 112x 112x 112x 112x 16x 16x 137x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 137x 137x 137x 137x 137x 1x 1x 136x 136x 137x 1x | /**
* LoginForm Component Implementation
* Story 1.2.1: AWS Cognito Authentication UI with i18n
*/
import React, { useState, useEffect, useRef } from 'react';
import {
Box,
TextField,
Button,
Typography,
FormControlLabel,
Checkbox,
Alert,
CircularProgress,
Link,
Paper,
Container,
IconButton,
InputAdornment,
Divider,
} from '@mui/material';
import { Visibility, VisibilityOff, Google } from '@mui/icons-material';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router-dom';
import { useAuth } from '@hooks/useAuth';
import { useFeature } from '@/contexts/useFeature';
import { authService } from '@/services/auth/authService';
import { consumeLogoutReason } from '@/services/auth/logoutReason';
import { LoginCredentials } from '@/types/auth';
import LanguageSwitcher from '@components/shared/LanguageSwitcher/LanguageSwitcher';
type LoginFormData = {
email: string;
password: string;
rememberMe?: boolean;
};
interface LoginFormProps {
onSuccess?: () => void;
onForgotPassword?: () => void;
onSignUp?: () => void;
}
// Factory function for localized validation schema
const createLoginSchema = (t: (key: string) => string) =>
z.object({
email: z
.string()
.min(1, t('validation:email.required'))
.email(t('validation:email.invalid'))
.max(255, t('validation:email.tooLong')),
password: z
.string()
.min(1, t('validation:password.required'))
.min(8, t('validation:password.tooShort'))
.max(128, t('validation:password.tooLong')),
rememberMe: z.boolean().default(false),
});
// Map error codes to i18n keys
const getErrorTranslationKey = (errorCode?: string): string => {
const errorMap: Record<string, string> = {
INVALID_CREDENTIALS: 'auth:errors.invalidCredentials',
EMAIL_NOT_VERIFIED: 'auth:errors.emailNotVerified',
ACCOUNT_LOCKED: 'auth:errors.accountLocked',
NETWORK_ERROR: 'auth:errors.networkError',
};
return errorMap[errorCode || ''] || 'auth:errors.unknownError';
};
export const LoginForm: React.FC<LoginFormProps> = ({ onSuccess, onForgotPassword, onSignUp }) => {
const { t } = useTranslation(['auth', 'validation']);
const { signIn, confirmNewPassword, isLoading, error, clearError } = useAuth();
// Story 12.9: "Continue with Google" button gated on the runtime features.sso flag.
const ssoEnabled = useFeature('sso');
const [submitError, setSubmitError] = useState<string | null>(null);
// Story 12.7 / G1: the API client redirects here with ?reason=account_deactivated
// after the gateway returns 403 ACCOUNT_DEACTIVATED (it also forced a logout).
// Surface a dismissible notice so the user understands why they were signed out.
const [searchParams] = useSearchParams();
const [deactivatedDismissed, setDeactivatedDismissed] = useState(false);
// Story 12.8 F5: the reason may also arrive via the sessionStorage hand-off instead of
// the query param — e.g. the AuthCallbackPage navigates to plain `/login` after a failed
// federated hydration (its `replace` wipes the interceptor's ?reason=), or Amplify's
// hosted-UI logout redirect swallowed the in-app navigation entirely.
const [storedLogoutReason] = useState(() => consumeLogoutReason());
const showDeactivatedNotice =
(searchParams.get('reason') === 'account_deactivated' ||
storedLogoutReason === 'account_deactivated') &&
!deactivatedDismissed;
const [showPassword, setShowPassword] = useState(false);
// Epic 11 bug fix 2026-05-19 — when Cognito returns
// CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED on first sign-in (with the temp
// password issued by issueInvitationCredentials), switch the form to the
// "set new password" panel. Previously the form silently failed with a
// generic error.
const [pendingNewPassword, setPendingNewPassword] = useState(false);
const [newPassword, setNewPassword] = useState('');
const [confirmPasswordValue, setConfirmPasswordValue] = useState('');
const [showNewPassword, setShowNewPassword] = useState(false);
const [newPasswordError, setNewPasswordError] = useState<string | null>(null);
const {
control,
handleSubmit,
formState: { errors, isValid },
watch,
reset,
} = useForm<LoginFormData>({
resolver: zodResolver(createLoginSchema(t)),
defaultValues: {
email: '',
password: '',
rememberMe: false,
},
mode: 'onChange',
});
// Clear errors when the user starts typing — but ONLY on an actual change of the
// watched values. `error`/`submitError` must stay in the deps (exhaustive-deps), yet
// without the prev-value guard the effect re-fires the moment the error APPEARS and
// wipes it before the Alert ever renders (2026-06-04 regression: wrong-password
// INVALID_CREDENTIALS was never shown — the form just silently re-rendered).
const watchedEmail = watch('email');
const watchedPassword = watch('password');
const prevCredentialsRef = useRef({ email: watchedEmail, password: watchedPassword });
useEffect(() => {
const prev = prevCredentialsRef.current;
const typed = prev.email !== watchedEmail || prev.password !== watchedPassword;
prevCredentialsRef.current = { email: watchedEmail, password: watchedPassword };
if (typed && (error || submitError)) {
clearError();
setSubmitError(null);
}
}, [watchedEmail, watchedPassword, error, submitError, clearError]);
const onSubmit = async (data: LoginFormData) => {
try {
console.log('[LoginForm] Form submitted with data:', {
email: data.email,
rememberMe: data.rememberMe,
});
setSubmitError(null);
const credentials: LoginCredentials = {
email: data.email,
password: data.password,
rememberMe: data.rememberMe,
};
console.log('[LoginForm] Calling signIn...');
const outcome = await signIn(credentials);
console.log('[LoginForm] signIn outcome:', outcome.kind);
Iif (outcome.kind === 'success') {
console.log('[LoginForm] Sign in successful, calling onSuccess callback');
reset();
onSuccess?.();
} else if (Ioutcome.kind === 'requires-new-password') {
console.log('[LoginForm] FORCE_CHANGE_PASSWORD — switching to new-password panel');
setPendingNewPassword(true);
setNewPassword('');
setConfirmPasswordValue('');
setNewPasswordError(null);
} else {
console.log('[LoginForm] Sign in failed');
}
} catch (err) {
console.error('[LoginForm] Error during sign in:', err);
setSubmitError(t('auth:errors.unknownError'));
}
};
const handleSubmitNewPassword = async (event: React.FormEvent) => {
event.preventDefault();
setNewPasswordError(null);
const trimmed = newPassword.trim();
if (trimmed.length < 8) {
setNewPasswordError(t('validation:password.tooShort'));
return;
}
if (trimmed.length > 128) {
setNewPasswordError(t('validation:password.tooLong'));
return;
}
if (newPassword !== confirmPasswordValue) {
setNewPasswordError(t('auth:newPassword.mismatch', 'Passwords do not match'));
return;
}
const success = await confirmNewPassword(newPassword);
if (success) {
console.log('[LoginForm] confirmNewPassword successful');
reset();
setPendingNewPassword(false);
setNewPassword('');
setConfirmPasswordValue('');
onSuccess?.();
}
};
const handleForgotPassword = () => {
onForgotPassword?.();
};
const handleSignUp = () => {
onSignUp?.();
};
// Get localized error message
const displayError = error ? t(getErrorTranslationKey(error.code)) : submitError;
return (
<Container maxWidth="sm">
<Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 2 }}>
<LanguageSwitcher />
</Box>
<Box
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
mt: 2,
}}
>
<Paper elevation={3} sx={{ p: 4, width: '100%' }}>
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<Typography component="h1" variant="h4" gutterBottom>
{pendingNewPassword
? t('auth:newPassword.title', 'Set a new password')
: t('auth:login.title')}
</Typography>
<Typography variant="body2" color="text.secondary" align="center" sx={{ mb: 3 }}>
{pendingNewPassword
? t(
'auth:newPassword.subtitle',
'You signed in with a temporary password. Choose a permanent password to continue.'
)
: t('auth:login.subtitle')}
</Typography>
{showDeactivatedNotice && (
<Alert
severity="warning"
onClose={() => setDeactivatedDismissed(true)}
sx={{ width: '100%', mb: 2 }}
>
{t('auth:login.deactivatedNotice')}
</Alert>
)}
{(displayError || newPasswordError) && (
<Alert severity="error" sx={{ width: '100%', mb: 2 }}>
{newPasswordError || displayError}
</Alert>
)}
{pendingNewPassword ? (
<Box component="form" onSubmit={handleSubmitNewPassword} sx={{ width: '100%' }}>
<TextField
fullWidth
label={t('auth:newPassword.newPasswordLabel', 'New password')}
type={showNewPassword ? 'text' : 'password'}
autoComplete="new-password"
autoFocus
margin="normal"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
disabled={isLoading}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label={
showNewPassword
? t('auth:login.hidePassword')
: t('auth:login.showPassword')
}
onClick={() => setShowNewPassword(!showNewPassword)}
edge="end"
>
{showNewPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
<TextField
fullWidth
label={t('auth:newPassword.confirmPasswordLabel', 'Confirm new password')}
type={showNewPassword ? 'text' : 'password'}
autoComplete="new-password"
margin="normal"
value={confirmPasswordValue}
onChange={(e) => setConfirmPasswordValue(e.target.value)}
disabled={isLoading}
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
disabled={isLoading || !newPassword || !confirmPasswordValue}
startIcon={isLoading ? <CircularProgress size={20} /> : null}
>
{t('auth:newPassword.submitButton', 'Set password and sign in')}
</Button>
</Box>
) : (
<>
{ssoEnabled && (
<>
<Button
variant="outlined"
fullWidth
startIcon={<Google />}
disabled={isLoading}
onClick={() => authService.signInWithFederated('Google')}
sx={{ mb: 1 }}
>
{t('auth:login.continueWithGoogle')}
</Button>
<Divider sx={{ my: 2 }}>{t('auth:login.orDivider')}</Divider>
</>
)}
<Box component="form" onSubmit={handleSubmit(onSubmit)} sx={{ width: '100%' }}>
<Controller
name="email"
control={control}
render={({ field }) => (
<TextField
{...field}
fullWidth
label={t('auth:login.emailLabel')}
placeholder={t('auth:login.emailPlaceholder')}
type="email"
autoComplete="email username"
autoFocus
margin="normal"
error={!!errors.email}
helperText={errors.email?.message}
disabled={isLoading}
/>
)}
/>
<Controller
name="password"
control={control}
render={({ field }) => (
<TextField
{...field}
fullWidth
label={t('auth:login.passwordLabel')}
placeholder={t('auth:login.passwordPlaceholder')}
type={showPassword ? 'text' : 'password'}
autoComplete="current-password"
margin="normal"
error={!!errors.password}
helperText={errors.password?.message}
disabled={isLoading}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
aria-label={
showPassword
? t('auth:login.hidePassword')
: t('auth:login.showPassword')
}
onClick={() => setShowPassword(!showPassword)}
edge="end"
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
)}
/>
<Controller
name="rememberMe"
control={control}
render={({ field: { value, onChange, ...field } }) => (
<FormControlLabel
control={
<Checkbox
{...field}
checked={value}
onChange={(e) => onChange(e.target.checked)}
disabled={isLoading}
/>
}
label={t('auth:login.rememberMe')}
sx={{ mt: 1 }}
/>
)}
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
disabled={isLoading || !isValid}
startIcon={isLoading ? <CircularProgress size={20} /> : null}
>
{t('auth:login.signInButton')}
</Button>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 2 }}>
<Link
component="button"
variant="body2"
type="button"
onClick={handleForgotPassword}
disabled={isLoading}
sx={{ textDecoration: 'none' }}
>
{t('auth:login.forgotPassword')}
</Link>
<Box sx={{ textAlign: 'right' }}>
<Typography variant="body2" component="span" color="text.secondary">
{t('auth:login.noAccount')}{' '}
</Typography>
<Link
component="button"
variant="body2"
type="button"
onClick={handleSignUp}
disabled={isLoading}
sx={{ textDecoration: 'none' }}
>
{t('auth:login.createAccount')}
</Link>
</Box>
</Box>
</Box>
</>
)}
</Box>
</Paper>
</Box>
</Container>
);
};
|