snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,447 @@
import { VisuallyHidden } from '@react-aria/visually-hidden';
import { UserStatus } from '@rocket.chat/core-typings';
import { css } from '@rocket.chat/css-in-js';
import type { SelectOption } from '@rocket.chat/fuselage';
import { Box, Button, Divider, Icon, InputBox, Margins } from '@rocket.chat/fuselage';
import {
Field,
FieldGroup,
FieldLabel,
FieldRow,
FieldError,
FieldHint,
TextInput,
TextAreaInput,
Select,
} from '@rocket.chat/fuselage-forms';
import { validateEmail } from '@rocket.chat/tools';
import { CustomFieldsForm } from '@rocket.chat/ui-client';
import {
useAccountsCustomFields,
useToastMessageDispatch,
useTranslation,
useEndpoint,
useUser,
useLayout,
useSetting,
} from '@rocket.chat/ui-contexts';
import { useMutation } from '@tanstack/react-query';
import type { AllHTMLAttributes, ChangeEvent } from 'react';
import { useCallback, useEffect, useMemo } from 'react';
import { Controller, useFormContext } from 'react-hook-form';
import type { AccountProfileFormValues } from './getProfileInitialValues';
import { useAccountProfileSettings } from './useAccountProfileSettings';
import { getUserEmailAddress } from '../../../../lib/getUserEmailAddress';
import UserAutoCompleteMultiple from '../../../components/UserAutoCompleteMultiple';
import UserStatusMenu from '../../../components/UserStatusMenu';
import UserAvatarEditor from '../../../components/avatar/UserAvatarEditor';
import { useUpdateAvatar } from '../../../hooks/useUpdateAvatar';
import { USER_STATUS_TEXT_MAX_LENGTH, BIO_TEXT_MAX_LENGTH } from '../../../lib/constants';
import { STATUS_DURATION_OPTIONS, validateStatusExpiration } from '../../../lib/statusDurations';
const AccountProfileForm = (props: AllHTMLAttributes<HTMLFormElement>) => {
const t = useTranslation();
const user = useUser();
const dispatchToastMessage = useToastMessageDispatch();
const { isMobile } = useLayout();
const setPreferences = useEndpoint('POST', '/v1/users.setPreferences');
const statusVisibilityEnabled = useSetting('Accounts_StatusVisibility_Enabled', false);
const checkUsernameAvailability = useEndpoint('GET', '/v1/users.checkUsernameAvailability');
const sendConfirmationEmail = useEndpoint('POST', '/v1/users.sendConfirmationEmail');
const customFieldsMetadata = useAccountsCustomFields();
const {
allowRealNameChange,
allowUserStatusMessageChange,
allowEmailChange,
allowUserAvatarChange,
canChangeUsername,
requireName,
namesRegex,
} = useAccountProfileSettings();
const {
control,
watch,
handleSubmit,
reset,
setValue,
formState: { errors, dirtyFields },
} = useFormContext<AccountProfileFormValues>();
const { email, avatar, username, name: userFullName, statusDuration, statusType, statusText } = watch();
const isExpirationDisabled = statusType === UserStatus.ONLINE && !statusText?.trim();
useEffect(() => {
if (isExpirationDisabled) {
setValue('statusDuration', '', { shouldValidate: true });
}
}, [isExpirationDisabled, setValue]);
const statusDurationOptions: SelectOption[] = useMemo(
() => STATUS_DURATION_OPTIONS.map(({ value, labelKey }) => [value, t(labelKey)]),
[t],
);
const previousEmail = user ? getUserEmailAddress(user) : '';
const previousUsername = user?.username || '';
const isUserVerified = user?.emails?.[0]?.verified ?? false;
const mutateConfirmationEmail = useMutation({
mutationFn: sendConfirmationEmail,
onSuccess: () => dispatchToastMessage({ type: 'success', message: t('Verification_email_sent') }),
onError: (error) => dispatchToastMessage({ type: 'error', message: error }),
});
const handleSendConfirmationEmail = useCallback(async () => {
if (email !== previousEmail) {
return;
}
mutateConfirmationEmail.mutateAsync({ email });
}, [email, previousEmail, mutateConfirmationEmail]);
const validateUsername = async (username: string): Promise<string | undefined> => {
if (!username) {
return;
}
if (username === previousUsername) {
return;
}
if (!namesRegex.test(username)) {
return t('error-invalid-username');
}
const { result: isAvailable } = await checkUsernameAvailability({ username });
if (!isAvailable) {
return t('Username_already_exist');
}
};
const updateOwnBasicInfo = useEndpoint('POST', '/v1/users.updateOwnBasicInfo');
const setUserStatus = useEndpoint('POST', '/v1/users.setStatus');
const updateAvatar = useUpdateAvatar(avatar, user?._id || '');
const handleSave = async (values: AccountProfileFormValues) => {
const {
email,
name,
username,
statusType,
statusText,
statusDuration,
statusCustomDate,
statusCustomTime,
nickname,
bio,
customFields,
statusVisibilityDenied,
} = values;
const expiresAt = STATUS_DURATION_OPTIONS.find((o) => o.value === statusDuration)?.getExpiresAt?.({
now: new Date(),
customDate: statusCustomDate,
customTime: statusCustomTime,
});
const statusDirty =
dirtyFields.statusText ||
dirtyFields.statusType ||
dirtyFields.statusDuration ||
dirtyFields.statusCustomDate ||
dirtyFields.statusCustomTime;
try {
await updateOwnBasicInfo({
data: {
name,
...(user ? getUserEmailAddress(user) !== email && { email } : {}),
username,
nickname,
bio,
},
customFields,
});
if (dirtyFields.statusVisibilityDenied) {
await setPreferences({ data: { statusVisibilityDenied } });
}
if (statusDirty) {
await setUserStatus({
status: statusType,
...(allowUserStatusMessageChange && { message: statusText }),
...(allowUserStatusMessageChange && expiresAt && { expiresAt: expiresAt.toISOString() }),
});
}
await updateAvatar();
dispatchToastMessage({ type: 'success', message: t('Profile_saved_successfully') });
reset(values);
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
};
return (
<Box {...props} is='form' autoComplete='off' onSubmit={handleSubmit(handleSave)}>
<FieldGroup>
<VisuallyHidden>
<legend>{t('Profile_details')}</legend>
</VisuallyHidden>
<Field>
<Controller
control={control}
name='avatar'
render={({ field: { onChange } }) => (
<UserAvatarEditor
etag={user?.avatarETag}
currentUsername={user?.username}
name={userFullName}
username={username}
setAvatarObj={onChange}
disabled={!allowUserAvatarChange}
/>
)}
/>
</Field>
<Box display='flex' flexDirection={isMobile ? 'column' : 'row'} style={{ gap: '16px' }}>
<Field flexShrink={1}>
<FieldLabel required={requireName}>{t('Name')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='name'
rules={{ required: requireName && t('Required_field', { field: t('Name') }) }}
render={({ field }) => (
<TextInput {...field} disabled={!allowRealNameChange} error={errors.name?.message} aria-required={true} />
)}
/>
</FieldRow>
{errors.name && <FieldError>{errors.name.message}</FieldError>}
{!allowRealNameChange && <FieldHint>{t('RealName_Change_Disabled')}</FieldHint>}
</Field>
<Field flexShrink={1}>
<FieldLabel required>{t('Username')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='username'
rules={{
required: t('Required_field', { field: t('Username') }),
validate: validateUsername,
}}
render={({ field }) => (
<TextInput
{...field}
aria-required={true}
disabled={!canChangeUsername}
endAddon={<Icon name='at' size='x20' />}
error={errors.username?.message}
/>
)}
/>
</FieldRow>
{errors.username && <FieldError>{errors.username.message}</FieldError>}
{!canChangeUsername && <FieldHint>{t('Username_Change_Disabled')}</FieldHint>}
</Field>
</Box>
<Divider marginBlockStart={24} marginBlockEnd={0} />
<Field>
<FieldLabel>{t('Status')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='statusText'
rules={{
maxLength: {
value: USER_STATUS_TEXT_MAX_LENGTH,
message: t('Max_length_is', { limit: USER_STATUS_TEXT_MAX_LENGTH }),
},
}}
render={({ field }) => (
<TextInput
{...field}
placeholder={t('StatusMessage_Placeholder')}
disabled={!allowUserStatusMessageChange}
flexGrow={1}
error={errors.statusText?.message}
startAddon={
<Controller
control={control}
name='statusType'
render={({ field: { value, onChange } }) => <UserStatusMenu onChange={onChange} initialStatus={value} />}
/>
}
/>
)}
/>
</FieldRow>
{errors.statusText && <FieldError>{errors.statusText.message}</FieldError>}
{!allowUserStatusMessageChange && <FieldHint>{t('StatusMessage_Change_Disabled')}</FieldHint>}
{allowUserStatusMessageChange && <FieldHint>{t('Status_you_can_use_emoji')}</FieldHint>}
</Field>
<Field>
<FieldLabel>{t('Status_clear_after')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='statusDuration'
rules={{
deps: ['statusCustomDate', 'statusCustomTime'],
validate: (value, { statusCustomDate, statusCustomTime }) =>
validateStatusExpiration(value, { statusCustomDate, statusCustomTime }, t),
}}
render={({ field: { value, onChange } }) => (
<Select
value={value}
options={statusDurationOptions}
disabled={!allowUserStatusMessageChange || isExpirationDisabled}
onChange={(next) => onChange(String(next))}
/>
)}
/>
</FieldRow>
{statusDuration === 'custom' && (
<Box display='flex' marginInline='neg-x4' marginBlockStart={8}>
<Margins inline={4}>
<Controller
control={control}
name='statusCustomDate'
render={({ field: { value, onChange } }) => (
<InputBox
aria-label={t('Status_expiration_date')}
type='date'
disabled={!allowUserStatusMessageChange}
flexGrow={1}
value={value}
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange(e.currentTarget.value)}
min={new Date().toLocaleDateString('en-CA')}
/>
)}
/>
<Controller
control={control}
name='statusCustomTime'
render={({ field: { value, onChange } }) => (
<InputBox
aria-label={t('Status_expiration_time')}
type='time'
disabled={!allowUserStatusMessageChange}
flexGrow={1}
value={value}
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange(e.currentTarget.value)}
/>
)}
/>
</Margins>
</Box>
)}
{errors.statusDuration && <FieldError>{errors.statusDuration.message}</FieldError>}
<FieldHint>{t('Status_new_status_warning')}</FieldHint>
</Field>
{statusVisibilityEnabled && (
<Field>
<FieldLabel>{t('Accounts_StatusVisibility_HideStatusFromUsers')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='statusVisibilityDenied'
render={({ field: { onChange, value } }) => (
<UserAutoCompleteMultiple
value={value}
onChange={onChange}
exceptions={user?.username ? [user.username] : undefined}
placeholder={t('Select_users')}
/>
)}
/>
</FieldRow>
<FieldHint>{t('Accounts_StatusVisibility_HideFromUsers_Description')}</FieldHint>
</Field>
)}
<Divider marginBlockStart={24} marginBlockEnd={0} />
<Field>
<FieldLabel>{t('Nickname')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='nickname'
render={({ field }) => <TextInput {...field} flexGrow={1} endAddon={<Icon name='edit' size='x20' alignSelf='center' />} />}
/>
</FieldRow>
</Field>
<Field>
<FieldLabel>{t('Bio')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='bio'
rules={{
maxLength: { value: BIO_TEXT_MAX_LENGTH, message: t('Max_length_is', { limit: BIO_TEXT_MAX_LENGTH }) },
}}
render={({ field }) => (
<TextAreaInput
{...field}
rows={3}
flexGrow={1}
error={errors.bio?.message}
endAddon={<Icon name='edit' size='x20' alignSelf='center' />}
/>
)}
/>
</FieldRow>
{errors.bio && <FieldError>{errors.bio.message}</FieldError>}
</Field>
<Field>
<FieldLabel required>{t('Email')}</FieldLabel>
<FieldRow
flexDirection={isMobile ? 'column' : 'row'}
alignItems='stretch'
className={css`
gap: 8px;
`}
>
<Controller
control={control}
name='email'
rules={{
required: t('Required_field', { field: t('Email') }),
validate: {
validateEmail: (email) => (validateEmail(email) ? undefined : t('error-invalid-email-address')),
},
}}
render={({ field }) => (
<TextInput
{...field}
aria-required={true}
flexGrow={1}
disabled={!allowEmailChange}
endAddon={<Icon name={isUserVerified ? 'circle-check' : 'mail'} size='x20' />}
error={errors.email?.message}
/>
)}
/>
{!isUserVerified && (
<Button disabled={email !== previousEmail} onClick={handleSendConfirmationEmail}>
{t('Resend_verification_email')}
</Button>
)}
</FieldRow>
{errors.email && <FieldError>{errors.email.message}</FieldError>}
{!allowEmailChange && <FieldHint>{t('Email_Change_Disabled')}</FieldHint>}
</Field>
{customFieldsMetadata && <CustomFieldsForm formName='customFields' formControl={control} metadata={customFieldsMetadata} />}
</FieldGroup>
</Box>
);
};
export default AccountProfileForm;

View File

@@ -0,0 +1,154 @@
import { ButtonGroup, Button, Box } from '@rocket.chat/fuselage';
import { SHA256 } from '@rocket.chat/sha256';
import { Page, PageFooter, PageHeader, PageScrollableContentWithShadow } from '@rocket.chat/ui-client';
import type { TranslationKey } from '@rocket.chat/ui-contexts';
import {
useSetModal,
useToastMessageDispatch,
useUser,
useLogout,
useEndpoint,
useTranslation,
useSetting,
useLayout,
} from '@rocket.chat/ui-contexts';
import { useId, useState, useCallback } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import AccountProfileForm from './AccountProfileForm';
import ActionConfirmModal from './ActionConfirmModal';
import { getProfileInitialValues } from './getProfileInitialValues';
import ConfirmOwnerChangeModal from '../../../components/ConfirmOwnerChangeModal';
import { useAllowPasswordChange } from '../security/useAllowPasswordChange';
// TODO: enforce useMutation
const AccountProfilePage = () => {
const t = useTranslation();
const user = useUser();
const dispatchToastMessage = useToastMessageDispatch();
const { isMobile } = useLayout();
const setModal = useSetModal();
const logout = useLogout();
const [loggingOut, setLoggingOut] = useState(false);
const erasureType = useSetting('Message_ErasureType');
const allowDeleteOwnAccount = useSetting('Accounts_AllowDeleteOwnAccount');
const { hasLocalPassword } = useAllowPasswordChange();
const methods = useForm({
defaultValues: getProfileInitialValues(user),
reValidateMode: 'onBlur',
});
const {
reset,
formState: { isDirty, isSubmitting },
} = methods;
const logoutOtherClients = useEndpoint('POST', '/v1/users.logoutOtherClients');
const deleteOwnAccount = useEndpoint('POST', '/v1/users.deleteOwnAccount');
const handleLogoutOtherLocations = useCallback(async () => {
setLoggingOut(true);
try {
await logoutOtherClients();
dispatchToastMessage({
type: 'success',
message: t('Logged_out_of_other_clients_successfully'),
});
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
setLoggingOut(false);
}, [logoutOtherClients, dispatchToastMessage, t]);
const handleConfirmOwnerChange = useCallback(
(passwordOrUsername: string, shouldChangeOwner: string[], shouldBeRemoved: string[]) => {
const handleConfirm = async (): Promise<void> => {
try {
await deleteOwnAccount({ password: SHA256(passwordOrUsername), confirmRelinquish: true });
dispatchToastMessage({ type: 'success', message: t('User_has_been_deleted') });
setModal(null);
logout();
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
};
return setModal(
<ConfirmOwnerChangeModal
onConfirm={handleConfirm}
onCancel={() => setModal(null)}
contentTitle={t(`Delete_User_Warning_${erasureType}` as TranslationKey)}
confirmText={t('Delete')}
shouldChangeOwner={shouldChangeOwner}
shouldBeRemoved={shouldBeRemoved}
/>,
);
},
[erasureType, setModal, t, deleteOwnAccount, dispatchToastMessage, logout],
);
const handleDeleteOwnAccount = useCallback(async () => {
const handleConfirm = async (passwordOrUsername: string): Promise<void> => {
try {
await deleteOwnAccount({ password: SHA256(passwordOrUsername) });
dispatchToastMessage({ type: 'success', message: t('User_has_been_deleted') });
setModal(null);
} catch (error: any) {
if (error.error === 'user-last-owner') {
const { shouldChangeOwner, shouldBeRemoved } = error.details;
return handleConfirmOwnerChange(passwordOrUsername, shouldChangeOwner, shouldBeRemoved);
}
if (error.errorType === 'error-invalid-password') {
throw error;
}
dispatchToastMessage({ type: 'error', message: error });
}
};
return setModal(<ActionConfirmModal onConfirm={handleConfirm} onCancel={() => setModal(null)} isPassword={hasLocalPassword} />);
}, [dispatchToastMessage, hasLocalPassword, setModal, handleConfirmOwnerChange, deleteOwnAccount, t]);
const profileFormId = useId();
return (
<Page>
<PageHeader title={t('Profile')} />
<PageScrollableContentWithShadow>
<Box maxWidth='600px' width='full' alignSelf='center'>
<FormProvider {...methods}>
<AccountProfileForm id={profileFormId} />
</FormProvider>
<Box marginBlock={12}>
<ButtonGroup stretch vertical={isMobile}>
<Button onClick={handleLogoutOtherLocations} flexGrow={0} loading={loggingOut}>
{t('Logout_Others')}
</Button>
{allowDeleteOwnAccount && (
<Button icon='trash' danger onClick={handleDeleteOwnAccount}>
{t('Delete_my_account')}
</Button>
)}
</ButtonGroup>
</Box>
</Box>
</PageScrollableContentWithShadow>
<PageFooter isDirty={isDirty}>
<ButtonGroup>
<Button disabled={!isDirty} onClick={() => reset(getProfileInitialValues(user))}>
{t('Cancel')}
</Button>
<Button form={profileFormId} primary disabled={!isDirty || loggingOut} loading={isSubmitting} type='submit'>
{t('Save_changes')}
</Button>
</ButtonGroup>
</PageFooter>
</Page>
);
};
export default AccountProfilePage;

View File

@@ -0,0 +1,16 @@
import { useSetting } from '@rocket.chat/ui-contexts';
import AccountProfilePage from './AccountProfilePage';
import NotAuthorizedPage from '../../notAuthorized/NotAuthorizedPage';
const AccountProfileRoute = () => {
const canViewProfile = useSetting('Accounts_AllowUserProfileChange');
if (!canViewProfile) {
return <NotAuthorizedPage />;
}
return <AccountProfilePage />;
};
export default AccountProfileRoute;

View File

@@ -0,0 +1,91 @@
import { Box, PasswordInput, TextInput, FieldGroup, Field, FieldRow, FieldError, FieldLabel } from '@rocket.chat/fuselage';
import { GenericModal } from '@rocket.chat/ui-client';
import { useId } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
export type ActionConfirmModalProps = {
isPassword: boolean;
onConfirm: (input: string) => Promise<void>;
onCancel: () => void;
};
const ActionConfirmModal = ({ isPassword, onConfirm, onCancel }: ActionConfirmModalProps) => {
const { t } = useTranslation();
const credentialFieldId = useId();
const credentialFieldError = `${credentialFieldId}-error`;
const {
control,
handleSubmit,
setError,
formState: { errors },
} = useForm({
defaultValues: { credential: '' },
mode: 'onBlur',
});
const handleSave = async ({ credential }: { credential: string }) => {
try {
await onConfirm(credential);
} catch (error: any) {
if (error.errorType === 'error-invalid-password') {
setError('credential', { message: t('Invalid_password') });
}
}
};
return (
<GenericModal
wrapperFunction={(props) => <Box is='form' onSubmit={handleSubmit(handleSave)} {...props} />}
onCancel={onCancel}
variant='danger'
title={t('Delete_account?')}
confirmText={t('Delete_account')}
>
<FieldGroup width='full'>
<Field>
<FieldLabel required htmlFor={credentialFieldId}>
{isPassword ? t('Enter_your_password_to_delete_your_account') : t('Enter_your_username_to_delete_your_account')}
</FieldLabel>
<FieldRow>
<Controller
name='credential'
control={control}
rules={{ required: t('error-the-field-is-required', { field: isPassword ? t('Password') : t('Username') }) }}
render={({ field }) =>
isPassword ? (
<PasswordInput
{...field}
id={credentialFieldId}
error={errors.credential?.message}
aria-invalid={errors.credential ? 'true' : 'false'}
aria-describedby={errors.credential ? credentialFieldError : undefined}
aria-required='true'
/>
) : (
<TextInput
{...field}
id={credentialFieldId}
placeholder={t('Username')}
error={errors.credential?.message}
aria-invalid={errors.credential ? 'true' : 'false'}
aria-describedby={errors.credential ? credentialFieldError : undefined}
aria-required='true'
/>
)
}
/>
</FieldRow>
{errors.credential && (
<FieldError role='alert' id={credentialFieldError}>
{errors.credential.message}
</FieldError>
)}
</Field>
</FieldGroup>
</GenericModal>
);
};
export default ActionConfirmModal;

View File

@@ -0,0 +1,32 @@
import type { AvatarObject, IUser } from '@rocket.chat/core-typings';
import { getUserEmailAddress } from '../../../../lib/getUserEmailAddress';
import type { UserStatusInitialValues } from '../../../lib/getUserInitialStatus';
import { getUserStatusInitialValues } from '../../../lib/getUserInitialStatus';
export type AccountProfileFormValues = {
email: string;
name: string;
username: string;
avatar: AvatarObject;
url: string;
bio: string;
customFields: Record<string, string>;
nickname: string;
statusVisibilityDenied: string[];
} & UserStatusInitialValues;
export const getProfileInitialValues = (user: IUser | null): AccountProfileFormValues => {
return {
email: user ? getUserEmailAddress(user) || '' : '',
name: user?.name ?? '',
username: user?.username ?? '',
avatar: '' as AvatarObject,
url: '',
bio: user?.bio ?? '',
customFields: user?.customFields ?? {},
nickname: user?.nickname ?? '',
statusVisibilityDenied: user?.settings?.preferences?.statusVisibilityDenied ?? [],
...getUserStatusInitialValues(user),
};
};

View File

@@ -0,0 +1,25 @@
import { useSetting } from '@rocket.chat/ui-contexts';
import { useMemo } from 'react';
export const useAccountProfileSettings = () => {
const allowRealNameChange = useSetting('Accounts_AllowRealNameChange', true);
const allowUserStatusMessageChange = useSetting('Accounts_AllowUserStatusMessageChange', true);
const canChangeUsername = useSetting('Accounts_AllowUsernameChange', true);
const allowEmailChange = useSetting('Accounts_AllowEmailChange', true);
const allowUserAvatarChange = useSetting('Accounts_AllowUserAvatarChange', true);
const requireName = useSetting('Accounts_RequireNameForSignUp', true);
const namesRegexSetting = useSetting('UTF8_User_Names_Validation', '[0-9a-zA-Z-_.]+');
const namesRegex = useMemo(() => new RegExp(`^${namesRegexSetting}$`), [namesRegexSetting]);
return {
allowRealNameChange,
allowUserStatusMessageChange,
allowEmailChange,
allowUserAvatarChange,
canChangeUsername,
requireName,
namesRegex,
};
};