Skip to content

Commit

Permalink
do some code cleaning
Browse files Browse the repository at this point in the history
  • Loading branch information
jnsereko committed Feb 5, 2024
1 parent 622ffe5 commit 3b829aa
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 105 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, ModalBody, ModalFooter, ModalHeader, InlineNotification, Tile, PasswordInput } from '@carbon/react';
import { navigate, showToast, useConfig } from '@openmrs/esm-framework';
import { Button, ModalBody, ModalFooter, ModalHeader, Tile, PasswordInput, Form, Layer } from '@carbon/react';
import { navigate, showSnackbar } from '@openmrs/esm-framework';
import styles from './change-password-modal.scss';
import { performPasswordChange } from './change-password-model.resource';

Expand All @@ -11,8 +11,6 @@ interface ChangePasswordModalProps {

export default function ChangePasswordModal({ close }: ChangePasswordModalProps) {
const { t } = useTranslation();
const config = useConfig();
const [errorMessage, setErrorMessage] = useState('');
const [isSavingPassword, setIsSavingPassword] = useState(false);
const oldPasswordInputRef = useRef<HTMLInputElement>(null);
const newPasswordInputRef = useRef<HTMLInputElement>(null);
Expand All @@ -30,6 +28,58 @@ export default function ChangePasswordModal({ close }: ChangePasswordModalProps)
confirmPassword: '',
});

const handleValidation = useCallback(
(passwordInputValue, passwordInputFieldName) => {
if (passwordInputFieldName === 'newPassword') {
const uppercaseRegExp = /(?=.*?[A-Z])/;
const lowercaseRegExp = /(?=.*?[a-z])/;
const digitsRegExp = /(?=.*?[0-9])/;
const minLengthRegExp = /.{8,}/;
const passwordLength = passwordInputValue.length;
const uppercasePassword = uppercaseRegExp.test(passwordInputValue);
const lowercasePassword = lowercaseRegExp.test(passwordInputValue);
const digitsPassword = digitsRegExp.test(passwordInputValue);
const minLengthPassword = minLengthRegExp.test(passwordInputValue);
let errMsg = '';
if (passwordLength === 0) {
errMsg = t('passwordIsEmpty', 'Password is empty');
} else if (!uppercasePassword) {
errMsg = t('atLeastOneUppercase', 'At least one Uppercase');
} else if (!lowercasePassword) {
errMsg = t('atLeastOneLowercase', 'At least one Lowercase');
} else if (!digitsPassword) {
errMsg = t('atLeastOneDigit', 'At least one digit');
} else if (!minLengthPassword) {
errMsg = t('minimum8Characters', 'Minimum 8 characters');
} else if (passwordInput.oldPassword.length > 0 && passwordInput.newPassword === passwordInput.oldPassword) {
errMsg = t('newPasswordMustNotBeTheSameAsOld', 'New password must not be the same as password');
} else {
errMsg = '';
setIsNewPasswordInvalid(false);
}
setNewPasswordErr(errMsg);
} else if (
passwordInputFieldName === 'confirmPassword' ||
(passwordInputFieldName === 'newPassword' && passwordInput.confirmPassword.length > 0)
) {
if (passwordInput.confirmPassword !== passwordInput.newPassword) {
setConfirmPasswordError(t('confirmPasswordMustBeTheSameAsNew', 'Confirm password must be the same as new'));
} else {
setConfirmPasswordError('');
setIsConfirmPasswordInvalid(false);
}
} else {
if (passwordInput.newPassword.length > 0 && passwordInput.newPassword === passwordInput.oldPassword) {
setOldPasswordErr(t('oldPasswordMustNotBeTheSameAsNew', 'Old password must not be the same as new'));
} else {
setOldPasswordErr('');
setIsOldPasswordInvalid(false);
}
}
},
[passwordInput.confirmPassword, passwordInput.newPassword, passwordInput.oldPassword, t],
);

useEffect(() => {
if (passwordInput.oldPassword !== '') {
handleValidation(passwordInput.oldPassword, 'oldPassword');
Expand All @@ -40,7 +90,7 @@ export default function ChangePasswordModal({ close }: ChangePasswordModalProps)
if (passwordInput.confirmPassword !== '') {
handleValidation(passwordInput.confirmPassword, 'confirmPassword');
}
}, [passwordInput]);
}, [handleValidation, passwordInput]);

const handlePasswordChange = (event) => {
const passwordInputValue = event.target.value.trim();
Expand All @@ -49,77 +99,30 @@ export default function ChangePasswordModal({ close }: ChangePasswordModalProps)
setPasswordInput(NewPasswordInput);
};

