fix: validate password on paste, change (#4344)

Co-authored-by: Vishal Sharma <makeavish786@gmail.com>
This commit is contained in:
Yunus M 2024-01-09 12:55:24 +05:30 committed by GitHub
parent be6bca3717
commit a47a90b0f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 160 additions and 31 deletions

View File

@ -64,9 +64,13 @@ export const Logout = (): void => {
}, },
}); });
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (window && window.Intercom) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore // @ts-ignore
window.Intercom('shutdown'); window.Intercom('shutdown');
}
history.push(ROUTES.LOGIN); history.push(ROUTES.LOGIN);
}; };

View File

@ -13,6 +13,7 @@ export const Container = styled.div`
&&& { &&& {
display: flex; display: flex;
justify-content: center; justify-content: center;
gap: 16px;
align-items: center; align-items: center;
min-height: 100vh; min-height: 100vh;

View File

@ -0,0 +1,72 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { act } from 'react-dom/test-utils';
import ResetPassword from './index';
jest.mock('api/user/resetPassword', () => ({
__esModule: true,
default: jest.fn(),
}));
jest.useFakeTimers();
describe('ResetPassword Component', () => {
beforeEach(() => {
userEvent.setup();
jest.clearAllMocks();
});
it('renders ResetPassword component correctly', () => {
render(<ResetPassword version="1.0" />);
expect(screen.getByText('Reset Your Password')).toBeInTheDocument();
expect(screen.getByLabelText('Password')).toBeInTheDocument();
// eslint-disable-next-line sonarjs/no-duplicate-string
expect(screen.getByLabelText('Confirm Password')).toBeInTheDocument();
expect(
// eslint-disable-next-line sonarjs/no-duplicate-string
screen.getByRole('button', { name: 'Get Started' }),
).toBeInTheDocument();
});
it('disables the "Get Started" button when password is invalid', async () => {
render(<ResetPassword version="1.0" />);
const passwordInput = screen.getByLabelText('Password');
const confirmPasswordInput = screen.getByLabelText('Confirm Password');
const submitButton = screen.getByRole('button', { name: 'Get Started' });
act(() => {
// Set invalid password
fireEvent.change(passwordInput, { target: { value: 'password' } });
fireEvent.change(confirmPasswordInput, { target: { value: 'password' } });
});
await waitFor(() => {
// Expect the "Get Started" button to be disabled
expect(submitButton).toBeDisabled();
});
});
it('enables the "Get Started" button when password is valid', async () => {
render(<ResetPassword version="1.0" />);
const passwordInput = screen.getByLabelText('Password');
const confirmPasswordInput = screen.getByLabelText('Confirm Password');
const submitButton = screen.getByRole('button', { name: 'Get Started' });
act(() => {
fireEvent.change(passwordInput, { target: { value: 'newPassword' } });
fireEvent.change(confirmPasswordInput, { target: { value: 'newPassword' } });
});
act(() => {
jest.advanceTimersByTime(500);
});
await waitFor(() => {
// Expect the "Get Started" button to be enabled
expect(submitButton).toBeEnabled();
});
});
});

View File

@ -3,6 +3,7 @@ import resetPasswordApi from 'api/user/resetPassword';
import { Logout } from 'api/utils'; import { Logout } from 'api/utils';
import WelcomeLeftContainer from 'components/WelcomeLeftContainer'; import WelcomeLeftContainer from 'components/WelcomeLeftContainer';
import ROUTES from 'constants/routes'; import ROUTES from 'constants/routes';
import useDebouncedFn from 'hooks/useDebouncedFunction';
import { useNotifications } from 'hooks/useNotifications'; import { useNotifications } from 'hooks/useNotifications';
import history from 'lib/history'; import history from 'lib/history';
import { Label } from 'pages/SignUp/styles'; import { Label } from 'pages/SignUp/styles';
@ -20,6 +21,8 @@ function ResetPassword({ version }: ResetPasswordProps): JSX.Element {
const [confirmPasswordError, setConfirmPasswordError] = useState<boolean>( const [confirmPasswordError, setConfirmPasswordError] = useState<boolean>(
false, false,
); );
const [isValidPassword, setIsValidPassword] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const { t } = useTranslation(['common']); const { t } = useTranslation(['common']);
const { search } = useLocation(); const { search } = useLocation();
@ -35,7 +38,7 @@ function ResetPassword({ version }: ResetPasswordProps): JSX.Element {
} }
}, [token]); }, [token]);
const handleSubmit: () => Promise<void> = async () => { const handleFormSubmit: () => Promise<void> = async () => {
try { try {
setLoading(true); setLoading(true);
const { password } = form.getFieldsValue(); const { password } = form.getFieldsValue();
@ -72,38 +75,88 @@ function ResetPassword({ version }: ResetPasswordProps): JSX.Element {
}); });
} }
}; };
const handleValuesChange: (changedValues: FormValues) => void = (
changedValues,
) => {
if ('confirmPassword' in changedValues) {
const { confirmPassword } = changedValues;
const isSamePassword = form.getFieldValue('password') === confirmPassword; const validatePassword = (): boolean => {
setConfirmPasswordError(!isSamePassword); const { password, confirmPassword } = form.getFieldsValue();
if (
password &&
confirmPassword &&
password.trim() &&
confirmPassword.trim() &&
password.length > 0 &&
confirmPassword.length > 0
) {
return password === confirmPassword;
}
return false;
};
const handleValuesChange = useDebouncedFn((): void => {
const { password, confirmPassword } = form.getFieldsValue();
if (!password || !confirmPassword) {
setIsValidPassword(false);
}
if (
password &&
confirmPassword &&
password.trim() &&
confirmPassword.trim()
) {
const isValid = validatePassword();
setIsValidPassword(isValid);
setConfirmPasswordError(!isValid);
}
}, 100);
const handleSubmit = (): void => {
const isValid = validatePassword();
setIsValidPassword(isValid);
if (token) {
handleFormSubmit();
} }
}; };
return ( return (
<WelcomeLeftContainer version={version}> <WelcomeLeftContainer version={version}>
<FormWrapper> <FormWrapper>
<FormContainer <FormContainer form={form} onFinish={handleSubmit}>
form={form}
onValuesChange={handleValuesChange}
onFinish={handleSubmit}
>
<Title level={4}>Reset Your Password</Title> <Title level={4}>Reset Your Password</Title>
<div> <div>
<Label htmlFor="Password">Password</Label> <Label htmlFor="password">Password</Label>
<FormContainer.Item noStyle name="password"> <Form.Item
<Input.Password required id="currentPassword" /> name="password"
</FormContainer.Item> validateTrigger="onBlur"
rules={[{ required: true, message: 'Please enter password!' }]}
>
<Input.Password
tabIndex={0}
onChange={handleValuesChange}
id="password"
data-testid="password"
/>
</Form.Item>
</div> </div>
<div> <div>
<Label htmlFor="ConfirmPassword">Confirm Password</Label> <Label htmlFor="confirmPassword">Confirm Password</Label>
<FormContainer.Item noStyle name="confirmPassword"> <Form.Item
<Input.Password required id="UpdatePassword" /> name="confirmPassword"
</FormContainer.Item> // validateTrigger="onChange"
validateTrigger="onBlur"
rules={[{ required: true, message: 'Please enter confirm password!' }]}
>
<Input.Password
onChange={handleValuesChange}
id="confirmPassword"
data-testid="confirmPassword"
/>
</Form.Item>
{confirmPasswordError && ( {confirmPasswordError && (
<Typography.Paragraph <Typography.Paragraph
@ -113,7 +166,8 @@ function ResetPassword({ version }: ResetPasswordProps): JSX.Element {
marginTop: '0.50rem', marginTop: '0.50rem',
}} }}
> >
Passwords dont match. Please try again The passwords entered do not match. Please double-check and re-enter
your passwords.
</Typography.Paragraph> </Typography.Paragraph>
)} )}
</div> </div>
@ -124,13 +178,7 @@ function ResetPassword({ version }: ResetPasswordProps): JSX.Element {
htmlType="submit" htmlType="submit"
data-attr="signup" data-attr="signup"
loading={loading} loading={loading}
disabled={ disabled={!isValidPassword || loading}
loading ||
!form.getFieldValue('password') ||
!form.getFieldValue('confirmPassword') ||
confirmPasswordError ||
token === null
}
> >
Get Started Get Started
</Button> </Button>

View File

@ -4,8 +4,12 @@ import styled from 'styled-components';
export const FormWrapper = styled(Card)` export const FormWrapper = styled(Card)`
display: flex; display: flex;
justify-content: center; justify-content: center;
max-width: 432px; width: 432px;
flex: 1; flex: 1;
.ant-card-body {
width: 100%;
}
`; `;
export const ButtonContainer = styled.div` export const ButtonContainer = styled.div`