const handleValidation = (passwordInputValue, passwordInputFieldName) => {
if (passwordInputFieldName === 'newPassword') {
const uppercaseRegExp = /(?=.*?[A-Z])/;
const lowercaseRegExp = /(?=.*?[a-z])/;
const digitsRegExp = /(?=.*?[0-9])/;
const minLengthRegExp = /.{8,}/;
const passwordLength = passwordInputValue.length;
const uppercasePassword = uppercaseRegExp.test(passwordInputValue);
const lowercasePassword = lowercaseRegExp.test(passwordInputValue);
const digitsPassword = digitsRegExp.test(passwordInputValue);
const minLengthPassword = minLengthRegExp.test(passwordInputValue);
let errMsg = '';
if (passwordLength === 0) {
errMsg = t('passwordIsEmpty', 'Password is empty');
} else if (!uppercasePassword) {
errMsg = t('atLeastOneUppercase', 'At least one Uppercase');
} else if (!lowercasePassword) {
errMsg = t('atLeastOneLowercase', 'At least one Lowercase');
} else if (!digitsPassword) {
errMsg = t('atLeastOneDigit', 'At least one digit');
} else if (!minLengthPassword) {
errMsg = t('minimum8Characters', 'Minimum 8 characters');
} else if (passwordInput.oldPassword.length > 0 && passwordInput.newPassword === passwordInput.oldPassword) {
errMsg = t('newPasswordMustNotBeTheSameAsOld', 'New password must not be the same as password');
} else {
errMsg = '';
setIsNewPasswordInvalid(false);
}
setNewPasswordErr(errMsg);
} else if (
passwordInputFieldName === 'confirmPassword' ||
(passwordInputFieldName === 'newPassword' && passwordInput.confirmPassword.length > 0)
) {
if (passwordInput.confirmPassword !== passwordInput.newPassword) {
setConfirmPasswordError(t('confirmPasswordMustBeTheSameAsNew', 'Confirm password must be the same as new'));
} else {
setConfirmPasswordError('');
setIsConfirmPasswordInvalid(false);
}
} else {
if (passwordInput.newPassword.length > 0 && passwordInput.newPassword === passwordInput.oldPassword) {
setOldPasswordErr(t('oldPasswordMustNotBeTheSameAsNew', 'Old password must not be the same as new'));
} else {
setOldPasswordErr('');
setIsOldPasswordInvalid(false);
}
}
};

const handleSubmit = useCallback(
async (evt: React.FormEvent<HTMLFormElement>) => {
evt.preventDefault();
evt.stopPropagation();

try {
setIsSavingPassword(true);
await performPasswordChange(passwordInput.oldPassword, passwordInput.confirmPassword).then(() => {
setIsSavingPassword(true);
performPasswordChange(passwordInput.oldPassword, passwordInput.confirmPassword)
.then(() => {
close();
navigate({ to: `\${openmrsSpaBase}/logout` });
showToast({
title: t('userPassword', 'User password'),
description: t('userPasswordUpdated', 'User password updated successfully'),
showSnackbar({
isLowContrast: true,
kind: 'success',
subtitle: t('userPasswordUpdated', 'User password updated successfully'),
title: t('userPassword', 'User password'),
});
})
.catch((error) => {
setIsSavingPassword(false);
showSnackbar({
title: t('invalidPasswordCredentials', 'Invalid password provided'),
kind: 'error',
isLowContrast: false,
subtitle: error?.message,
});
});
} catch (error) {
setIsSavingPassword(false);
setErrorMessage(`${t('invalidPasswordCredentials', 'Invalid password provided')}: ${error.message}`);
}

return false;
},
[close, passwordInput.confirmPassword, passwordInput.oldPassword, t],
);
Expand All @@ -128,23 +131,10 @@ export default function ChangePasswordModal({ close }: ChangePasswordModalProps)
<>
<ModalHeader closeModal={close} title={t('changePassword', 'Change Password')} />
<ModalBody>
<div className={styles['input-group']}>
{errorMessage && (
<InlineNotification
className={styles.errorMessage}
kind="error"
/**
* This comment tells i18n to still keep the following translation keys (used as value for: errorMessage):
* t('invalidPasswordCredentials')
*/
subtitle={t(errorMessage)}
title={t('error', 'Error')}
onClick={() => setErrorMessage('')}
/>
)}
<Tile>
<form onSubmit={handleSubmit} ref={formRef}>
<div className={styles['input-group']}>
<Tile>
<Form onSubmit={handleSubmit} ref={formRef}>
<div className={styles['input-group']}>
<Layer>
<PasswordInput
id="oldPassword"
invalid={oldPasswordError.length > 0}
Expand All @@ -157,6 +147,8 @@ export default function ChangePasswordModal({ close }: ChangePasswordModalProps)
required
showPasswordLabel="Show old password"
/>
</Layer>
<Layer>
<PasswordInput
id="newPassword"
invalid={newPasswordError.length > 0}
Expand All @@ -169,6 +161,8 @@ export default function ChangePasswordModal({ close }: ChangePasswordModalProps)
required
showPasswordLabel="Show new password"
/>
</Layer>
<Layer>
<PasswordInput
id="confirmPassword"
invalid={confirmPasswordError.length > 0}
Expand All @@ -181,10 +175,10 @@ export default function ChangePasswordModal({ close }: ChangePasswordModalProps)
required
showPasswordLabel="Show confirm password"
/>
</div>
</form>
</Tile>
</div>
</Layer>
</div>
</Form>
</Tile>
</ModalBody>
<ModalFooter>
<Button kind="secondary" onClick={close}>
Expand All @@ -195,7 +189,7 @@ export default function ChangePasswordModal({ close }: ChangePasswordModalProps)
onClick={handleSubmit}
disabled={isSavingPassword || isNewPasswordInvalid || isConfirmPasswordInvalid || isOldPasswordInvalid}
>
{t('apply', 'Apply')}
{t('updatePassword', 'Update Password')}
</Button>
</ModalFooter>
</>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,3 @@
background-color: white;
}
}

.errorMessage {
position: absolute;
top: 0;
margin-top: 0.25rem;
z-index: 1;
width: 50%;
left: 25%;
}
2 changes: 1 addition & 1 deletion packages/esm-system-admin-app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export const changePasswordButton = getAsyncLifecycle(
options,
);

export const ChangePasswordModal = getAsyncLifecycle(
export const changePasswordModal = getAsyncLifecycle(
() => import('./change-password-modal/change-password-modal.component'),
options,
);
2 changes: 1 addition & 1 deletion packages/esm-system-admin-app/src/routes.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
},
{
"name": "change-password-modal",
"component": "ChangePasswordModal",
"component": "changePasswordModal",
"online": true,
"offline": true
}
Expand Down
3 changes: 1 addition & 2 deletions packages/esm-system-admin-app/translations/ar.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
"apply": "يتقدم",
"atLeastOneDigit": "رقم واحد على الأقل",
"atLeastOneLowercase": "حرف صغير واحد على الأقل",
"atLeastOneUppercase": "حرف كبير واحد على الأقل",
Expand All @@ -8,7 +7,6 @@
"config": "الإعدادات",
"confirmPassword": "تأكيد كلمة المرور",
"confirmPasswordMustBeTheSameAsNew": "تأكيد كلمة المرور يجب أن تكون هي نفسها الجديدة",
"error": "خطأ",
"invalidPasswordCredentials": "",
"legacyAdmin": "إدارة النظام القديم",
"minimum8Characters": "الحد الأدنى 8 أحرف",
Expand All @@ -18,6 +16,7 @@
"oldPasswordMustNotBeTheSameAsNew": "يجب ألا تكون كلمة المرور القديمة هي نفس كلمة المرور الجديدة",
"passwordIsEmpty": "كلمة المرور فارغة",
"systemAdmin": "إدارة النظام",
"updatePassword": "تطوير كلمة السر",
"userPassword": "كلمة مرور المستخدم",
"userPasswordUpdated": "تم تحديث كلمة مرور المستخدم بنجاح"
}
3 changes: 1 addition & 2 deletions packages/esm-system-admin-app/translations/en.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
"apply": "Apply",
"atLeastOneDigit": "At least one digit",
"atLeastOneLowercase": "At least one Lowercase",
"atLeastOneUppercase": "At least one Uppercase",
Expand All @@ -8,7 +7,6 @@
"config": "Configurations",
"confirmPassword": "Confirm Password",
"confirmPasswordMustBeTheSameAsNew": "Confirm password must be the same as new",
"error": "Error",
"invalidPasswordCredentials": "",
"legacyAdmin": "Legacy Admin",
"minimum8Characters": "Minimum 8 characters",
Expand All @@ -18,6 +16,7 @@
"oldPasswordMustNotBeTheSameAsNew": "Old password must not be the same as new",
"passwordIsEmpty": "Password is empty",
"systemAdmin": "System Administration",
"updatePassword": "Update Password",
"userPassword": "User password",
"userPasswordUpdated": "User password updated successfully"
}

0 comments on commit 3b829aa

Please sign in to comment.