index
int64 0
0
| repo_id
stringlengths 16
181
| file_path
stringlengths 28
270
| content
stringlengths 1
11.6M
| __index_level_0__
int64 0
10k
|
|---|---|---|---|---|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layout/PrivateMainSettingsArea.tsx
|
import { Children, ReactNode, cloneElement, isValidElement, useEffect, useRef } from 'react';
import { useLocation } from 'react-router';
import clsx from '@proton/utils/clsx';
import noop from '@proton/utils/noop';
import createScrollIntoView from '../../helpers/createScrollIntoView';
import useAppTitle from '../../hooks/useAppTitle';
import { SettingsPageTitle, SettingsParagraph } from '../account';
import ErrorBoundary from '../app/ErrorBoundary';
import PrivateMainArea from './PrivateMainArea';
import SubSettingsSection from './SubSettingsSection';
import { getIsSubsectionAvailable } from './helper';
import { SettingsAreaConfig } from './interface';
import useActiveSection from './useActiveSection';
interface PrivateMainSettingsAreaBaseProps {
breadcrumbs?: ReactNode;
title: string;
noTitle?: boolean;
description?: ReactNode;
setActiveSection?: (section: string) => void;
children?: ReactNode;
}
export const PrivateMainSettingsAreaBase = ({
breadcrumbs,
title,
noTitle,
description,
setActiveSection,
children,
}: PrivateMainSettingsAreaBaseProps) => {
const location = useLocation();
const mainAreaRef = useRef<HTMLDivElement>(null);
const useIntersectionSection = useRef(false);
useAppTitle(title);
useEffect(() => {
if (mainAreaRef.current) {
mainAreaRef.current.scrollTop = 0;
}
}, [location.pathname]);
useEffect(() => {
const { hash } = location;
if (!hash) {
useIntersectionSection.current = true;
return;
}
if (!mainAreaRef.current) {
return;
}
const mainArea = mainAreaRef.current;
let el: Element | null | undefined;
try {
el = mainArea.querySelector(hash);
} catch (e) {}
if (!el) {
return;
}
useIntersectionSection.current = false;
setActiveSection?.(hash.slice(1));
const abortScroll = createScrollIntoView(el, mainArea, true);
let removeListeners: () => void;
const abort = () => {
useIntersectionSection.current = true;
abortScroll();
removeListeners?.();
};
const options = {
passive: true,
capture: true,
};
// Abort on any user interaction such as scrolling, touching, or keyboard interaction
window.addEventListener('wheel', abort, options);
window.addEventListener('keydown', abort, options);
window.addEventListener('mousedown', abort, options);
window.addEventListener('touchstart', abort, options);
// Automatically abort after some time where it's assumed to have successfully scrolled into place.
const timeoutId = window.setTimeout(abort, 15000);
removeListeners = () => {
window.removeEventListener('wheel', abort, options);
window.removeEventListener('keydown', abort, options);
window.removeEventListener('mousedown', abort, options);
window.removeEventListener('touchstart', abort, options);
window.clearTimeout(timeoutId);
};
return () => {
abort();
};
// Listen to location instead of location.hash since it's possible to click the same #section multiple times and end up with a new entry in history
}, [location]);
// Don't always use the observer section observed value since it can not go to sections that are at the bottom or too small.
// In those cases it can be overridden by clicking on a specific section
const sectionObserver = useActiveSection(
useIntersectionSection.current && setActiveSection ? setActiveSection : noop
);
const wrappedSections = Children.toArray(children).map((child) => {
if (!isValidElement<{ observer: IntersectionObserver; className: string }>(child)) {
return null;
}
return cloneElement(child, {
observer: sectionObserver,
});
});
return (
<PrivateMainArea ref={mainAreaRef}>
<div className="container-section-sticky">
{breadcrumbs && <div className="mt-6 md:mt-0">{breadcrumbs}</div>}
{!noTitle && (
<SettingsPageTitle className={clsx('mt-14', description ? 'mb-5' : 'mb-14')}>
{title}
</SettingsPageTitle>
)}
{description && <SettingsParagraph className="mb-6">{description}</SettingsParagraph>}
<ErrorBoundary>{wrappedSections}</ErrorBoundary>
</div>
</PrivateMainArea>
);
};
interface PrivateMainSettingsAreaProps {
children: ReactNode;
setActiveSection?: (section: string) => void;
config: SettingsAreaConfig;
}
const PrivateMainSettingsArea = ({ setActiveSection, children, config }: PrivateMainSettingsAreaProps) => {
const { text, title, description, subsections } = config;
const wrappedSections = Children.toArray(children).map((child, i) => {
if (!isValidElement<{ observer: IntersectionObserver; className: string }>(child)) {
return null;
}
const subsectionConfig = subsections?.[i];
if (!subsectionConfig) {
throw new Error('Missing subsection');
}
if (!getIsSubsectionAvailable(subsectionConfig)) {
return null;
}
return (
<SubSettingsSection
key={subsectionConfig.id}
id={subsectionConfig.id}
title={subsectionConfig.text}
className="container-section-sticky-section"
>
{child}
</SubSettingsSection>
);
});
return (
<PrivateMainSettingsAreaBase
title={title || text}
description={description}
setActiveSection={setActiveSection}
>
{wrappedSections}
</PrivateMainSettingsAreaBase>
);
};
export default PrivateMainSettingsArea;
| 6,400
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layout/SubSettingsSection.tsx
|
import { ComponentPropsWithoutRef, ReactNode, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import { c } from 'ttag';
import { textToClipboard } from '@proton/shared/lib/helpers/browser';
import clsx from '@proton/utils/clsx';
import { Icon } from '../../components';
import { useNotifications } from '../../hooks';
import { SettingsSectionTitle } from '../account';
export interface SubSettingsSectionProps extends ComponentPropsWithoutRef<'div'> {
id: string;
className?: string;
observer?: IntersectionObserver;
title?: string;
children: ReactNode;
}
const SubSettingsSection = ({ id, observer, title, children, className, ...rest }: SubSettingsSectionProps) => {
const ref = useRef<HTMLDivElement>(null);
const { createNotification } = useNotifications();
useEffect(() => {
const el = ref.current;
if (!observer || !el) {
return;
}
observer.observe(el);
return () => {
observer.unobserve(el);
};
}, [observer, ref.current]);
const handleLinkClick = () => {
const hash = document.location.hash;
const dehashedHref = document.location.href.replace(hash, '');
const urlToCopy = `${dehashedHref}#${id}`;
textToClipboard(urlToCopy);
createNotification({
text: c('Info').t`Link copied to clipboard`,
});
};
return (
<>
<div className="relative">
<div id={id} className="header-height-anchor" />
</div>
<section
{...rest}
id={id}
ref={ref}
data-target-id={id}
className={clsx([className, 'sub-settings-section'])}
>
{title && (
<SettingsSectionTitle className="group-hover-opacity-container relative">
<Link
to={`#${id}`}
onClick={handleLinkClick}
className="sub-settings-section-anchor absolute group-hover:opacity-100"
aria-hidden="true"
tabIndex={-1}
>
<Icon name="link" />
</Link>
{title}
</SettingsSectionTitle>
)}
{children}
</section>
</>
);
};
export default SubSettingsSection;
| 6,401
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layout/helper.ts
|
import { SectionConfig, SubSectionConfig } from '@proton/components';
export const getIsSubsectionAvailable = (section: SubSectionConfig) => {
return !(section.available === false);
};
export const getIsSectionAvailable = (section: SectionConfig) => {
const subsections = Object.values(section.subsections || {});
return !(section.available === false || subsections.every((subsection) => !getIsSubsectionAvailable(subsection)));
};
export const getSectionPath = (path: string, section: SectionConfig) => {
return `${path}${section.to}`;
};
| 6,402
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layout/index.ts
|
export { default as PrivateMainArea } from './PrivateMainArea';
export { default as PrivateMainSettingsArea } from './PrivateMainSettingsArea';
export { default as PrivateMainAreaLoading } from './PrivateMainAreaLoading';
export { default as SubSettingsSection } from './SubSettingsSection';
export * from './interface';
| 6,403
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layout/interface.ts
|
import { ReactNode } from 'react';
import { ThemeColor } from '@proton/colors';
import { IconName } from '../../components';
export interface SubSectionConfig {
text?: string;
id: string;
hide?: boolean;
available?: boolean;
}
export interface SettingsAreaConfig {
text: string;
title?: string;
description?: ReactNode;
subsections: SubSectionConfig[];
}
export interface SectionConfig extends SettingsAreaConfig {
to: string;
icon: IconName;
available?: boolean;
notification?: ThemeColor;
}
export interface SidebarConfig {
readonly available?: boolean;
readonly header: string;
readonly routes: { [key: string]: SectionConfig };
}
| 6,404
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layout/useActiveSection.ts
|
import { useEffect, useState } from 'react';
import 'intersection-observer';
const useActiveSection = (setActiveSection: (section: string) => void) => {
const [observer, setObserver] = useState<IntersectionObserver | undefined>();
useEffect(() => {
if (!setActiveSection) {
return;
}
const map: { [key: string]: number } = {};
const keys: string[] = [];
const handleIntersect = (elements: IntersectionObserverEntry[]) => {
elements.forEach((element) => {
const { target, intersectionRatio } = element;
if (!(target instanceof HTMLElement)) {
return;
}
const id = target.dataset.targetId;
if (!id) {
return;
}
if (!map[id]) {
keys.push(id);
}
map[id] = intersectionRatio;
});
const { id } = keys.reduce<{ value: number; id: string }>(
(cur, id) => {
const otherValue = map[id];
if (otherValue > cur.value) {
return { value: otherValue, id };
}
return cur;
},
{ value: map[keys[0]], id: keys[0] }
);
setActiveSection(id);
};
const options = {
root: null,
rootMargin: '0px',
threshold: [0.5, 0.99],
/*
A 0.5 threshold takes care of observing changes in big sections, while the 0.99 takes care of small sections.
Using 0.99 instead of 1 should help in case intersectionRatio doesn't fully reach 1, which has been observed to happen
*/
};
const observer = new IntersectionObserver(handleIntersect, options);
setObserver(observer);
return () => {
observer.disconnect();
};
}, [setActiveSection]);
return observer;
};
export default useActiveSection;
| 6,405
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/ComposerModeCards.tsx
|
import { c } from 'ttag';
import { COMPOSER_MODE } from '@proton/shared/lib/mail/mailSettings';
import composerMaximizedSvg from '@proton/styles/assets/img/layout/layout-thumb-composer-maximized.svg';
import composerPopUpSvg from '@proton/styles/assets/img/layout/layout-thumb-composer-normal.svg';
import { LayoutCards } from '../../components';
const { POPUP, MAXIMIZED } = COMPOSER_MODE;
interface Props {
composerMode: COMPOSER_MODE;
onChange: (composerMode: COMPOSER_MODE) => void;
loading: boolean;
describedByID: string;
className?: string;
liClassName?: string;
}
const ComposerModeCards = ({
composerMode,
onChange,
className,
liClassName,
loading,
describedByID,
...rest
}: Props) => {
const layoutCardPopup = {
value: POPUP,
selected: composerMode === POPUP,
disabled: loading,
name: 'composerMode',
label: c('Label to change composer mode').t`Normal`,
onChange() {
onChange(POPUP);
},
src: composerPopUpSvg,
describedByID,
};
const layoutCardMaximized = {
value: MAXIMIZED,
selected: composerMode === MAXIMIZED,
disabled: loading,
name: 'composerMode',
label: c('Label to change composer mode').t`Maximized`,
onChange() {
onChange(MAXIMIZED);
},
src: composerMaximizedSvg,
describedByID,
};
return (
<LayoutCards
list={[layoutCardPopup, layoutCardMaximized]}
className={className}
liClassName={liClassName}
describedByID={describedByID}
{...rest}
/>
);
};
export default ComposerModeCards;
| 6,406
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/DensityInjector.tsx
|
import { useLayoutEffect } from 'react';
import { DENSITY } from '@proton/shared/lib/constants';
import { useUserSettings } from '../../hooks';
const { COMPACT, COMFORTABLE } = DENSITY;
const CLASSES = {
[COMPACT]: 'is-compact',
[COMFORTABLE]: 'is-comfortable',
} as const;
const DensityInjector = () => {
const [{ Density } = { Density: COMFORTABLE }] = useUserSettings();
useLayoutEffect(() => {
document.body.classList.add(CLASSES[Density]);
return () => {
document.body.classList.remove(CLASSES[Density]);
};
}, [Density]);
return null;
};
export default DensityInjector;
| 6,407
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/DensityRadiosCards.tsx
|
import { c } from 'ttag';
import { DENSITY } from '@proton/shared/lib/constants';
import comfortableDensitySvg from '@proton/styles/assets/img/layout/layout-thumb-density-comfortable.svg';
import compactDensitySvg from '@proton/styles/assets/img/layout/layout-thumb-density-compact.svg';
import { LayoutCards } from '../../components';
const { COMFORTABLE, COMPACT } = DENSITY;
interface Props {
density: DENSITY;
onChange: (density: DENSITY) => void;
loading: boolean;
describedByID: string;
className?: string;
liClassName?: string;
}
const DensityRadiosCards = ({ density, onChange, loading, className, liClassName, describedByID, ...rest }: Props) => {
const layoutCardComfortable = {
value: COMFORTABLE,
selected: density === COMFORTABLE,
disabled: loading,
name: 'density',
label: c('Label to change density').t`Comfortable`,
onChange() {
onChange(COMFORTABLE);
},
src: comfortableDensitySvg,
describedByID,
};
const layoutCardCompact = {
value: COMPACT,
selected: density === COMPACT,
disabled: loading,
name: 'density',
label: c('Label to change density').t`Compact`,
onChange() {
onChange(COMPACT);
},
src: compactDensitySvg,
describedByID,
};
return (
<LayoutCards
list={[layoutCardComfortable, layoutCardCompact]}
className={className}
liClassName={liClassName}
describedByID={describedByID}
{...rest}
/>
);
};
export default DensityRadiosCards;
| 6,408
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/DraftTypeSelect.tsx
|
import { ChangeEvent } from 'react';
import { c } from 'ttag';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Select } from '../../components';
const { DEFAULT, PLAINTEXT } = MIME_TYPES;
interface Props {
id: string;
draftType: MIME_TYPES;
onChange: (draftType: MIME_TYPES) => void;
loading: boolean;
}
const DraftTypeSelect = ({ id, draftType, onChange, loading, ...rest }: Props) => {
const options = [
{ text: c('Option').t`Normal`, value: DEFAULT },
{ text: c('Option').t`Plain text`, value: PLAINTEXT },
];
const handleChange = ({ target }: ChangeEvent<HTMLSelectElement>) => onChange(target.value as MIME_TYPES);
return <Select id={id} value={draftType} options={options} disabled={loading} onChange={handleChange} {...rest} />;
};
export default DraftTypeSelect;
| 6,409
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/FontFaceSelect.tsx
|
import * as React from 'react';
import { Option, SelectTwo } from '../../components';
import { DEFAULT_FONT_FACE, FONT_FACES } from '../../components/editor/constants';
interface Props {
id: string;
fontFace: string;
onChange: (value: string) => void;
loading: boolean;
}
const options = Object.values(FONT_FACES).map(({ label: text, value }) => ({ text, value: value.toLowerCase() }));
const FontFaceSelect = ({ id, fontFace, onChange, loading, ...rest }: Props) => {
const isValid = fontFace && options.some((option) => option.value === fontFace.toLowerCase());
// FontFace default API value is null and it doesn't trigger default parameter value
const fontFaceValue = isValid ? fontFace.toLowerCase() : DEFAULT_FONT_FACE.toLowerCase();
return (
<SelectTwo
id={id}
value={fontFaceValue}
disabled={loading}
onChange={({ value: selectedValue }) => {
const option = Object.values(FONT_FACES).find(({ value }) => value.toLowerCase() === selectedValue);
if (option) {
onChange(option.value);
}
}}
{...rest}
>
{options.map(({ text, value }) => (
<Option key={value} title={text} value={value} />
))}
</SelectTwo>
);
};
export default FontFaceSelect;
| 6,410
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/FontSizeSelect.tsx
|
import * as React from 'react';
import { Option, SelectTwo } from '../../components';
import { DEFAULT_FONT_SIZE, FONT_SIZES } from '../../components/editor/constants';
interface Props {
id: string;
fontSize: number;
onChange: (value: number) => void;
loading: boolean;
}
const options = Object.entries(FONT_SIZES).map(([valueInPx]) => {
const fontSizeNumber = valueInPx.replace('px', '');
return { text: fontSizeNumber, value: parseInt(fontSizeNumber, 10) };
});
const FontSizeSelect = ({ id, fontSize, onChange, loading, ...rest }: Props) => {
const isValid = options.some((option) => fontSize === option.value);
const fontFaceSize = isValid ? fontSize : DEFAULT_FONT_SIZE;
return (
<SelectTwo
id={id}
value={fontFaceSize}
disabled={loading}
onChange={({ value }) => {
onChange(value);
}}
{...rest}
>
{options.map(({ text, value }) => (
<Option key={value} value={value} title={text} />
))}
</SelectTwo>
);
};
export default FontSizeSelect;
| 6,411
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/LayoutsSection.tsx
|
import { c } from 'ttag';
import { useLoading } from '@proton/hooks';
import { updateComposerMode, updateViewLayout } from '@proton/shared/lib/api/mailSettings';
import { updateDensity } from '@proton/shared/lib/api/settings';
import { DENSITY } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { COMPOSER_MODE, DEFAULT_MAILSETTINGS, VIEW_LAYOUT } from '@proton/shared/lib/mail/mailSettings';
import { Info, Loader } from '../../components';
import { useApi, useEventManager, useMailSettings, useNotifications, useUserSettings } from '../../hooks';
import { SettingsSectionWide } from '../account';
import ComposerModeCards from './ComposerModeCards';
import DensityRadiosCards from './DensityRadiosCards';
import ViewLayoutCards from './ViewLayoutCards';
const LayoutsSection = () => {
const [{ ComposerMode, ViewLayout } = DEFAULT_MAILSETTINGS, loadingMailSettings] = useMailSettings();
const [{ Density }, loadingUserSettings] = useUserSettings();
const { call } = useEventManager();
const { createNotification } = useNotifications();
const api = useApi();
const [loadingComposerMode, withLoadingComposerMode] = useLoading();
const [loadingViewLayout, withLoadingViewLayout] = useLoading();
const [loadingDensity, withLoadingDensity] = useLoading();
const notifyPreferenceSaved = () => createNotification({ text: c('Success').t`Preference saved` });
const handleChangeComposerMode = async (mode: COMPOSER_MODE) => {
await api(updateComposerMode(mode));
await call();
notifyPreferenceSaved();
};
const handleChangeViewLayout = async (layout: VIEW_LAYOUT) => {
await api(updateViewLayout(layout));
await call();
notifyPreferenceSaved();
};
const handleChangeDensity = async (density: DENSITY) => {
await api(updateDensity(density));
await call();
notifyPreferenceSaved();
};
return (
<SettingsSectionWide className="flex flex-wrap">
{loadingMailSettings || loadingUserSettings ? (
<Loader />
) : (
<>
<div className="flex flex-nowrap mb-4 on-mobile-flex-column flex-column">
<span className="mb-4 text-semibold">
<span className="mr-2" id="layoutMode_desc">{c('Label').t`Inbox`}</span>
<Info
url={getKnowledgeBaseUrl('/change-inbox-layout')}
title={c('Tooltip').t`Set the default layout for your Inbox.`}
/>
</span>
<ViewLayoutCards
describedByID="layoutMode_desc"
viewLayout={ViewLayout}
onChange={(value) => withLoadingViewLayout(handleChangeViewLayout(value))}
loading={loadingViewLayout}
/>
</div>
<div className="flex flex-nowrap mb-4 on-mobile-flex-column flex-column">
<span className="mb-4 text-semibold">
<span className="mr-2" id="composerMode_desc">{c('Label').t`Composer`}</span>
<Info
url={getKnowledgeBaseUrl('/composer')}
title={c('Tooltip').t`Set the default Composer popup size as small or full screen.`}
/>
</span>
<ComposerModeCards
describedByID="composerMode_desc"
composerMode={ComposerMode}
onChange={(value) => withLoadingComposerMode(handleChangeComposerMode(value))}
loading={loadingComposerMode}
/>
</div>
<div className="flex flex-nowrap mb-4 on-mobile-flex-column flex-column">
<span className="mb-4 text-semibold">
<span className="mr-2" id="densityMode_desc">{c('Label').t`Density`}</span>
<Info
url={getKnowledgeBaseUrl('/change-inbox-layout')}
title={c('Tooltip').t`Set how your list of messages looks like by default.`}
/>
</span>
<DensityRadiosCards
density={Density}
describedByID="densityMode_desc"
onChange={(value) => withLoadingDensity(handleChangeDensity(value))}
loading={loadingDensity}
/>
</div>
</>
)}
</SettingsSectionWide>
);
};
export default LayoutsSection;
| 6,412
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/MessagesOtherSection.tsx
|
import { c } from 'ttag';
import { getFontFaceIdFromValue, getFontFaceValueFromId } from '@proton/components/components/editor/helpers/fontFace';
import { useLoading } from '@proton/hooks';
import {
updateDraftType,
updateFontFace,
updateFontSize,
updateRightToLeft,
} from '@proton/shared/lib/api/mailSettings';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { DEFAULT_MAILSETTINGS, DIRECTION } from '@proton/shared/lib/mail/mailSettings';
import { Info, Label } from '../../components';
import { DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE } from '../../components/editor/constants';
import { useApi, useEventManager, useMailSettings, useNotifications } from '../../hooks';
import SettingsLayout from '../account/SettingsLayout';
import SettingsLayoutLeft from '../account/SettingsLayoutLeft';
import SettingsLayoutRight from '../account/SettingsLayoutRight';
import DelaySendSecondsSelect from '../messages/DelaySendSecondsSelect';
import DraftTypeSelect from './DraftTypeSelect';
import FontFaceSelect from './FontFaceSelect';
import FontSizeSelect from './FontSizeSelect';
import TextDirectionSelect from './TextDirectionSelect';
const MessagesOtherSection = () => {
const api = useApi();
const [{ DraftMIMEType, RightToLeft, FontFace, FontSize, DelaySendSeconds } = DEFAULT_MAILSETTINGS] =
useMailSettings();
const fontFaceValue = getFontFaceValueFromId(FontFace) || DEFAULT_FONT_FACE;
const { createNotification } = useNotifications();
const { call } = useEventManager();
const [loadingDraftType, withLoadingDraftType] = useLoading();
const [loadingRightToLeft, withLoadingRightToLeft] = useLoading();
const [loadingFontFace, withLoadingFontFace] = useLoading();
const [loadingFontSize, withLoadingFontSize] = useLoading();
const notifyPreferenceSaved = () => createNotification({ text: c('Success').t`Preference saved` });
const handleChangeDraftType = async (value: MIME_TYPES) => {
await api(updateDraftType(value));
await call();
notifyPreferenceSaved();
};
const handleChangeRightToLeft = async (value: DIRECTION) => {
await api(updateRightToLeft(value));
await call();
notifyPreferenceSaved();
};
const handleChangeFontFace = async (value: string) => {
const fontFaceId = getFontFaceIdFromValue(value);
if (fontFaceId) {
await api(updateFontFace(fontFaceId));
await call();
notifyPreferenceSaved();
}
};
const handleChangeFontSize = async (value: number) => {
await api(updateFontSize(value));
await call();
notifyPreferenceSaved();
};
return (
<>
<SettingsLayout>
<SettingsLayoutLeft>
<Label htmlFor="draftType" className="text-semibold">
{c('Label').t`Composer mode`}
</Label>
</SettingsLayoutLeft>
<SettingsLayoutRight>
<DraftTypeSelect
id="draftType"
draftType={DraftMIMEType}
onChange={(value) => withLoadingDraftType(handleChangeDraftType(value))}
loading={loadingDraftType}
data-testid="appearance:draft-type-select"
/>
</SettingsLayoutRight>
</SettingsLayout>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="textDirection" className="text-semibold">
{c('Label').t`Composer text direction`}
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight>
<TextDirectionSelect
id="textDirection"
rightToLeft={RightToLeft}
onChange={(value) => withLoadingRightToLeft(handleChangeRightToLeft(value))}
loading={loadingRightToLeft}
data-testid="appearance:text-direction-select"
/>
</SettingsLayoutRight>
</SettingsLayout>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="fontFace" id="label-composer-default-font-size" className="text-semibold">
{c('Label').t`Composer default font/size`}
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="settings-layout-right-fixed-size flex flex-row">
<div className="flex-item-fluid pr-2">
<FontFaceSelect
id="fontFace"
aria-describedby="label-composer-default-font-size"
fontFace={fontFaceValue}
onChange={(value) => withLoadingFontFace(handleChangeFontFace(value))}
loading={loadingFontFace}
/>
</div>
<div className="flex-item-noshrink">
<FontSizeSelect
id="fontSize"
aria-describedby="label-composer-default-font-size"
fontSize={FontSize || DEFAULT_FONT_SIZE}
onChange={(value) => withLoadingFontSize(handleChangeFontSize(value))}
loading={loadingFontSize}
/>
</div>
</SettingsLayoutRight>
</SettingsLayout>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="delaySendSecondsSelect" className="text-semibold">
<span className="mr-2">{c('Label').t`Undo send`}</span>
<Info
title={c('Tooltip')
.t`This feature delays sending your emails, giving you the opportunity to undo send during the selected time frame.`}
/>
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight>
<DelaySendSecondsSelect id="delaySendSecondsSelect" delaySendSeconds={DelaySendSeconds} />
</SettingsLayoutRight>
</SettingsLayout>
</>
);
};
export default MessagesOtherSection;
| 6,413
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/StickyLabelsToggle.tsx
|
import { ChangeEvent } from 'react';
import { STICKY_LABELS } from '@proton/shared/lib/mail/mailSettings';
import { Toggle } from '../../components';
import { useToggle } from '../../hooks';
const { ENABLED, DISABLED } = STICKY_LABELS;
interface Props {
id: string;
stickyLabels: STICKY_LABELS;
onToggle: (value: STICKY_LABELS) => void;
loading: boolean;
disabled?: boolean;
}
const StickyLabelsToggle = ({ id, stickyLabels, onToggle, loading, ...rest }: Props) => {
const { state, toggle } = useToggle(stickyLabels === ENABLED);
const handleToggle = ({ target }: ChangeEvent<HTMLInputElement>) => {
onToggle(target.checked ? ENABLED : DISABLED);
toggle();
};
return <Toggle id={id} checked={state} onChange={handleToggle} loading={loading} {...rest} />;
};
export default StickyLabelsToggle;
| 6,414
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/TextDirectionSelect.tsx
|
import { ChangeEvent } from 'react';
import { c } from 'ttag';
import { DIRECTION } from '@proton/shared/lib/mail/mailSettings';
import { Select } from '../../components';
const { LEFT_TO_RIGHT, RIGHT_TO_LEFT } = DIRECTION;
interface Props {
id: string;
rightToLeft: DIRECTION;
onChange: (value: DIRECTION) => void;
loading: boolean;
}
const TextDirectionSelect = ({ id, rightToLeft, onChange, loading, ...rest }: Props) => {
const options = [
{ text: c('Option').t`Left to Right`, value: LEFT_TO_RIGHT },
{ text: c('Option').t`Right to Left`, value: RIGHT_TO_LEFT },
];
const handleChange = ({ target }: ChangeEvent<HTMLSelectElement>) => {
onChange(parseInt(target.value, 10) as DIRECTION);
};
return (
<Select id={id} value={rightToLeft} options={options} disabled={loading} onChange={handleChange} {...rest} />
);
};
export default TextDirectionSelect;
| 6,415
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/ViewLayoutCards.tsx
|
import { c } from 'ttag';
import { VIEW_LAYOUT } from '@proton/shared/lib/mail/mailSettings';
import inboxColumnSvg from '@proton/styles/assets/img/layout/layout-thumb-inbox-column.svg';
import inboxRowSvg from '@proton/styles/assets/img/layout/layout-thumb-inbox-row.svg';
import { LayoutCards } from '../../components';
const { COLUMN, ROW } = VIEW_LAYOUT;
interface Props {
viewLayout: VIEW_LAYOUT;
onChange: (viewLayout: VIEW_LAYOUT) => void;
loading: boolean;
describedByID: string;
className?: string;
liClassName?: string;
}
const ViewLayoutCards = ({ viewLayout, onChange, loading, className, liClassName, describedByID, ...rest }: Props) => {
const layoutCardColumn = {
value: COLUMN,
selected: viewLayout === COLUMN,
disabled: loading,
name: 'viewLayout',
label: c('Label to change view layout').t`Column`,
onChange() {
onChange(COLUMN);
},
src: inboxColumnSvg,
describedByID,
};
const layoutCardRow = {
value: ROW,
selected: viewLayout === ROW,
disabled: loading,
name: 'viewLayout',
label: c('Label to change view layout').t`Row`,
onChange() {
onChange(ROW);
},
src: inboxRowSvg,
describedByID,
};
return (
<LayoutCards
list={[layoutCardColumn, layoutCardRow]}
className={className}
liClassName={liClassName}
describedByID={describedByID}
{...rest}
/>
);
};
export default ViewLayoutCards;
| 6,416
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/ViewModeToggle.tsx
|
import { ChangeEvent } from 'react';
import { VIEW_MODE } from '@proton/shared/lib/mail/mailSettings';
import { Toggle } from '../../components';
import { useToggle } from '../../hooks';
const { GROUP, SINGLE } = VIEW_MODE;
interface Props {
viewMode: VIEW_MODE;
onToggle: (viewMode: VIEW_MODE) => void;
loading: boolean;
id: string;
}
const ViewModeToggle = ({ viewMode, onToggle, loading, id, ...rest }: Props) => {
const { state, toggle } = useToggle(viewMode === GROUP);
const handleToggle = ({ target }: ChangeEvent<HTMLInputElement>) => {
onToggle(target.checked ? GROUP : SINGLE);
toggle();
};
return <Toggle id={id} checked={state} onChange={handleToggle} loading={loading} {...rest} />;
};
export default ViewModeToggle;
| 6,417
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/layouts/index.ts
|
export { default as DraftTypeSelect } from './DraftTypeSelect';
export { default as TextDirectionSelect } from './TextDirectionSelect';
export { default as ViewModeToggle } from './ViewModeToggle';
export { default as LayoutsSection } from './LayoutsSection';
export { default as ViewLayoutCards } from './ViewLayoutCards';
export { default as ComposerModeCards } from './ComposerModeCards';
export { default as DensityInjector } from './DensityInjector';
export { default as MessagesOtherSection } from './MessagesOtherSection';
| 6,418
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/login/AbuseModal.tsx
|
import DOMPurify from 'dompurify';
import { c } from 'ttag';
import { Button, Href } from '@proton/atoms';
import { isElement } from '@proton/shared/lib/helpers/dom';
import { getAbuseURL } from '@proton/shared/lib/helpers/url';
import { Prompt } from '../../components';
interface Props {
message?: string;
open: boolean;
onClose: () => void;
}
const sanitize = (msg: string) => {
const sanitizedElement = DOMPurify.sanitize(msg, {
RETURN_DOM: true,
ALLOWED_TAGS: ['b', 'a', 'i', 'em', 'strong', 'br', 'p', 'span'],
ALLOWED_ATTR: ['href'],
});
sanitizedElement.querySelectorAll('A').forEach((node) => {
if (node.tagName === 'A') {
node.setAttribute('rel', 'noopener noreferrer');
node.setAttribute('target', '_blank');
}
});
return sanitizedElement;
};
const containsHTML = (el?: Node) => {
return el?.childNodes && Array.from(el.childNodes).some(isElement);
};
const purifyMessage = (msg: string) => {
const sanitizedElement = sanitize(msg);
if (containsHTML(sanitizedElement)) {
return <div dangerouslySetInnerHTML={{ __html: sanitizedElement.innerHTML }} />;
}
return <>{msg}</>;
};
const AbuseModal = ({ message, open, onClose }: Props) => {
const contactLink = (
<Href href={getAbuseURL()} key={1}>
{c('Info').t`here`}
</Href>
);
return (
<Prompt
open={open}
title={c('Title').t`Account suspended`}
onClose={onClose}
buttons={<Button onClick={onClose}>{c('Action').t`Close`}</Button>}
>
{message ? (
purifyMessage(message)
) : (
<>
<div className="mb-4">{c('Info')
.t`This account has been suspended due to a potential policy violation.`}</div>
<div>{c('Info').jt`If you believe this is in error, please contact us ${contactLink}.`}</div>
</>
)}
</Prompt>
);
};
export default AbuseModal;
| 6,419
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/login/FooterDetails.tsx
|
import { ReactNode } from 'react';
import { c } from 'ttag';
import { BRAND_NAME } from '@proton/shared/lib/constants';
interface Props {
link?: ReactNode;
}
const FooterDetails = ({ link }: Props) => {
const currentYear = new Date().getFullYear();
return (
<>
{currentYear} {link} -{' '}
{
// translator: full sentence 'Proton. Privacy by default.'
c('Footer').t`${BRAND_NAME}. Privacy by default.`
}
</>
);
};
export default FooterDetails;
| 6,420
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/login/MinimalLoginContainer.tsx
|
import { ReactNode, useEffect, useRef, useState } from 'react';
import { c } from 'ttag';
import { Button, CircleLoader } from '@proton/atoms';
import { TotpInputs } from '@proton/components/containers';
import { startUnAuthFlow } from '@proton/components/containers/api/unAuthenticatedApi';
import { useLoading } from '@proton/hooks';
import { getApiErrorMessage } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { API_CUSTOM_ERROR_CODES } from '@proton/shared/lib/errors';
import { requiredValidator } from '@proton/shared/lib/helpers/formValidators';
import noop from '@proton/utils/noop';
import { InputFieldTwo, PasswordInputTwo, useFormErrors } from '../../components';
import { useApi, useConfig, useErrorHandler, useNotifications } from '../../hooks';
import { OnLoginCallback } from '../app/interface';
import { Challenge, ChallengeError, ChallengeRef, ChallengeResult } from '../challenge';
import useKTActivation from '../keyTransparency/useKTActivation';
import AbuseModal from './AbuseModal';
import { AuthActionResponse, AuthCacheResult, AuthStep } from './interface';
import { handleLogin, handleNextLogin, handleTotp, handleUnlock } from './loginActions';
const UnlockForm = ({
onSubmit,
cancelButton,
}: {
onSubmit: (totp: string) => Promise<void>;
cancelButton?: ReactNode;
}) => {
const [loading, withLoading] = useLoading();
const [keyPassword, setKeyPassword] = useState('');
const { validator, onFormSubmit } = useFormErrors();
return (
<form
name="unlockForm"
onSubmit={(event) => {
event.preventDefault();
if (!onFormSubmit()) {
return;
}
withLoading(onSubmit(keyPassword)).catch(noop);
}}
method="post"
>
<InputFieldTwo
as={PasswordInputTwo}
id="mailboxPassword"
bigger
label={c('Label').t`Mailbox password`}
error={validator([requiredValidator(keyPassword)])}
disableChange={loading}
autoFocus
value={keyPassword}
onValue={setKeyPassword}
/>
<div className="flex flex-justify-space-between">
<Button
color="norm"
size="large"
fullWidth
type="submit"
loading={loading}
data-cy-login="submit mailbox password"
>
{c('Action').t`Submit`}
</Button>
{cancelButton}
</div>
</form>
);
};
const TOTPForm = ({
onSubmit,
cancelButton,
}: {
onSubmit: (totp: string) => Promise<void>;
cancelButton?: ReactNode;
}) => {
const [loading, withLoading] = useLoading();
const [code, setCode] = useState('');
const [type, setType] = useState<'totp' | 'recovery-code'>('totp');
const hasBeenAutoSubmitted = useRef(false);
const { validator, onFormSubmit, reset } = useFormErrors();
const safeCode = code.replaceAll(/\s+/g, '');
const requiredError = requiredValidator(safeCode);
useEffect(() => {
if (type !== 'totp' || loading || requiredError || hasBeenAutoSubmitted.current) {
return;
}
// Auto-submit the form once the user has entered the TOTP
if (safeCode.length === 6) {
// Do it just one time
hasBeenAutoSubmitted.current = true;
withLoading(onSubmit(safeCode)).catch(noop);
}
}, [safeCode]);
return (
<form
name="totpForm"
onSubmit={(event) => {
event.preventDefault();
if (!onFormSubmit()) {
return;
}
withLoading(onSubmit(safeCode)).catch(noop);
}}
method="post"
>
<TotpInputs
type={type}
code={code}
error={validator([requiredError])}
loading={loading}
setCode={setCode}
bigger={true}
/>
<div className="flex flex-justify-space-between">
<Button size="large" fullWidth color="norm" type="submit" loading={loading}>
{c('Action').t`Submit`}
</Button>
<Button
color="norm"
shape="ghost"
size="large"
fullWidth
className="mt-2"
onClick={() => {
if (loading) {
return;
}
reset();
setCode('');
setType(type === 'totp' ? 'recovery-code' : 'totp');
}}
>
{type === 'totp' ? c('Action').t`Use recovery code` : c('Action').t`Use authentication code`}
</Button>
{cancelButton}
</div>
</form>
);
};
const LoginForm = ({
onSubmit,
hasChallenge,
needHelp,
footer,
}: {
onSubmit: (username: string, password: string, payload: ChallengeResult) => Promise<void>;
hasChallenge?: boolean;
needHelp?: ReactNode;
footer?: ReactNode;
}) => {
const [loading, withLoading] = useLoading();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const challengeRefLogin = useRef<ChallengeRef>();
const usernameRef = useRef<HTMLInputElement>(null);
const [challengeLoading, setChallengeLoading] = useState(hasChallenge);
const [challengeError, setChallengeError] = useState(false);
const { validator, onFormSubmit } = useFormErrors();
useEffect(() => {
if (challengeLoading) {
return;
}
// Special focus management for challenge
usernameRef.current?.focus();
}, [challengeLoading]);
if (challengeError) {
return <ChallengeError />;
}
return (
<>
{challengeLoading && (
<div className="text-center">
<CircleLoader className="color-primary" size="large" />
</div>
)}
<form
name="loginForm"
className={challengeLoading ? 'hidden' : undefined}
onSubmit={(event) => {
event.preventDefault();
if (!onFormSubmit()) {
return;
}
const run = async () => {
const payload = await challengeRefLogin.current?.getChallenge().catch(noop);
return onSubmit(username, password, payload);
};
withLoading(run()).catch(noop);
}}
method="post"
>
{hasChallenge && (
<Challenge
className="h-0"
tabIndex={-1}
challengeRef={challengeRefLogin}
name="login"
type={0}
onSuccess={() => {
setChallengeLoading(false);
}}
onError={() => {
setChallengeLoading(false);
setChallengeError(true);
}}
/>
)}
<InputFieldTwo
id="username"
bigger
label={c('Label').t`Email or username`}
error={validator([requiredValidator(username)])}
autoComplete="username"
value={username}
onValue={setUsername}
ref={usernameRef}
/>
<InputFieldTwo
id="password"
bigger
label={c('Label').t`Password`}
error={validator([requiredValidator(password)])}
as={PasswordInputTwo}
autoComplete="current-password"
value={password}
onValue={setPassword}
rootClassName="mt-2"
/>
<div className="flex flex-justify-space-between mt-4">
{needHelp}
<Button color="norm" size="large" type="submit" fullWidth loading={loading} data-cy-login="submit">
{c('Action').t`Sign in`}
</Button>
</div>
{footer}
</form>
</>
);
};
interface Props {
onLogin: OnLoginCallback;
needHelp?: ReactNode;
footer?: ReactNode;
hasChallenge?: boolean;
ignoreUnlock?: boolean;
}
const MinimalLoginContainer = ({ onLogin, hasChallenge = false, ignoreUnlock = false, needHelp, footer }: Props) => {
const { APP_NAME } = useConfig();
const { createNotification } = useNotifications();
const [abuseModal, setAbuseModal] = useState<{ apiErrorMessage?: string } | undefined>(undefined);
const ktActivation = useKTActivation();
const normalApi = useApi();
const silentApi = <T,>(config: any) => normalApi<T>({ ...config, silence: true });
const errorHandler = useErrorHandler();
const cacheRef = useRef<AuthCacheResult | undefined>(undefined);
const [step, setStep] = useState(AuthStep.LOGIN);
const handleResult = (result: AuthActionResponse) => {
if (result.to === AuthStep.DONE) {
return onLogin(result.session);
}
cacheRef.current = result.cache;
setStep(result.to);
};
const handleCancel = () => {
cacheRef.current = undefined;
setStep(AuthStep.LOGIN);
};
const handleError = (e: any) => {
if (e.data?.Code === API_CUSTOM_ERROR_CODES.AUTH_ACCOUNT_DISABLED) {
setAbuseModal({ apiErrorMessage: getApiErrorMessage(e) });
return;
}
if (e.name === 'TOTPError' || e.name === 'PasswordError') {
createNotification({ type: 'error', text: e.message });
return;
}
if (
step === AuthStep.LOGIN ||
(step === AuthStep.UNLOCK && e.name !== 'PasswordError') ||
(step === AuthStep.TWO_FA && e.name !== 'TOTPError')
) {
handleCancel();
}
errorHandler(e);
};
const cancelButton = (
<Button size="large" shape="ghost" type="button" fullWidth onClick={handleCancel} className="mt-2">
{c('Action').t`Cancel`}
</Button>
);
const cache = cacheRef.current;
return (
<>
<AbuseModal
message={abuseModal?.apiErrorMessage}
open={!!abuseModal}
onClose={() => setAbuseModal(undefined)}
/>
{step === AuthStep.LOGIN && (
<LoginForm
needHelp={needHelp}
footer={footer}
hasChallenge={hasChallenge}
onSubmit={async (username, password, payload) => {
try {
await startUnAuthFlow();
const loginResult = await handleLogin({
username,
persistent: false,
payload,
password,
api: silentApi,
});
const result = await handleNextLogin({
authResponse: loginResult.authResult.result,
authVersion: loginResult.authResult.authVersion,
appName: APP_NAME,
toApp: APP_NAME,
username,
password,
api: silentApi,
ignoreUnlock,
hasTrustedDeviceRecovery: false,
persistent: false,
setupVPN: false,
ktActivation,
});
return await handleResult(result);
} catch (e) {
handleError(e);
}
}}
/>
)}
{step === AuthStep.TWO_FA && cache && (
<TOTPForm
cancelButton={cancelButton}
onSubmit={(totp) => {
return handleTotp({
cache,
totp,
})
.then(handleResult)
.catch(handleError);
}}
/>
)}
{step === AuthStep.UNLOCK && cache && (
<UnlockForm
cancelButton={cancelButton}
onSubmit={(keyPassword) => {
return handleUnlock({
cache,
clearKeyPassword: keyPassword,
isOnePasswordMode: false,
})
.then(handleResult)
.catch(handleError);
}}
/>
)}
</>
);
};
export default MinimalLoginContainer;
| 6,421
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/login/UnlockModal.tsx
|
import { useRef, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { PASSWORD_WRONG_ERROR } from '@proton/shared/lib/api/auth';
import { getApiError } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { queryUnlock } from '@proton/shared/lib/api/user';
import { srpAuth } from '@proton/shared/lib/srp';
import noop from '@proton/utils/noop';
import {
Form,
InputFieldTwo,
ModalTwo as Modal,
ModalTwoContent as ModalContent,
ModalTwoFooter as ModalFooter,
ModalTwoHeader as ModalHeader,
ModalProps,
PasswordInputTwo,
} from '../../components';
import { useApi, useErrorHandler } from '../../hooks';
interface Props extends Omit<ModalProps<typeof Form>, 'as' | 'onSubmit' | 'size' | 'onSuccess'> {
onSuccess?: (password: string) => Promise<void> | void;
onClose?: () => void;
onCancel?: () => void;
}
const UnlockModal = ({ onClose, onSuccess, onCancel, ...rest }: Props) => {
const api = useApi();
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const passwordRef = useRef<HTMLInputElement>(null);
const errorHandler = useErrorHandler();
const cancelClose = () => {
onCancel?.();
onClose?.();
};
const handleSubmit = async () => {
try {
setLoading(true);
await srpAuth({
api,
credentials: { password },
config: { ...queryUnlock(), silence: true },
});
// We want to just keep the modal open until the consumer's promise is finished. Not interested in errors.
await onSuccess?.(password)?.catch(noop);
onClose?.();
} catch (error: any) {
errorHandler(error);
setLoading(false);
const { code } = getApiError(error);
if (code !== PASSWORD_WRONG_ERROR) {
cancelClose();
return;
}
setPassword('');
passwordRef.current?.focus();
}
};
// Don't allow to close this modal if it's loading as it could leave other consumers in an undefined state
const handleClose = loading ? noop : cancelClose;
return (
<Modal {...rest} size="small" as={Form} onSubmit={() => handleSubmit()} onClose={handleClose}>
<ModalHeader title={c('Title').t`Enter your password`} />
<ModalContent>
<InputFieldTwo
ref={passwordRef}
required
autoFocus
autoComplete="current-password"
id="password"
as={PasswordInputTwo}
value={password}
onValue={setPassword}
label={c('Label').t`Password`}
placeholder={c('Placeholder').t`Password`}
/>
</ModalContent>
<ModalFooter>
<Button onClick={handleClose} disabled={loading}>{c('Action').t`Cancel`}</Button>
<Button color="norm" type="submit" loading={loading}>
{c('Action').t`Authenticate`}
</Button>
</ModalFooter>
</Modal>
);
};
export default UnlockModal;
| 6,422
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/login/index.ts
|
export { default as AbuseModal } from './AbuseModal';
export { default as MinimalForgotUsernameContainer } from '../forgotUsername/MinimalForgotUsernameContainer';
export { default as MinimalLoginContainer } from './MinimalLoginContainer';
export { default as FooterDetails } from './FooterDetails';
export { default as UnlockModal } from './UnlockModal';
| 6,423
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/login/interface.tsx
|
import { AuthResponse, AuthVersion } from '@proton/shared/lib/authentication/interface';
import { APP_NAMES } from '@proton/shared/lib/constants';
import {
Address,
Api,
KeyMigrationKTVerifier,
PreAuthKTVerifier,
Address as tsAddress,
KeySalt as tsKeySalt,
User as tsUser,
} from '@proton/shared/lib/interfaces';
import { AddressGenerationSetup, ClaimableAddress } from '@proton/shared/lib/keys';
export interface AddressGeneration {
externalEmailAddress: Address | undefined;
availableDomains: string[];
setup: AddressGenerationSetup;
claimableAddress: ClaimableAddress | undefined;
}
export enum AuthStep {
LOGIN,
TWO_FA,
UNLOCK,
NEW_PASSWORD,
SETUP,
DONE,
}
export interface AuthTypes {
totp: boolean;
fido2: boolean;
unlock: boolean;
}
export interface AuthCacheResult {
appName: APP_NAMES;
toApp: APP_NAMES | undefined;
shouldSetup?: boolean;
authVersion: AuthVersion;
authResponse: AuthResponse;
api: Api;
data: { user?: tsUser; salts?: tsKeySalt[]; addresses?: Address[] };
authTypes: AuthTypes;
username: string;
persistent: boolean;
loginPassword: string;
hasTrustedDeviceRecovery: boolean;
ignoreUnlock: boolean;
addressGeneration?: AddressGeneration;
setupVPN: boolean;
preAuthKTVerifier: PreAuthKTVerifier;
keyMigrationKTVerifier: KeyMigrationKTVerifier;
}
export type AuthFlows = 'signup' | 'reset' | 'switch' | 'login' | undefined;
export interface AppIntent {
app: APP_NAMES;
ref?: 'product-switch';
}
export interface AuthSession {
UID: string;
EventID?: string;
LocalID: number;
User: tsUser;
Addresses?: tsAddress[];
keyPassword?: string;
loginPassword?: string;
path?: string;
flow?: AuthFlows;
appIntent?: AppIntent;
persistent: boolean;
trusted: boolean;
}
export type AuthActionResponse =
| {
to: AuthStep.DONE;
session: AuthSession;
}
| {
cache: AuthCacheResult;
to: Exclude<AuthStep, AuthStep.DONE>;
};
export enum AuthType {
SRP,
ExternalSSO,
}
| 6,424
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/login/loginActions.ts
|
import { c } from 'ttag';
import { serverTime, wasServerTimeEverUpdated } from '@proton/crypto';
import { getAllAddresses } from '@proton/shared/lib/api/addresses';
import { auth2FA, getInfo, revoke } from '@proton/shared/lib/api/auth';
import { queryAvailableDomains } from '@proton/shared/lib/api/domains';
import { getApiErrorMessage } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { getKeySalts } from '@proton/shared/lib/api/keys';
import { getSettings, upgradePassword } from '@proton/shared/lib/api/settings';
import { getUser } from '@proton/shared/lib/api/user';
import { AuthResponse, AuthVersion, Fido2Data, InfoResponse } from '@proton/shared/lib/authentication/interface';
import loginWithFallback from '@proton/shared/lib/authentication/loginWithFallback';
import { maybeResumeSessionByUser, persistSession } from '@proton/shared/lib/authentication/persistedSessionHelper';
import { APPS, APP_NAMES } from '@proton/shared/lib/constants';
import { HTTP_ERROR_CODES } from '@proton/shared/lib/errors';
import { wait } from '@proton/shared/lib/helpers/promise';
import { captureMessage } from '@proton/shared/lib/helpers/sentry';
import { getHostname } from '@proton/shared/lib/helpers/url';
import {
Api,
KeyTransparencyActivation,
UserSettings,
Address as tsAddress,
KeySalt as tsKeySalt,
User as tsUser,
} from '@proton/shared/lib/interfaces';
import {
getDecryptedUserKeysHelper,
getRequiresPasswordSetup,
getSentryError,
migrateUser,
} from '@proton/shared/lib/keys';
import { handleSetupAddressKeys } from '@proton/shared/lib/keys/setupAddressKeys';
import { getHasV2KeysToUpgrade, upgradeV2KeysHelper } from '@proton/shared/lib/keys/upgradeKeysV2';
import {
attemptDeviceRecovery,
getIsDeviceRecoveryAvailable,
removeDeviceRecovery,
storeDeviceRecovery,
} from '@proton/shared/lib/recoveryFile/deviceRecovery';
import { srpVerify } from '@proton/shared/lib/srp';
import { AUTH_VERSION } from '@proton/srp';
import noop from '@proton/utils/noop';
import { ChallengeResult } from '../challenge';
import { createKeyMigrationKTVerifier, createPreAuthKTVerifier } from '../keyTransparency';
import { AuthActionResponse, AuthCacheResult, AuthStep } from './interface';
import { getAuthTypes, handleUnlockKey } from './loginHelper';
const syncUser = async (cache: AuthCacheResult): Promise<tsUser> => {
const user = await cache.api<{ User: tsUser }>(getUser()).then(({ User }) => User);
cache.data.user = user;
return user;
};
const syncAddresses = async (cache: AuthCacheResult): Promise<tsAddress[]> => {
const addresses = await getAllAddresses(cache.api);
cache.data.addresses = addresses;
return addresses;
};
const syncSalts = async (cache: AuthCacheResult): Promise<tsKeySalt[]> => {
const salts = await cache.api<{ KeySalts: tsKeySalt[] }>(getKeySalts()).then(({ KeySalts }) => KeySalts);
cache.data.salts = salts;
return salts;
};
/**
* Finalize login can be called without a key password in these cases:
* 1) The admin panel
* 2) Users who have no keys but are in 2-password mode
*/
const finalizeLogin = async ({
cache,
loginPassword,
keyPassword,
}: {
cache: AuthCacheResult;
loginPassword: string;
keyPassword?: string;
}): Promise<AuthActionResponse> => {
const { authResponse, authVersion, api, persistent, appName, hasTrustedDeviceRecovery, preAuthKTVerifier } = cache;
if (authVersion < AUTH_VERSION) {
await srpVerify({
api,
credentials: { password: loginPassword },
config: upgradePassword(),
});
}
if (appName !== APPS.PROTONACCOUNT) {
const user = cache.data.user || (await syncUser(cache));
const trusted = false;
await persistSession({ ...authResponse, User: user, keyPassword, api, persistent, trusted });
return {
to: AuthStep.DONE,
session: {
...authResponse,
keyPassword,
loginPassword,
persistent,
trusted,
User: user,
flow: 'login',
},
};
}
let [user, addresses] = await Promise.all([
cache.data.user || syncUser(cache),
cache.data.addresses || syncAddresses(cache),
]);
const validatedSession = await maybeResumeSessionByUser(api, user);
if (validatedSession) {
await api(revoke()).catch(noop);
return {
to: AuthStep.DONE,
session: { ...validatedSession, loginPassword, flow: 'login' },
};
}
let trusted = false;
if (hasTrustedDeviceRecovery && keyPassword) {
const numberOfReactivatedKeys = await attemptDeviceRecovery({
api,
user,
addresses,
keyPassword,
preAuthKTVerify: preAuthKTVerifier.preAuthKTVerify,
}).catch(noop);
if (numberOfReactivatedKeys !== undefined && numberOfReactivatedKeys > 0) {
cache.data.user = undefined;
cache.data.addresses = undefined;
[user, addresses] = await Promise.all([syncUser(cache), syncAddresses(cache)]);
}
// Store device recovery information
if (persistent) {
const [userKeys] = await Promise.all([getDecryptedUserKeysHelper(user, keyPassword)]);
const isDeviceRecoveryAvailable = getIsDeviceRecoveryAvailable({
user,
addresses,
userKeys,
appName,
});
if (isDeviceRecoveryAvailable) {
const userSettings = await api<{ UserSettings: UserSettings }>(getSettings()).then(
({ UserSettings }) => UserSettings
);
if (userSettings.DeviceRecovery) {
await storeDeviceRecovery({ api, user, userKeys });
trusted = true;
}
}
} else {
removeDeviceRecovery(user.ID);
}
}
await persistSession({
...authResponse,
User: user,
keyPassword,
api,
persistent,
trusted,
});
await preAuthKTVerifier.preAuthKTCommit(user.ID);
return {
to: AuthStep.DONE,
session: {
...authResponse,
keyPassword,
loginPassword,
persistent,
trusted,
User: user,
flow: 'login',
},
};
};
const handleKeyUpgrade = async ({
cache,
loginPassword,
clearKeyPassword,
keyPassword: maybeKeyPassword,
isOnePasswordMode,
}: {
cache: AuthCacheResult;
loginPassword: string;
clearKeyPassword: string;
keyPassword: string;
isOnePasswordMode?: boolean;
}) => {
const { api, preAuthKTVerifier, keyMigrationKTVerifier } = cache;
let keyPassword = maybeKeyPassword;
let [user, addresses] = await Promise.all([
cache.data.user || syncUser(cache),
cache.data.addresses || syncAddresses(cache),
]);
const { preAuthKTVerify } = preAuthKTVerifier;
if (getHasV2KeysToUpgrade(user, addresses)) {
const newKeyPassword = await upgradeV2KeysHelper({
user,
addresses,
loginPassword,
keyPassword,
clearKeyPassword,
isOnePasswordMode,
api,
preAuthKTVerify,
keyMigrationKTVerifier,
}).catch((e) => {
const error = getSentryError(e);
if (error) {
captureMessage('Key upgrade error', { extra: { error } });
}
return undefined;
});
if (newKeyPassword !== undefined) {
cache.data.user = undefined;
cache.data.addresses = undefined;
[user, addresses] = await Promise.all([syncUser(cache), syncAddresses(cache)]);
keyPassword = newKeyPassword;
}
}
const hasDoneMigration = await migrateUser({
api,
keyPassword,
user,
addresses,
preAuthKTVerify,
keyMigrationKTVerifier,
}).catch((e) => {
const error = getSentryError(e);
if (error) {
captureMessage('Key migration error', {
extra: { error, serverTime: serverTime(), isServerTime: wasServerTimeEverUpdated() },
});
}
return false;
});
if (hasDoneMigration) {
cache.data.user = undefined;
cache.data.addresses = undefined;
}
return finalizeLogin({ cache, loginPassword, keyPassword });
};
/**
* Step 3. Handle unlock.
* Attempt to decrypt the primary private key with the password.
*/
export const handleUnlock = async ({
cache,
clearKeyPassword,
isOnePasswordMode,
}: {
cache: AuthCacheResult;
clearKeyPassword: string;
isOnePasswordMode: boolean;
}) => {
const {
data: { salts, user },
loginPassword,
} = cache;
if (!salts || !user) {
throw new Error('Invalid state');
}
await wait(500);
const unlockResult = await handleUnlockKey(user, salts, clearKeyPassword).catch(() => undefined);
if (!unlockResult) {
const error: any = new Error(c('Error').t`Incorrect mailbox password. Please try again.`);
error.name = 'PasswordError';
error.trace = false;
throw error;
}
return handleKeyUpgrade({
cache,
loginPassword,
clearKeyPassword,
keyPassword: unlockResult.keyPassword,
isOnePasswordMode,
});
};
/**
* Setup keys and address for users that have not setup.
*/
export const handleSetupPassword = async ({ cache, newPassword }: { cache: AuthCacheResult; newPassword: string }) => {
const { api, username, preAuthKTVerifier } = cache;
const [domains, addresses] = await Promise.all([
api<{ Domains: string[] }>(queryAvailableDomains('signup')).then(({ Domains }) => Domains),
cache.data.addresses || (await syncAddresses(cache)),
]);
const keyPassword = await handleSetupAddressKeys({
api,
username,
password: newPassword,
addresses,
domains,
preAuthKTVerify: preAuthKTVerifier.preAuthKTVerify,
});
cache.data.user = undefined;
cache.data.addresses = undefined;
return finalizeLogin({
cache,
loginPassword: newPassword,
keyPassword,
});
};
const next = async ({ cache, from }: { cache: AuthCacheResult; from: AuthStep }): Promise<AuthActionResponse> => {
const { authTypes, ignoreUnlock, authResponse, loginPassword } = cache;
if (from === AuthStep.LOGIN) {
if (authTypes.fido2 || authTypes.totp) {
return {
cache,
to: AuthStep.TWO_FA,
};
}
}
// Special case for the admin panel, return early since it can not get key salts.
if (ignoreUnlock) {
return finalizeLogin({ cache, loginPassword });
}
const [user] = await Promise.all([cache.data.user || syncUser(cache), cache.data.salts || syncSalts(cache)]);
if (user.Keys.length === 0) {
if (authResponse.TemporaryPassword) {
return { cache, to: AuthStep.NEW_PASSWORD };
}
if (getRequiresPasswordSetup(user, cache.setupVPN)) {
return handleSetupPassword({ cache, newPassword: loginPassword });
}
return finalizeLogin({ cache, loginPassword });
}
if (authTypes.unlock) {
return {
cache,
to: AuthStep.UNLOCK,
};
}
return handleUnlock({ cache, clearKeyPassword: loginPassword, isOnePasswordMode: true });
};
export const handleFido2 = async ({
cache,
payload,
}: {
cache: AuthCacheResult;
payload: Fido2Data;
}): Promise<AuthActionResponse> => {
const { api } = cache;
await api(auth2FA({ FIDO2: payload }));
return next({ cache, from: AuthStep.TWO_FA });
};
/**
* Step 2. Handle TOTP.
* Unless there is another auth type active, the flow will continue until it's logged in.
*/
export const handleTotp = async ({
cache,
totp,
}: {
cache: AuthCacheResult;
totp: string;
}): Promise<AuthActionResponse> => {
const { api } = cache;
await api(auth2FA({ TwoFactorCode: totp })).catch((e) => {
if (e.status === HTTP_ERROR_CODES.UNPROCESSABLE_ENTITY) {
const error: any = new Error(
getApiErrorMessage(e) || c('Error').t`Incorrect login credentials. Please try again.`
);
error.name = 'TOTPError';
error.trace = false;
throw error;
}
throw e;
});
return next({ cache, from: AuthStep.TWO_FA });
};
export const handleLogin = async ({
username,
password,
payload,
persistent,
api,
}: {
username: string;
password: string;
payload: ChallengeResult;
persistent: boolean;
api: Api;
}) => {
const infoResult = await api<InfoResponse>(getInfo(username));
const authResult = await loginWithFallback({
api,
credentials: { username, password },
initialAuthInfo: infoResult,
payload,
persistent,
});
return { infoResult, authResult };
};
export const handleNextLogin = async ({
authResponse,
authVersion,
username,
password,
persistent,
api,
ignoreUnlock,
hasTrustedDeviceRecovery,
appName,
toApp,
setupVPN,
ktActivation,
}: {
authVersion: AuthVersion;
authResponse: AuthResponse;
username: string;
password: string;
persistent: boolean;
api: Api;
ignoreUnlock: boolean;
hasTrustedDeviceRecovery: boolean;
appName: APP_NAMES;
toApp: APP_NAMES | undefined;
setupVPN: boolean;
ktActivation: KeyTransparencyActivation;
}): Promise<AuthActionResponse> => {
const cache: AuthCacheResult = {
authResponse,
authVersion,
appName,
toApp,
data: {},
api,
authTypes: getAuthTypes(authResponse, appName),
username,
persistent,
loginPassword: password,
ignoreUnlock,
hasTrustedDeviceRecovery,
setupVPN,
preAuthKTVerifier: createPreAuthKTVerifier(ktActivation, api),
keyMigrationKTVerifier: createKeyMigrationKTVerifier(ktActivation, api),
};
return next({ cache, from: AuthStep.LOGIN });
};
export const handleExternalSSOLogin = ({ token, signal }: { token: string; signal: AbortSignal }) => {
if (!token) {
throw new Error('Unexpected response');
}
const url = `${window.location.origin}/api/auth/sso/${token}`;
const handleMessage = (event: MessageEvent) => {
if (event.data.action === 'sso' && event.data.payload) {
const uid: string = event.data.payload.uid;
const token: string = event.data.payload.token;
return {
action: 'resolve' as const,
payload: { uid, token },
};
} else {
return {
action: 'reject' as const,
payload: new Error('Unknown message'),
};
}
};
const tab = window.open(url);
if (!tab) {
throw new Error('Unable to open tab');
}
return new Promise<{ uid: string; token: string }>((resolve, reject) => {
let handle: ReturnType<typeof setInterval> | undefined = undefined;
let reset: () => void;
const assertOpen = () => {
if (!tab || tab.closed) {
reset();
reject(new Error('Process closed'));
}
};
function onMessage(event: MessageEvent) {
if (event.source !== tab && getHostname(event.origin) !== window.location.origin) {
return;
}
const result = handleMessage(event);
if (result) {
if (result.action === 'resolve') {
resolve(result.payload);
} else if (result.action === 'reject') {
reject(result.payload);
}
reset();
tab?.close?.();
}
}
function abort() {
reset();
tab?.close?.();
reject(new Error('Process aborted'));
}
reset = () => {
clearInterval(handle);
signal.removeEventListener('abort', abort);
window.removeEventListener('message', onMessage, false);
};
signal.addEventListener('abort', abort);
window.addEventListener('message', onMessage, false);
handle = setInterval(() => {
assertOpen();
}, 5000);
});
};
| 6,425
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/login/loginHelper.ts
|
import { AuthTypes } from '@proton/components/containers/login/interface';
import { CryptoProxy } from '@proton/crypto';
import { AuthResponse } from '@proton/shared/lib/authentication/interface';
import { APP_NAMES, PASSWORD_MODE } from '@proton/shared/lib/constants';
import { KeySalt as tsKeySalt } from '@proton/shared/lib/interfaces/KeySalt';
import { User as tsUser } from '@proton/shared/lib/interfaces/User';
import { getPrimaryKeyWithSalt } from '@proton/shared/lib/keys/keys';
import { getHasFIDO2Enabled, getHasTOTPEnabled } from '@proton/shared/lib/settings/twoFactor';
import { getHasFIDO2Support } from '@proton/shared/lib/webauthn/helper';
import { computeKeyPassword } from '@proton/srp';
export const getAuthTypes = (info: AuthResponse, app: APP_NAMES): AuthTypes => {
const Enabled = info?.['2FA']?.Enabled || 0;
return {
totp: getHasTOTPEnabled(Enabled),
fido2: getHasFIDO2Enabled(Enabled) && getHasFIDO2Support(app, location.hostname),
unlock: info?.PasswordMode === PASSWORD_MODE.TWO_PASSWORD,
};
};
export const handleUnlockKey = async (User: tsUser, KeySalts: tsKeySalt[], rawKeyPassword: string) => {
const { KeySalt, PrivateKey } = getPrimaryKeyWithSalt(User.Keys, KeySalts);
if (!PrivateKey) {
throw new Error('Missing private key');
}
// Support for versions without a key salt.
const keyPassword = KeySalt ? ((await computeKeyPassword(rawKeyPassword, KeySalt)) as string) : rawKeyPassword;
const primaryKey = await CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: keyPassword });
return { primaryKey, keyPassword };
};
| 6,426
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/AppVersionCell.tsx
|
import { AuthLog } from '@proton/shared/lib/authlog';
interface Props {
appVersion: AuthLog['AppVersion'];
}
const AppVersionCell = ({ appVersion }: Props) => {
if (appVersion === null) {
return <span className="flex-item-fluid">-</span>;
}
const appVersionList = appVersion.split('@', 2);
if (appVersionList.length > 1) {
return (
<span className="flex-item-fluid">
{appVersionList[0]}
<br />
{appVersionList[1]}
</span>
);
}
return <span className="flex-item-fluid">{appVersion}</span>;
};
export default AppVersionCell;
| 6,427
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/DeviceCell.tsx
|
import { AuthLog } from '@proton/shared/lib/authlog';
interface Props {
device: AuthLog['Device'];
}
const DeviceCell = ({ device }: Props) => {
return <span className="flex-item-fluid">{device || '-'}</span>;
};
export default DeviceCell;
| 6,428
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/EventCell.tsx
|
import { AuthLog, AuthLogStatus } from '@proton/shared/lib/authlog';
import { Icon } from '../../components';
interface Props {
description: AuthLog['Description'];
status: AuthLog['Status'];
}
const getIcon = (status: AuthLogStatus) => {
switch (status) {
case AuthLogStatus.Attempt:
return <Icon className="align-text-bottom color-warning" name="exclamation-circle-filled" />;
case AuthLogStatus.Failure:
return <Icon className="align-text-bottom color-danger" name="cross-circle-filled" />;
}
return <Icon className="align-text-bottom color-success" name="checkmark-circle-filled" />;
};
const EventCell = ({ description, status }: Props) => {
return (
<div className="inline-flex">
<span className="flex-item-noshrink mr-2">{getIcon(status)}</span>
<span className="flex-item-fluid">{description}</span>
</div>
);
};
export default EventCell;
| 6,429
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/IPCell.tsx
|
import { c } from 'ttag';
import { PROTON_SENTINEL_NAME } from '@proton/shared/lib/constants';
interface Props {
ip: string;
isAuthLogAdvanced?: boolean;
isProtonSentinelEnabled?: boolean;
firstRow?: boolean;
}
const IPCell = ({ ip, isAuthLogAdvanced, isProtonSentinelEnabled, firstRow }: Props) => {
const advancedLogsUpsell = c('Description').t`Enable advanced logs to access these features`;
const advancedLogsAndProtonSentinelUpsell = c('Description')
.t`Enable advanced logs and ${PROTON_SENTINEL_NAME} to access these features`;
if (isAuthLogAdvanced) {
return <code>{ip || '-'}</code>;
}
if (firstRow) {
return (
<span className="flex-item-fluid text-bold color-weak">
{!isProtonSentinelEnabled && !isAuthLogAdvanced
? advancedLogsAndProtonSentinelUpsell
: advancedLogsUpsell}
</span>
);
}
return null;
};
export default IPCell;
| 6,430
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/LocationCell.tsx
|
import { c } from 'ttag';
import { PROTON_SENTINEL_NAME } from '@proton/shared/lib/constants';
interface Props {
location: string | null;
isProtonSentinelEnabled?: boolean;
firstRow?: boolean;
}
const LocationCell = ({ location, isProtonSentinelEnabled, firstRow }: Props) => {
const protonSentinelUpsell = c('Description').t`Enable ${PROTON_SENTINEL_NAME} to access these features`;
if (isProtonSentinelEnabled) {
return <span className="flex-item-fluid">{location || '-'}</span>;
}
if (firstRow) {
return <span className="flex-item-fluid text-bold color-weak">{protonSentinelUpsell}</span>;
}
return null;
};
export default LocationCell;
| 6,431
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/LogsSection.tsx
|
import { ChangeEvent, useEffect, useRef, useState } from 'react';
import { fromUnixTime } from 'date-fns';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { useLoading } from '@proton/hooks';
import { clearLogs, queryLogs } from '@proton/shared/lib/api/logs';
import { updateLogAuth } from '@proton/shared/lib/api/settings';
import { AuthLog } from '@proton/shared/lib/authlog';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import { wait } from '@proton/shared/lib/helpers/promise';
import { SETTINGS_LOG_AUTH_STATE } from '@proton/shared/lib/interfaces';
import { Alert, ConfirmModal, Icon, Info, Pagination, Toggle, usePaginationAsync } from '../../components';
import { useApi, useModals, useUserSettings } from '../../hooks';
import { SettingsParagraph, SettingsSectionWide } from '../account';
import SettingsLayout from '../account/SettingsLayout';
import SettingsLayoutLeft from '../account/SettingsLayoutLeft';
import SettingsLayoutRight from '../account/SettingsLayoutRight';
import LogsTable from './LogsTable';
import WipeLogsButton from './WipeLogsButton';
import { getAllAuthenticationLogs } from './helper';
const { BASIC, DISABLE, ADVANCED } = SETTINGS_LOG_AUTH_STATE;
const INITIAL_STATE = {
logs: [],
total: 0,
};
const PAGE_SIZE = 10;
const LogsSection = () => {
const [settings] = useUserSettings();
const { createModal } = useModals();
const [logAuth, setLogAuth] = useState(settings.LogAuth);
const protonSentinel = settings.HighSecurity.Value;
const api = useApi();
const [state, setState] = useState<{ logs: AuthLog[]; total: number }>(INITIAL_STATE);
const { page, onNext, onPrevious, onSelect } = usePaginationAsync(1);
const [loading, withLoading] = useLoading();
const [loadingRefresh, withLoadingRefresh] = useLoading();
const [loadingDownload, withLoadingDownload] = useLoading();
const [loadingWipe, withLoadingWipe] = useLoading();
const [error, setError] = useState(false);
const handleWipe = async () => {
await withLoadingWipe(api(clearLogs()));
setState(INITIAL_STATE);
};
const handleDownload = async () => {
const Logs = await getAllAuthenticationLogs(api);
const data = Logs.reduce(
(acc, { Description, Time, IP }) => {
acc.push(`${Description},${fromUnixTime(Time).toISOString()},${IP}`);
return acc;
},
[['Event', 'Time', 'IP'].join(',')]
);
const filename = 'logs.csv';
const csvString = data.join('\r\n');
const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8' });
downloadFile(blob, filename);
};
const confirmDisable = () => {
return new Promise<void>((resolve, reject) => {
createModal(
<ConfirmModal title={c('Title').t`Clear`} onConfirm={resolve} onClose={reject}>
<Alert className="mb-4" type="warning">{c('Warning')
.t`By disabling the logs, you will also clear your entire logs history. Are you sure you want to disable the logs?`}</Alert>
</ConfirmModal>
);
});
};
const handleLogAuth = async (newLogAuthState: SETTINGS_LOG_AUTH_STATE) => {
if (state.total > 0 && newLogAuthState === DISABLE) {
await confirmDisable();
}
await api(updateLogAuth(newLogAuthState));
setLogAuth(newLogAuthState);
if (newLogAuthState === DISABLE) {
setState(INITIAL_STATE);
}
};
const handleLogsChange = ({ target: { checked } }: ChangeEvent<HTMLInputElement>) => {
handleLogAuth(checked ? BASIC : DISABLE);
};
const handleAdvancedLogsChange = ({ target: { checked } }: ChangeEvent<HTMLInputElement>) => {
handleLogAuth(checked ? ADVANCED : BASIC);
};
// Handle updates from the event manager
useEffect(() => {
setLogAuth(settings.LogAuth);
}, [settings.LogAuth]);
const latestRef = useRef<any>();
const fetchAndSetState = async () => {
const latest = {};
latestRef.current = latest;
setError(false);
try {
const { Logs, Total } = await api<{ Logs: AuthLog[]; Total: number }>(
queryLogs({
Page: page - 1,
PageSize: 10,
})
);
if (latestRef.current !== latest) {
return;
}
setState({ logs: Logs, total: Total });
} catch (e: any) {
if (latestRef.current !== latest) {
return;
}
setError(true);
}
};
const handleWipeWithReload = async () => {
await withLoadingWipe(handleWipe());
await withLoadingRefresh(fetchAndSetState);
};
useEffect(() => {
withLoading(fetchAndSetState());
}, [page, protonSentinel]);
const BRAND_NAME_TWO = BRAND_NAME;
return (
<SettingsSectionWide>
<SettingsParagraph>
{c('Info')
.t`Logs include authentication attempts for all ${BRAND_NAME} services that use your ${BRAND_NAME_TWO} credentials.`}
</SettingsParagraph>
<SettingsLayout>
<SettingsLayoutLeft>
<label className="text-semibold" htmlFor="logs-toggle">
{c('Log preference').t`Enable authentication logs`}
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="pt-2">
<Toggle
id="logs-toggle"
checked={logAuth === BASIC || logAuth === ADVANCED}
onChange={handleLogsChange}
/>
</SettingsLayoutRight>
</SettingsLayout>
{logAuth !== DISABLE && (
<SettingsLayout>
<SettingsLayoutLeft>
<label className="text-semibold" htmlFor="advanced-logs-toggle">
<span className="mr-2">{c('Log preference').t`Enable advanced logs`}</span>
<Info
title={c('Tooltip')
.t`Enabling advanced logs records the IP address for each event in the security log.`}
/>
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="pt-2">
<Toggle
id="advanced-logs-toggle"
checked={logAuth === ADVANCED}
onChange={handleAdvancedLogsChange}
/>
</SettingsLayoutRight>
</SettingsLayout>
)}
<div className="flex flex-justify-space-between flex-align-items-start mt-8 mb-4">
{logAuth !== DISABLE && (
<div className="mb-2">
<Button
shape="outline"
className="mr-4 inline-flex flex-align-items-center"
loading={loadingRefresh}
onClick={() => withLoadingRefresh(wait(1000).then(fetchAndSetState))}
title={c('Action').t`Reload`}
>
<Icon name="arrow-rotate-right" className="mr-2" />
<span>{c('Action').t`Reload`}</span>
</Button>
{state.logs.length ? (
<WipeLogsButton className="mr-4" onWipe={handleWipeWithReload} loading={loadingWipe} />
) : null}
{state.logs.length ? (
<Button
shape="outline"
className="mr-4"
onClick={() => withLoadingDownload(handleDownload())}
loading={loadingDownload}
>{c('Action').t`Download`}</Button>
) : null}
</div>
)}
<div className="mb-2">
<Pagination
onNext={onNext}
onPrevious={onPrevious}
onSelect={onSelect}
total={state.total}
page={page}
limit={PAGE_SIZE}
/>
</div>
</div>
<LogsTable
logs={state.logs}
logAuth={logAuth}
protonSentinel={protonSentinel}
loading={loading || loadingRefresh}
error={error}
/>
</SettingsSectionWide>
);
};
export default LogsSection;
| 6,432
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/LogsTable.tsx
|
import { c } from 'ttag';
import { AuthLog } from '@proton/shared/lib/authlog';
import { SETTINGS_LOG_AUTH_STATE, SETTINGS_PROTON_SENTINEL_STATE } from '@proton/shared/lib/interfaces';
import isTruthy from '@proton/utils/isTruthy';
import { Alert, Info, Table, TableBody, TableCell, TableHeader, TableRow, Time } from '../../components';
import { useFeature } from '../../hooks';
import { FeatureCode } from '../features';
import AppVersionCell from './AppVersionCell';
import DeviceCell from './DeviceCell';
import EventCell from './EventCell';
import IPCell from './IPCell';
import LocationCell from './LocationCell';
import ProtectionCell from './ProtectionCell';
const { ADVANCED, DISABLE } = SETTINGS_LOG_AUTH_STATE;
const { ENABLED } = SETTINGS_PROTON_SENTINEL_STATE;
interface Props {
logs: AuthLog[];
logAuth: SETTINGS_LOG_AUTH_STATE;
protonSentinel: SETTINGS_PROTON_SENTINEL_STATE;
loading: boolean;
error: boolean;
}
const LogsTable = ({ logs, logAuth, protonSentinel, loading, error }: Props) => {
const isAuthLogAdvanced = logAuth === ADVANCED;
const isProtonSentinelEnabled = protonSentinel === ENABLED;
const isProtonSentinelAuthLogUpsellEnabled =
useFeature(FeatureCode.ProtonSentinelAuthLogUpsell).feature?.Value === true;
if (logAuth === DISABLE) {
return (
<Alert className="mb-4">{c('Info')
.t`You can enable authentication sign in to see when your account is accessed, and from which IP. We will record the IP address that accesses the account and the time, as well as failed attempts.`}</Alert>
);
}
if (!loading && !logs.length) {
return <Alert className="mb-4">{c('Info').t`No logs yet.`}</Alert>;
}
if (!loading && error) {
return <Alert className="mb-4" type="error">{c('Info').t`Failed to fetch logs.`}</Alert>;
}
const isUnavailableClass = (isAdvancedLogOnly = true) => {
if ((isAdvancedLogOnly && !isAuthLogAdvanced) || !isProtonSentinelEnabled) {
return 'bg-weak';
}
return '';
};
if (isProtonSentinelAuthLogUpsellEnabled) {
const headerCells = [
{
className: 'text-left',
header: c('Header').t`Time`,
},
{
className: isAuthLogAdvanced || isProtonSentinelEnabled ? 'w-1/6' : 'w-1/5',
header: c('Header').t`Event`,
},
{
header: c('Header').t`App version`,
},
{
className: isAuthLogAdvanced ? 'w-1/6' : 'bg-weak w-custom',
style: { '--w-custom': '5%' },
header: 'IP',
},
{
className: isUnavailableClass(),
header: c('Header').t`Location`,
info: c('Tooltip').t`An approximate location of the IP address`,
},
{
className:
isAuthLogAdvanced && isProtonSentinelEnabled
? `${isUnavailableClass()}`
: `${isUnavailableClass()} w-1/10`,
header: 'ISP',
info: c('Tooltip').t`The Internet Service Provider of the IP address`,
},
{
className: isProtonSentinelEnabled ? isUnavailableClass(false) : `${isUnavailableClass(false)} w-5`,
header: c('Header').t`Device`,
info: c('Tooltip').t`Device information such as operating system`,
},
{
className: isUnavailableClass(false),
header: c('Header').t`Protection`,
info: c('Tooltip').t`Any protection applied to suspicious activity`,
},
].filter(isTruthy);
return (
<Table responsive="cards">
<TableHeader>
<TableRow>
{headerCells.map(({ className, header, info }) => (
<TableCell key={header} className={className} type="header">
<div className="flex flex-align-items-center flex-nowrap">
{header}
{info && <Info className="ml-2 flex-item-noshrink" title={info} />}
</div>
</TableCell>
))}
</TableRow>
</TableHeader>
<TableBody loading={loading} colSpan={headerCells.length}>
{logs.map(
(
{
Time: time,
AppVersion,
Description,
IP,
InternetProvider,
Location,
Device,
ProtectionDesc,
Protection,
Status,
},
index
) => {
const key = index.toString();
const cells = [
{
label: c('Header').t`Time`,
className: 'text-left',
content: (
<Time key={key} format="PPp">
{time}
</Time>
),
},
{
label: c('Header').t`Event`,
content: <EventCell description={Description} status={Status} />,
},
{
label: c('Header').t`App version`,
content: <AppVersionCell appVersion={AppVersion} />,
},
{
label: 'IP',
className: isAuthLogAdvanced ? '' : 'bg-weak hidden lg:table-cell text-center',
colSpan: (() => {
if (!isAuthLogAdvanced) {
if (isProtonSentinelEnabled) {
return 3;
}
return 5;
}
return 1;
})(),
content: (
<IPCell
isAuthLogAdvanced={isAuthLogAdvanced}
isProtonSentinelEnabled={isProtonSentinelEnabled}
ip={IP}
firstRow={index === 0}
/>
),
},
isAuthLogAdvanced && {
label: c('Header').t`Location`,
className: `${isUnavailableClass()} ${
!isAuthLogAdvanced || !isProtonSentinelEnabled ? 'text-left lg:text-center' : ''
}`,
colSpan: isProtonSentinelEnabled ? 1 : 4,
content: (
<LocationCell
isProtonSentinelEnabled={isProtonSentinelEnabled}
location={Location}
firstRow={index === 0}
/>
),
},
isAuthLogAdvanced &&
isProtonSentinelEnabled && {
label: 'ISP',
content: <span className="flex-item-fluid">{InternetProvider || '-'}</span>,
},
isProtonSentinelEnabled && {
label: c('Header').t`Device`,
content: <DeviceCell device={Device} />,
},
isProtonSentinelEnabled && {
label: c('Header').t`Protection`,
content: <ProtectionCell protection={Protection} protectionDesc={ProtectionDesc} />,
},
].filter(isTruthy);
return (
<TableRow key={key}>
{cells.map(({ label, className, colSpan, content }) => (
<TableCell key={label} label={label} className={className} colSpan={colSpan}>
{content}
</TableCell>
))}
</TableRow>
);
}
)}
</TableBody>
</Table>
);
}
const headerCells = [
{
header: c('Header').t`Event`,
},
logAuth === ADVANCED && {
header: 'IP',
},
protonSentinel === ENABLED && {
header: c('Header').t`Protection`,
},
protonSentinel === ENABLED && {
header: c('Header').t`Device`,
},
{
header: c('Header').t`App version`,
className: 'text-right',
},
{
header: c('Header').t`Time`,
className: 'text-right',
},
].filter(isTruthy);
return (
<Table responsive="cards">
<TableHeader>
<TableRow>
{headerCells.map(({ header, className }) => (
<TableCell key={header} type="header" className={className}>
{header}
</TableCell>
))}
</TableRow>
</TableHeader>
<TableBody loading={loading} colSpan={headerCells.length}>
{logs.map(
(
{ Time: time, AppVersion, Description, IP, Device, ProtectionDesc, Protection, Status },
index
) => {
const key = index.toString();
const cells = [
{
label: c('Header').t`Event`,
content: <EventCell description={Description} status={Status} />,
},
logAuth === ADVANCED && {
label: 'IP',
content: <IPCell ip={IP} isAuthLogAdvanced={isAuthLogAdvanced} />,
},
protonSentinel === ENABLED && {
label: c('Header').t`Protection`,
content: <ProtectionCell protection={Protection} protectionDesc={ProtectionDesc} />,
},
protonSentinel === ENABLED && {
label: c('Header').t`Device`,
content: <DeviceCell device={Device} />,
},
{
label: c('Header').t`App version`,
className: 'text-left lg:text-right',
content: <AppVersionCell appVersion={AppVersion} />,
},
{
label: c('Header').t`Time`,
className: 'text-left lg:text-right',
content: <Time format="PPp">{time}</Time>,
},
].filter(isTruthy);
return (
<TableRow key={key}>
{cells.map(({ label, content, className }) => (
<TableCell key={label} label={label} className={className}>
{content}
</TableCell>
))}
</TableRow>
);
}
)}
</TableBody>
</Table>
);
};
export default LogsTable;
| 6,433
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/ProtectionCell.tsx
|
import { ProtectionType } from '@proton/shared/lib/authlog';
import { PROTON_SENTINEL_NAME } from '@proton/shared/lib/constants';
import { Icon, Tooltip } from '../../components';
type Props = {
protection?: ProtectionType | null;
protectionDesc?: string | null;
};
const ProtectionTooltip = () => {
return (
<Tooltip title={PROTON_SENTINEL_NAME} openDelay={0} closeDelay={150} longTapDelay={0}>
<Icon className="align-text-bottom color-primary" name="shield-filled" />
</Tooltip>
);
};
const ProtectionCell = ({ protection, protectionDesc }: Props) => {
const protectionTooltip = protection ? <ProtectionTooltip /> : null;
if (protection === ProtectionType.OK) {
return protectionTooltip;
}
return (
<>
<span className="flex-item-noshrink mr-2">{protectionTooltip}</span>
<span className="flex-item-fluid">{protectionDesc || '-'}</span>
</>
);
};
export default ProtectionCell;
| 6,434
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/WipeLogsButton.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Alert, ConfirmModal } from '../../components';
import { useModals } from '../../hooks';
interface Props {
onWipe: () => Promise<void>;
className?: string;
loading?: boolean;
}
const WipeLogsButton = ({ onWipe, className, loading }: Props) => {
const { createModal } = useModals();
const handleOpenModal = () => {
createModal(
<ConfirmModal
title={c('Title').t`Delete logs`}
onConfirm={onWipe}
confirm={<Button color="danger" type="submit">{c('Action').t`Delete`}</Button>}
>
<Alert className="mb-4" type="error">{c('Info')
.t`Are you sure you want to permanently delete all your logs?`}</Alert>
</ConfirmModal>
);
};
return (
<Button shape="outline" className={className} loading={loading} onClick={handleOpenModal}>{c('Action')
.t`Wipe`}</Button>
);
};
export default WipeLogsButton;
| 6,435
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/helper.ts
|
import queryPages from '@proton/shared/lib/api/helpers/queryPages';
import { queryLogs } from '@proton/shared/lib/api/logs';
import { AuthLog } from '@proton/shared/lib/authlog';
import { Api } from '@proton/shared/lib/interfaces';
export const getAllAuthenticationLogs = (api: Api) => {
return queryPages(
(Page, PageSize) => {
return api<{ Logs: AuthLog[]; Total: number }>(
queryLogs({
Page,
PageSize,
})
);
},
{ pageSize: 150 }
).then((pages) => {
return pages.flatMap(({ Logs }) => Logs);
});
};
| 6,436
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/logs/index.ts
|
export { default as WipeLogsButton } from './WipeLogsButton';
export { default as LogsSection } from './LogsSection';
export { default as LogsTable } from './LogsTable';
| 6,437
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mail/MailComposerModeModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { useLoading } from '@proton/hooks';
import { updateComposerMode } from '@proton/shared/lib/api/mailSettings';
import { COMPOSER_MODE, DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/mailSettings';
import { ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../components';
import { useApi, useEventManager, useMailSettings, useNotifications } from '../../hooks';
import ComposerModeCards from '../layouts/ComposerModeCards';
import './ModalSettingsLayoutCards.scss';
const MailComposerModeModal = (props: ModalProps) => {
const api = useApi();
const { call } = useEventManager();
const [{ ComposerMode } = DEFAULT_MAILSETTINGS] = useMailSettings();
const [loading, withLoading] = useLoading();
const { createNotification } = useNotifications();
const title = c('Title').t`Composer mode`;
const { onClose } = props;
const handleChangeComposerMode = async (mode: COMPOSER_MODE) => {
await api(updateComposerMode(mode));
await call();
createNotification({ text: c('Success').t`Preference saved` });
};
const handleSubmit = () => onClose?.();
return (
<ModalTwo {...props}>
<ModalTwoHeader title={title} />
<ModalTwoContent>
<div className="flex flex-nowrap mb-4 on-mobile-flex-column flex-column">
<span className="mb-4" id="composerMode_desc">
{c('Label').t`Select how your composer opens by default.`}
</span>
<ComposerModeCards
describedByID="composerMode_desc"
composerMode={ComposerMode}
onChange={(value) => withLoading(handleChangeComposerMode(value))}
loading={loading}
liClassName="w-full"
className="layoutCards-two-per-row"
/>
</div>
</ModalTwoContent>
<ModalTwoFooter>
<Button className="ml-auto" color="norm" onClick={handleSubmit}>{c('Action').t`OK`}</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default MailComposerModeModal;
| 6,438
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mail/MailDensityModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { useLoading } from '@proton/hooks';
import { updateDensity } from '@proton/shared/lib/api/settings';
import { DENSITY } from '@proton/shared/lib/constants';
import { ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../components';
import { useApi, useEventManager, useNotifications, useUserSettings } from '../../hooks';
import DensityRadiosCards from '../layouts/DensityRadiosCards';
import './ModalSettingsLayoutCards.scss';
const MailDensityModal = (props: ModalProps) => {
const api = useApi();
const { call } = useEventManager();
const [{ Density }] = useUserSettings();
const [loading, withLoading] = useLoading();
const { createNotification } = useNotifications();
const title = c('Title').t`Mailbox density`;
const { onClose } = props;
const handleChangeDensity = async (density: DENSITY) => {
await api(updateDensity(density));
await call();
createNotification({ text: c('Success').t`Preference saved` });
};
const handleSubmit = () => onClose?.();
return (
<ModalTwo {...props}>
<ModalTwoHeader title={title} />
<ModalTwoContent>
<div className="flex flex-nowrap mb-4 on-mobile-flex-column flex-column">
<span className="mb-4" id="densityMode_desc">
{c('Label').t`Select what your list of messages looks like by default.`}
</span>
<DensityRadiosCards
density={Density}
describedByID="densityMode_desc"
onChange={(value) => withLoading(handleChangeDensity(value))}
loading={loading}
liClassName="w-full"
className="layoutCards-two-per-row"
/>
</div>
</ModalTwoContent>
<ModalTwoFooter>
<Button className="ml-auto" color="norm" onClick={handleSubmit}>{c('Action').t`OK`}</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default MailDensityModal;
| 6,439
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mail/MailShortcutsModal.scss
|
@import '~@proton/styles/scss/lib';
.shortcut-modal {
// Special case otherwise shortcuts are not properly displayed
--size: #{rem(700)};
kbd {
word-spacing: rem(-3);
}
}
| 6,440
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mail/MailShortcutsModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { MAIL_APP_NAME } from '@proton/shared/lib/constants';
import { DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/mailSettings';
import { getShortcuts } from '@proton/shared/lib/shortcuts/mail';
import clsx from '@proton/utils/clsx';
import {
Alert,
Field,
Label,
ModalProps,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
Row,
ShortcutsSectionView,
} from '../../components';
import { useMailSettings } from '../../hooks';
import ShortcutsToggle from '../general/ShortcutsToggle';
import './MailShortcutsModal.scss';
const MailShortCutsModal = (props: ModalProps) => {
const title = c('Title').t`${MAIL_APP_NAME} Keyboard Shortcuts`;
const [{ Shortcuts } = DEFAULT_MAILSETTINGS] = useMailSettings();
const mailShortcuts = getShortcuts();
const alwaysOnSections = mailShortcuts.filter((section) => section.alwaysActive);
const shortcutEnabledSections = mailShortcuts.filter((section) => !section.alwaysActive);
const { onClose } = props;
return (
<ModalTwo className="shortcut-modal" {...props}>
<ModalTwoHeader title={title} />
<ModalTwoContent>
<Alert className="mb-4">
{c('Info')
.t`Basic navigation and actions remain available regardless of keyboard shortcuts being active or not in the settings.`}
</Alert>
<div className="list-columns md:column-2 gap-8">
{alwaysOnSections.map((section) => {
return <ShortcutsSectionView key={section.name} {...section} />;
})}
</div>
<hr className="my-8 border-bottom" />
<Row className="mb-8">
<Label htmlFor="toggle-shortcuts" className="mr-4">{c('Label').t`Keyboard shortcuts`}</Label>
<Field className="pt-2">
<ShortcutsToggle id="toggle-shortcuts" />
</Field>
</Row>
<div className={clsx('list-columns md:column-2 gap-8', !Shortcuts && 'opacity-50')}>
{shortcutEnabledSections.map((section) => {
return <ShortcutsSectionView key={section.name} {...section} />;
})}
</div>
</ModalTwoContent>
<ModalTwoFooter>
<Button className="ml-auto" onClick={onClose}>{c('Action').t`Close`}</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default MailShortCutsModal;
| 6,441
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mail/MailViewLayoutModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { useLoading } from '@proton/hooks';
import { updateViewLayout } from '@proton/shared/lib/api/mailSettings';
import { DEFAULT_MAILSETTINGS, VIEW_LAYOUT } from '@proton/shared/lib/mail/mailSettings';
import { ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../components';
import { useApi, useEventManager, useMailSettings, useNotifications } from '../../hooks';
import ViewLayoutCards from '../layouts/ViewLayoutCards';
import './ModalSettingsLayoutCards.scss';
const MailViewLayoutModal = (props: ModalProps) => {
const api = useApi();
const { call } = useEventManager();
const [{ ViewLayout } = DEFAULT_MAILSETTINGS] = useMailSettings();
const [loading, withLoading] = useLoading();
const { createNotification } = useNotifications();
const title = c('Title').t`Mailbox layout`;
const { onClose } = props;
const handleChangeViewLayout = async (layout: VIEW_LAYOUT) => {
await api(updateViewLayout(layout));
await call();
createNotification({ text: c('Success').t`Preference saved` });
};
const handleSubmit = () => onClose?.();
return (
<ModalTwo {...props}>
<ModalTwoHeader title={title} />
<ModalTwoContent>
<div className="flex flex-nowrap mb-4 on-mobile-flex-column flex-column">
<span className="mb-4" id="layoutMode_desc">
{c('Label').t`Select what your mailbox looks like by default.`}
</span>
<ViewLayoutCards
describedByID="layoutMode_desc"
viewLayout={ViewLayout}
onChange={(value) => withLoading(handleChangeViewLayout(value))}
loading={loading}
liClassName="w-full"
className="layoutCards-two-per-row"
/>
</div>
</ModalTwoContent>
<ModalTwoFooter>
<Button className="ml-auto" color="norm" onClick={handleSubmit}>{c('Action').t`OK`}</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default MailViewLayoutModal;
| 6,442
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mail/ModalSettingsLayoutCards.scss
|
@import '~@proton/styles/scss/lib';
.layoutCards-two-per-row {
&#{&} {
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 1em;
.layout-card-button {
margin: 0;
inline-size: 100%;
&#{&} {
background-color: transparent;
}
}
.layout-card-image {
inline-size: 100%;
}
@include media('<=xsmall') {
grid-template-columns: 1fr;
}
}
}
| 6,443
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mail/index.ts
|
export { default as MailShortcutsModal } from './MailShortcutsModal';
export { default as MailDensityModal } from './MailDensityModal';
export { default as MailViewLayoutModal } from './MailViewLayoutModal';
export { default as MailComposerModeModal } from './MailComposerModeModal';
| 6,444
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/ChangeMemberPasswordModal.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import {
useAuthentication,
useBeforeUnload,
useEventManager,
useGetAddressKeys,
useNotifications,
} from '@proton/components/hooks';
import useApi from '@proton/components/hooks/useApi';
import { getAllAddresses } from '@proton/shared/lib/api/addresses';
import { updatePrivateKeyRoute } from '@proton/shared/lib/api/keys';
import { authMember } from '@proton/shared/lib/api/members';
import { getOrganizationKeys } from '@proton/shared/lib/api/organization';
import { disable2FA } from '@proton/shared/lib/api/settings';
import { getUser, lockSensitiveSettings } from '@proton/shared/lib/api/user';
import { withUIDHeaders } from '@proton/shared/lib/fetch/headers';
import {
confirmPasswordValidator,
passwordLengthValidator,
requiredValidator,
} from '@proton/shared/lib/helpers/formValidators';
import { Address, Api, OrganizationKey, User } from '@proton/shared/lib/interfaces';
import { Member } from '@proton/shared/lib/interfaces/Member';
import {
generateKeySaltAndPassphrase,
getCachedOrganizationKey,
getDecryptedUserKeysHelper,
} from '@proton/shared/lib/keys';
import { getUpdateKeysPayload } from '@proton/shared/lib/keys/changePassword';
import { formatUser } from '@proton/shared/lib/models/userModel';
import { Credentials, srpVerify } from '@proton/shared/lib/srp';
import noop from '@proton/utils/noop';
import {
Form,
InputFieldTwo,
ModalTwo as Modal,
ModalTwoContent as ModalContent,
ModalTwoFooter as ModalFooter,
ModalTwoHeader as ModalHeader,
ModalProps,
PasswordInputTwo,
useFormErrors,
} from '../../components';
import { GenericError } from '../error';
import { AuthModal } from '../password';
interface Inputs {
newPassword: string;
confirmPassword: string;
}
interface Props extends ModalProps {
member: Member;
}
const ChangeMemberPasswordModal = ({ member, onClose, ...rest }: Props) => {
const normalApi = useApi();
const silentApi = <T,>(config: any) => normalApi<T>({ ...config, silence: true });
const [data, setData] = useState<{ UID: string; credentials: Credentials }>();
const authentication = useAuthentication();
const api = useApi();
const { call, stop, start } = useEventManager();
const { createNotification } = useNotifications();
const getAddressKeys = useGetAddressKeys();
const { validator, onFormSubmit } = useFormErrors();
const lockAndClose = (memberApi?: Api) => {
if (memberApi) {
void memberApi(lockSensitiveSettings());
}
void api(lockSensitiveSettings());
onClose?.();
};
const [inputs, setInputs] = useState<Inputs>({
newPassword: '',
confirmPassword: '',
});
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState(false);
useBeforeUnload(loading ? c('Info').t`By leaving now, changes may not be saved` : '');
const setPartialInput = (object: Partial<Inputs>) => setInputs((oldState) => ({ ...oldState, ...object }));
const newPasswordError = passwordLengthValidator(inputs.newPassword);
const confirmPasswordError =
passwordLengthValidator(inputs.confirmPassword) ||
confirmPasswordValidator(inputs.newPassword, inputs.confirmPassword);
const validateNewPasswords = () => {
if (newPasswordError || confirmPasswordError) {
throw new Error('Password error');
}
};
const notifySuccess = () => {
createNotification({ text: c('Success').t`Password updated` });
};
if (!data) {
return (
<AuthModal
config={authMember(member.ID, { Unlock: true })}
{...rest}
onCancel={onClose}
onSuccess={async ({ credentials, response }) => {
const data = await response.json();
const UID = data?.UID;
if (!UID) {
throw new Error('Failed to get auth data');
}
setData({ UID, credentials });
}}
/>
);
}
if (error) {
const handleClose = () => {
lockAndClose();
};
return (
<Modal {...rest} onClose={handleClose}>
<ModalHeader title={c('Title').t`Change password`} />
<ModalContent>
<GenericError />
</ModalContent>
<ModalFooter>
<div />
<Button color="norm" onClick={handleClose}>
{c('Action').t`OK`}
</Button>
</ModalFooter>
</Modal>
);
}
const getAddressesWithKeysList = (addresses: Address[]) => {
return Promise.all(
addresses.map(async (address) => {
return {
address,
keys: await getAddressKeys(address.ID),
};
})
);
};
const changeMemberPassword = async ({ memberApi, credentials }: { memberApi: Api; credentials: Credentials }) => {
const keyPassword = authentication.getPassword();
const User = await memberApi<{ User: User }>(getUser()).then(({ User }) => formatUser(User));
const [addresses, userKeysList, organizationKey] = await Promise.all([
getAllAddresses(memberApi),
getDecryptedUserKeysHelper(User, keyPassword),
User.isAdmin
? getCachedOrganizationKey({
keyPassword,
Key: await memberApi<OrganizationKey>(getOrganizationKeys()),
})
: undefined,
]);
if (userKeysList.length === 0) {
throw new Error('No user keys');
}
validateNewPasswords();
const { passphrase: newKeyPassword, salt: keySalt } = await generateKeySaltAndPassphrase(inputs.newPassword);
const addressesWithKeys = await getAddressesWithKeysList(addresses);
const updateKeysPayload = await getUpdateKeysPayload(
addressesWithKeys,
userKeysList,
organizationKey?.privateKey,
newKeyPassword,
keySalt
);
if (member['2faStatus']) {
await srpVerify({
api: memberApi,
credentials,
config: disable2FA(),
});
}
await srpVerify({
api: memberApi,
credentials: {
password: inputs.newPassword,
},
config: updatePrivateKeyRoute(updateKeysPayload),
});
};
const onSubmit = async () => {
if (!onFormSubmit()) {
return;
}
try {
stop();
setLoading(true);
const { UID, credentials } = data;
const memberApi = <T,>(config: any) => silentApi<T>(withUIDHeaders(UID, config));
await changeMemberPassword({ memberApi, credentials });
await call();
notifySuccess();
lockAndClose(memberApi);
} catch (e: any) {
setLoading(false);
setError(true);
} finally {
start();
}
};
const handleClose = loading ? noop : () => lockAndClose();
const userName = (
<b key="user" className="text-break">
{member.Name} ({(member?.Addresses || [])[0]?.Email ?? ''})
</b>
);
return (
<Modal as={Form} onClose={handleClose} {...rest} onSubmit={onSubmit}>
<ModalHeader title={c('Title').t`Change password`} />
<ModalContent>
<div className="mb-4">{c('Info').jt`Enter new password for user ${userName}.`}</div>
<InputFieldTwo
id="newPassword"
label={c('Label').t`User's new password`}
error={validator([
requiredValidator(inputs.newPassword),
passwordLengthValidator(inputs.newPassword),
])}
as={PasswordInputTwo}
autoFocus
autoComplete="new-password"
value={inputs.newPassword}
onValue={(value: string) => setPartialInput({ newPassword: value })}
disabled={loading}
/>
<InputFieldTwo
id="confirmPassword"
label={c('Label').t`Confirm new password`}
error={validator([
requiredValidator(inputs.confirmPassword),
passwordLengthValidator(inputs.confirmPassword),
confirmPasswordValidator(inputs.newPassword, inputs.confirmPassword),
])}
as={PasswordInputTwo}
autoComplete="new-password"
value={inputs.confirmPassword}
onValue={(value: string) => setPartialInput({ confirmPassword: value })}
disabled={loading}
/>
</ModalContent>
<ModalFooter>
<Button onClick={handleClose} disabled={loading}>
{c('Action').t`Cancel`}
</Button>
<Button loading={loading} type="submit" color="norm">
{c('Action').t`Change password`}
</Button>
</ModalFooter>
</Modal>
);
};
export default ChangeMemberPasswordModal;
| 6,445
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/InviteUserCreateSubUserModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { APP_NAMES, BRAND_NAME, PLAN_NAMES } from '@proton/shared/lib/constants';
import { CachedOrganizationKey, Domain, Organization } from '@proton/shared/lib/interfaces';
import { ModalStateProps, Prompt, SubUserCreateModal, Tooltip, useDomains, useModalState } from '../..';
interface Props extends ModalStateProps {
organization: Organization;
verifiedDomains: Domain[];
organizationKey?: CachedOrganizationKey;
onInviteUser: () => void;
app: APP_NAMES;
}
interface ButtonProps {
onClick: () => void;
}
const AddUserButton = ({ onClick }: ButtonProps) => {
const [domains = []] = useDomains();
if (domains.length === 0) {
return (
<Tooltip
title={c('familyOffer_2023:Family plan')
.t`You need to configure a custom domain before creating a new user.`}
>
<div className="w-full">
<Button disabled fullWidth>{c('familyOffer_2023:Action').t`Create a new user`}</Button>
</div>
</Tooltip>
);
}
return <Button onClick={onClick} fullWidth>{c('familyOffer_2023:Action').t`Create a new user`}</Button>;
};
interface InviteButtonProps {
organization: Organization;
}
const InviteProtonUserButton = ({ onClick, organization }: ButtonProps & InviteButtonProps) => {
if (organization && organization.InvitationsRemaining === 0) {
return (
<Tooltip
title={c('familyOffer_2023:Family plan')
.t`You have reached the limit of 10 accepted invitations in 6 months. The button will become clickable when you can invite additional users.`}
>
<div className="w-full">
<Button disabled fullWidth>{c('familyOffer_2023:Action')
.t`Invite an existing ${BRAND_NAME} user`}</Button>
</div>
</Tooltip>
);
}
return (
<Button fullWidth onClick={onClick} color="norm">{c('familyOffer_2023:Action')
.t`Invite an existing ${BRAND_NAME} user`}</Button>
);
};
const InviteUserCreateSubUserModal = ({
organization,
verifiedDomains,
organizationKey,
onInviteUser,
app,
...modalState
}: Props) => {
const [subUserCreateModalProps, setSubUserCreateModalOpen, renderSubUserCreateModal] = useModalState();
const handleAddUser = () => {
setSubUserCreateModalOpen(true);
};
const handleInviteUser = () => {
modalState.onClose();
onInviteUser();
};
return (
<>
<Prompt
title={c('familyOffer_2023:Title').t`Add a user to your ${PLAN_NAMES.visionary2022} account`}
buttons={[
<InviteProtonUserButton onClick={handleInviteUser} organization={organization} />,
<AddUserButton onClick={handleAddUser} />,
<Button fullWidth onClick={modalState.onClose} shape="ghost">{c('Action').t`Cancel`}</Button>,
]}
{...modalState}
>
<p>{c('familyOffer_2023:Info').t`To create a new user, a configured custom domain is required.`}</p>
</Prompt>
{renderSubUserCreateModal && organizationKey && verifiedDomains?.length > 0 && (
<SubUserCreateModal
organization={organization}
organizationKey={organizationKey}
verifiedDomains={verifiedDomains}
{...subUserCreateModalProps}
onClose={() => modalState.onClose()}
app={app}
/>
)}
</>
);
};
export default InviteUserCreateSubUserModal;
| 6,446
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/LoginMemberModal.tsx
|
import { useMemo, useState } from 'react';
import { c } from 'ttag';
import { Button, ButtonLike } from '@proton/atoms';
import { useAuthentication } from '@proton/components/hooks';
import useApi from '@proton/components/hooks/useApi';
import { revoke } from '@proton/shared/lib/api/auth';
import { authMember } from '@proton/shared/lib/api/members';
import { getUser } from '@proton/shared/lib/api/user';
import { getAppHref } from '@proton/shared/lib/apps/helper';
import { getSlugFromApp } from '@proton/shared/lib/apps/slugHelper';
import {
maybeResumeSessionByUser,
persistSessionWithPassword,
} from '@proton/shared/lib/authentication/persistedSessionHelper';
import { APPS, APP_NAMES, SSO_PATHS } from '@proton/shared/lib/constants';
import { withUIDHeaders } from '@proton/shared/lib/fetch/headers';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { User } from '@proton/shared/lib/interfaces';
import { CachedOrganizationKey, Organization } from '@proton/shared/lib/interfaces';
import { Member } from '@proton/shared/lib/interfaces/Member';
import { getOrganizationKeyInfo } from '@proton/shared/lib/organization/helper';
import noop from '@proton/utils/noop';
import { LearnMore, Prompt, PromptProps } from '../../components';
import { AuthModal } from '../password';
export const validateMemberLogin = (
organization: Organization | undefined,
organizationKey: CachedOrganizationKey | undefined
) => {
const organizationKeyInfo = getOrganizationKeyInfo(organization, organizationKey);
if (organizationKeyInfo.userNeedsToActivateKey) {
return c('Error').t`The organization key must be activated first.`;
}
if (organizationKeyInfo.userNeedsToReactivateKey) {
return c('Error').t`Permission denied, administrator privileges have been restricted.`;
}
if (!organizationKey?.privateKey) {
return c('Error').t`Organization key is not decrypted.`;
}
};
interface Props extends Omit<PromptProps, 'title' | 'children' | 'buttons'> {
member: Member;
app: APP_NAMES;
}
const LoginMemberModal = ({ app, member, onClose, ...rest }: Props) => {
const normalApi = useApi();
const silentApi = <T,>(config: any) => normalApi<T>({ ...config, silence: true });
const [authed, setAuthed] = useState(false);
const [data, setData] = useState<{ LocalID: number }>();
const authentication = useAuthentication();
const switchUrl = useMemo(() => {
const href = getAppHref(SSO_PATHS.SWITCH, APPS.PROTONACCOUNT);
const search = `?product=${getSlugFromApp(app || APPS.PROTONMAIL)}`;
return `${href}${search}`;
}, [app]);
if (!authed || !data) {
const handleData = async (data: { UID: string; LocalID: number }) => {
const UID = data?.UID;
const LocalID = data?.LocalID;
if (!UID || !LocalID) {
throw new Error('Failed to get auth data');
}
const memberApi = <T,>(config: any) => silentApi<T>(withUIDHeaders(UID, config));
const User = await memberApi<{ User: User }>(getUser()).then(({ User }) => User);
const validatedSession = await maybeResumeSessionByUser(silentApi, User);
if (validatedSession) {
memberApi(revoke()).catch(noop);
return validatedSession.LocalID;
}
await persistSessionWithPassword({
api: memberApi,
keyPassword: authentication.getPassword(),
User,
LocalID,
UID,
persistent: authentication.getPersistent(),
trusted: false,
});
return LocalID;
};
return (
<AuthModal
config={authMember(member.ID)}
{...rest}
onCancel={onClose}
onSuccess={async ({ response }) => {
const data = await response.json();
const LocalID = await handleData(data);
setData({ LocalID });
setAuthed(true);
}}
/>
);
}
const memberAddress = <b key="member">{member.Addresses?.[0].Email || member.Name}</b>;
return (
<Prompt
title={c('Title').t`Signed in to member account`}
buttons={[
<ButtonLike as="a" color="norm" target="_blank" href={switchUrl} onClick={onClose}>
{c('Action').t`Switch account`}
</ButtonLike>,
<Button color="weak" onClick={onClose}>
{c('Action').t`Close`}
</Button>,
]}
onClose={onClose}
{...rest}
>
<div className="mb-4 text-break">{c('Info').jt`You are signed in to the account ${memberAddress}.`}</div>
<div>
{c('Info').t`You can now access and manage the account as an administrator.`}{' '}
<LearnMore url={getKnowledgeBaseUrl('/manage-public-users-organization')} />
</div>
</Prompt>
);
};
export default LoginMemberModal;
| 6,447
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/MemberActions.tsx
|
import { c } from 'ttag';
import { UserManagementMode } from '@proton/components/containers/members/types';
import { useLoading } from '@proton/hooks';
import { APPS, MEMBER_PRIVATE, MEMBER_TYPE } from '@proton/shared/lib/constants';
import { hasOrganizationSetup, hasOrganizationSetupWithKeys } from '@proton/shared/lib/helpers/organization';
import { CachedOrganizationKey, Member, Organization, PartialMemberAddress } from '@proton/shared/lib/interfaces';
import isTruthy from '@proton/utils/isTruthy';
import { useConfig } from '../..';
import { DropdownActions } from '../../components';
interface Props {
member: Member;
onLogin: (member: Member) => void;
onChangePassword: (member: Member) => void;
onEdit: (member: Member) => void;
onDelete: (member: Member) => void;
onRevoke: (member: Member) => Promise<void>;
addresses: PartialMemberAddress[] | undefined;
organization: Organization;
organizationKey: CachedOrganizationKey | undefined;
mode: UserManagementMode;
}
const MemberActions = ({
member,
onEdit,
onDelete,
onLogin,
onChangePassword,
onRevoke,
addresses = [],
organization,
mode,
}: Props) => {
const { APP_NAME } = useConfig();
const [loading, withLoading] = useLoading();
const hasSetupOrganizationWithKeys = hasOrganizationSetupWithKeys(organization);
const hasSetupOrganization = hasOrganizationSetup(organization);
const canDelete = !member.Self;
const canEdit = hasSetupOrganization || hasSetupOrganizationWithKeys;
const canRevokeSessions =
hasSetupOrganizationWithKeys &&
!member.Self &&
member.Type === MEMBER_TYPE.MANAGED &&
mode === UserManagementMode.DEFAULT;
const canLogin =
APP_NAME !== APPS.PROTONVPN_SETTINGS &&
hasSetupOrganizationWithKeys &&
!member.Self &&
member.Private === MEMBER_PRIVATE.READABLE &&
member.Keys.length > 0 &&
addresses.length > 0;
const canChangePassword =
hasSetupOrganizationWithKeys &&
!member.Self &&
member.Private === MEMBER_PRIVATE.READABLE &&
member.Keys.length > 0 &&
addresses.length > 0;
const list = [
canEdit && {
text: c('Member action').t`Edit`,
onClick: () => {
onEdit(member);
},
},
canLogin && {
text: c('Member action').t`Sign in`,
onClick: () => {
// Add Addresses to member, missing when updated through event loop
onLogin({ ...member, Addresses: addresses });
},
},
canChangePassword && {
text: c('Member action').t`Change password`,
onClick: () => {
// Add Addresses to member, missing when updated through event loop
onChangePassword({ ...member, Addresses: addresses });
},
},
canRevokeSessions && {
text: c('Member action').t`Revoke sessions`,
onClick: () => {
void withLoading(onRevoke(member));
},
},
canDelete &&
({
text: canRevokeSessions ? c('Member action').t`Delete` : c('Member action').t`Remove`,
actionType: 'delete',
onClick: () => {
onDelete(member);
},
} as const),
].filter(isTruthy);
return <DropdownActions loading={loading} list={list} size="small" />;
};
export default MemberActions;
| 6,448
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/MemberAddresses.tsx
|
import { useState } from 'react';
import { c, msgid } from 'ttag';
import { Button } from '@proton/atoms';
import { PartialMemberAddress } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import { Icon } from '../../components';
const amountOfDisplayedAddresses = 3;
interface MemberAddressesProps {
addresses: PartialMemberAddress[] | undefined;
}
const MemberAddresses = ({ addresses = [] }: MemberAddressesProps) => {
const [expanded, setExpanded] = useState(false);
const handleExpandClick = () => {
setExpanded(true);
};
const amountOfAddresses = addresses.length;
const renderListItem = ({ ID, Email }: PartialMemberAddress, index: number) => {
/*
* By default, the addresses list shows 3 addresses as well as
* a clickable text saying "x more addresses", which, when clicked,
* expands the addresses list and shows all addresses.
*
* While not expanded the last list-item is colored more lightly as
* if to indicate a fade.
*/
const isLastDisplayedAddress = index === amountOfDisplayedAddresses - 1;
const displayAsFade = !expanded && isLastDisplayedAddress && amountOfAddresses > amountOfDisplayedAddresses;
const listItemClassName = clsx([displayAsFade && 'color-weak', 'my-2']);
return (
<li key={ID} className={listItemClassName}>
<span
className="text-ellipsis block"
title={Email}
data-testid="users-and-addresses-table:memberAddress"
>
{Email}
</span>
</li>
);
};
const initiallyDisplayedAddresses = addresses.slice(0, amountOfDisplayedAddresses).map(renderListItem);
const remainingAddresses = addresses.slice(amountOfDisplayedAddresses).map(renderListItem);
const getAddressesListItems = () => {
if (amountOfAddresses === 0) {
return (
<li className="py-2">
<span className="md:hidden">{amountOfAddresses}</span>
<span className="hidden md:inline">
{
// translator: addresses mean "email addresses" in this context
c('Info').ngettext(
msgid`${amountOfAddresses} address`,
`${amountOfAddresses} addresses`,
amountOfAddresses
)
}
</span>
</li>
);
}
if (expanded) {
return [...initiallyDisplayedAddresses, ...remainingAddresses];
}
if (remainingAddresses.length > 0) {
const expandButton = (
<li key="expand" className="mb-2">
<Button
onClick={handleExpandClick}
color="norm"
shape="ghost"
size="small"
className="flex flex-align-items-center"
>
<span className="md:hidden">
{
// translator: we speak about email addresses in this context
c('Info').ngettext(
msgid`${remainingAddresses.length} more`,
`${remainingAddresses.length} more`,
remainingAddresses.length
)
}
</span>
<span className="hidden md:inline">
{
// translator: addresses mean email addresses in this context
c('Info').ngettext(
msgid`${remainingAddresses.length} more address`,
`${remainingAddresses.length} more addresses`,
remainingAddresses.length
)
}
</span>
<Icon size={12} className="ml-1" name="chevron-down" />
</Button>
</li>
);
return [...initiallyDisplayedAddresses, expandButton];
}
return initiallyDisplayedAddresses;
};
return (
<ul className="unstyled my-custom" style={{ '--my-custom': 'calc(var(--space-2) * -1)' }}>
{getAddressesListItems()}
</ul>
);
};
export default MemberAddresses;
| 6,449
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/MemberFeatures.tsx
|
import { c, msgid } from 'ttag';
import humanSize from '@proton/shared/lib/helpers/humanSize';
import { Member, Organization } from '@proton/shared/lib/interfaces';
import { Icon } from '../../components';
interface Props {
member: Member;
organization: Organization;
}
const MemberFeatures = ({ member, organization }: Props) => {
const { UsedSpace, MaxSpace, MaxVPN } = member;
return (
<>
{organization.MaxSpace > 0 ? (
<span className="mb-2 flex flex-nowrap">
<span className="flex-item-noshrink flex mt-0.5">
<Icon name="filing-cabinet" />
</span>
<span className="flex-item-fluid pl-1" data-testid="users-and-addresses-table:storage">
{humanSize(UsedSpace, 'GB')} / {humanSize(MaxSpace, 'GB')}
</span>
</span>
) : null}
{organization.MaxVPN > 0 ? (
<span className="flex flex-nowrap">
<span className="flex-item-noshrink flex mt-0.5">
<Icon name="brand-proton-vpn" />
</span>
<span className="flex-item-fluid pl-1" data-testid="users-and-addresses-table:vpnConnections">
{c('Feature').ngettext(msgid`${MaxVPN} VPN connection`, `${MaxVPN} VPN connections`, MaxVPN)}
</span>
</span>
) : null}
</>
);
};
export default MemberFeatures;
| 6,450
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/MemberRole.tsx
|
import { c } from 'ttag';
import { MEMBER_ROLE } from '@proton/shared/lib/constants';
import { Member } from '@proton/shared/lib/interfaces';
const MemberRole = ({ member }: { member: Member }) => {
if (member.Subscriber) {
return <>{c('User role').t`Primary admin`}</>;
}
if (member.Role === MEMBER_ROLE.ORGANIZATION_MEMBER) {
return <>{c('User role').t`Member`}</>;
}
if (member.Role === MEMBER_ROLE.ORGANIZATION_ADMIN) {
return <>{c('User role').t`Admin`}</>;
}
return null;
};
export default MemberRole;
| 6,451
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/MemberStorageSelector.tsx
|
import { ReactNode, useRef, useState } from 'react';
import { c } from 'ttag';
import { Donut } from '@proton/atoms';
import Slider from '@proton/atoms/Slider/Slider';
import { ThemeColor, getVariableFromThemeColor } from '@proton/colors';
import { GIGA } from '@proton/shared/lib/constants';
import generateUID from '@proton/shared/lib/helpers/generateUID';
import humanSize, { getLongSizeFormat, getSizeFormat, getUnit } from '@proton/shared/lib/helpers/humanSize';
import clamp from '@proton/utils/clamp';
import { Tooltip } from '../../components';
import InputField from '../../components/v2/field/InputField';
import { useElementRect } from '../../hooks';
export const getTotalStorage = (
{ UsedSpace: memberUsedSpace = 0, MaxSpace: memberMaxSpace = 0 } = {},
{ MaxSpace: organizationMaxSpace = 0, AssignedSpace: organizationAssignedSpace = 0 }
) => {
return {
memberUsedSpace: memberUsedSpace,
organizationUsedSpace: organizationAssignedSpace - memberMaxSpace,
organizationMaxSpace: organizationMaxSpace,
};
};
export const getStorageRange = (
{ UsedSpace: memberUsedSpace = 0, MaxSpace: memberMaxSpace = 0 } = {},
{ MaxSpace: organizationMaxSpace = 0, AssignedSpace: organizationAssignedSpace = 0 }
) => {
return {
min: memberUsedSpace,
max: organizationMaxSpace - organizationAssignedSpace + memberMaxSpace,
};
};
interface Props {
range: ReturnType<typeof getStorageRange>;
totalStorage: ReturnType<typeof getTotalStorage>;
value: number;
sizeUnit: number;
onChange: (value: number) => void;
className?: string;
disabled?: boolean;
orgInitialization?: boolean;
}
const getNumberWithPrecision = (value: number, precision: number) => {
const multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
};
const getDisplayedValue = (value: number, precision: number) => {
return `${getNumberWithPrecision(value, precision).toFixed(precision)}`;
};
const getGraphValue = (value: number, total: number) => {
// Round to a nice number to avoid float issues
const percentage = Math.round((value / total) * 100);
if (percentage < 1 || Number.isNaN(percentage)) {
return 0;
}
return percentage;
};
interface Segment {
label: string;
size: ReactNode;
tooltip: string;
value: [number, ThemeColor];
}
const getSegments = (totalStorage: Props['totalStorage'], allocatedStorage: number): Segment[] => {
const alreadyUsedPercentage = getGraphValue(totalStorage.memberUsedSpace, totalStorage.organizationMaxSpace);
const alreadyAllocatedPercentage = getGraphValue(
totalStorage.organizationUsedSpace,
totalStorage.organizationMaxSpace
);
const allocatedPercentage = Math.min(
getGraphValue(allocatedStorage, totalStorage.organizationMaxSpace),
100 - (alreadyUsedPercentage + alreadyAllocatedPercentage)
);
return [
{
label: c('Info').t`Already used`,
size: humanSize(totalStorage.memberUsedSpace),
tooltip: c('Info').t`Storage used by this user`,
value: [alreadyUsedPercentage, ThemeColor.Danger],
},
{
label: c('Info').t`Already allocated`,
size: humanSize(totalStorage.organizationUsedSpace),
tooltip: c('Info').t`Storage allocated to other users in this organisation`,
value: [alreadyAllocatedPercentage, ThemeColor.Warning],
},
{
label: c('Info').t`Allocated`,
size: humanSize(allocatedStorage),
tooltip: c('Info').t`Storage allocated to this user`,
value: [allocatedPercentage, ThemeColor.Success],
},
];
};
const getValueInUnit = (value: number, sizeInBytes: number) => {
return value / sizeInBytes;
};
const getValueInBytes = (value: number, sizeInUnits: number) => {
return value * sizeInUnits;
};
const MemberStorageSelector = ({
range,
value,
onChange,
sizeUnit,
totalStorage,
className,
disabled,
orgInitialization = false,
}: Props) => {
const actualValue = getValueInUnit(value, sizeUnit);
const precision = 1;
const [tmpValue, setTmpValue] = useState(getDisplayedValue(actualValue, precision));
// We change the step depending on the remaining space
const remainingSpace = totalStorage.organizationMaxSpace - totalStorage.organizationUsedSpace;
const stepInBytes = remainingSpace > GIGA ? 0.5 * GIGA : 0.1 * GIGA;
const min = getNumberWithPrecision(getValueInUnit(range.min, sizeUnit), precision);
const max = getNumberWithPrecision(getValueInUnit(range.max, sizeUnit), precision);
const step = getNumberWithPrecision(getValueInUnit(stepInBytes, sizeUnit), precision);
const parsedValueInUnit = getNumberWithPrecision(Number.parseFloat(tmpValue), 1) || 0;
const parsedValueInBytes = Math.floor(getValueInBytes(parsedValueInUnit, sizeUnit));
const labelRef = useRef<HTMLDivElement>(null);
const rect = useElementRect(labelRef);
const sizeRef = useRef<HTMLDivElement>(null);
const sizeRect = useElementRect(sizeRef);
const [uid] = useState(generateUID('memberStorageSelector'));
const segments = getSegments(totalStorage, parsedValueInBytes);
const unit = getUnit(sizeUnit);
const handleSafeChange = (value: number) => {
if (Number.isNaN(value)) {
// Reset to old value if it's invalid
setTmpValue(getDisplayedValue(actualValue, precision));
return;
}
const safeValue = clamp(value, min, max);
setTmpValue(getDisplayedValue(safeValue, precision));
onChange(clamp(Math.floor(getValueInBytes(safeValue, sizeUnit)), range.min, range.max));
};
const sizeElementWidth = 1;
// We calculate a ratio because the modal has a transform animation which the getBoundingClientRect doesn't take into account
const ratio = (sizeRect?.width || 0) / sizeElementWidth;
const sizeLabel = getSizeFormat(unit, parsedValueInUnit);
const sizeLabelSuffix = (
<span id={uid} aria-label={getLongSizeFormat(unit, parsedValueInUnit)}>
{sizeLabel}
</span>
);
return (
<div className={className}>
<div className="flex on-tiny-mobile-flex-column">
<div className="w-3/10">
<InputField
label={c('Label').t`Account storage`}
disableChange={disabled}
value={tmpValue}
aria-label={c('Label').t`Account storage`}
data-testid="member-storage-selector"
aria-describedby={uid}
onValue={(value: string) => {
setTmpValue(value.replace(/[^\d.]/g, ''));
}}
onBlur={() => {
handleSafeChange(parsedValueInUnit);
}}
suffix={sizeLabelSuffix}
/>
</div>
<div className="flex flex-item-fluid flex-justify-end flex-align-self-start">
{orgInitialization ? (
<>
<div>
<b>{c('Info').t`Admin account allocation`}</b>: {humanSize(parsedValueInBytes, unit)}
</div>
<div>
<b>{c('Info').t`Storage for users`}</b>:{' '}
{humanSize(range.max - parsedValueInBytes, unit)}
</div>
</>
) : (
<>
<div className="w-custom" style={{ '--w-custom': `${(rect?.height || 0) / ratio}px` }}>
<Donut segments={segments.map(({ value }) => value)} />
</div>
<div className="ml-4 text-sm">
<div ref={labelRef}>
<div ref={sizeRef} style={{ width: `${sizeElementWidth}px` }} />
{segments.map(({ label, size, tooltip, value: [share, color] }) => (
<div className="mb-4 flex flex-align-items-center" key={tooltip}>
<Tooltip
title={
<>
{tooltip}
<br />({size})
</>
}
>
<span
className="inline-block user-select-none mr-2 w-custom rounded"
style={{
background: `var(${getVariableFromThemeColor(color)})`,
'--w-custom': '2em',
}}
>
</span>
</Tooltip>
<span className="sr-only">
{share} {sizeLabel}
</span>
<span className="text-semibold">{label}</span>
</div>
))}
</div>
</div>
</>
)}
</div>
</div>
<div className="mt-2 pr-2 md:pr-0">
<Slider
marks
disabled={disabled}
min={min}
max={max}
step={step}
aria-label={c('Label').t`Account storage`}
aria-describedby={uid}
value={parsedValueInUnit}
getDisplayedValue={(value) => getDisplayedValue(value, precision)}
onChange={handleSafeChange}
/>
</div>
</div>
);
};
export default MemberStorageSelector;
| 6,452
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/SubUserBulkCreateModal.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import SubUserCreateHint from '@proton/components/containers/members/SubUserCreateHint';
import CreateUserAccountsModal from '@proton/components/containers/members/multipleUserCreation/CreateUserAccountsModal/CreateUserAccountsModal';
import UploadCSVFileButton from '@proton/components/containers/members/multipleUserCreation/UploadCSVFileButton';
import { downloadVPNB2BSampleCSV } from '@proton/components/containers/members/multipleUserCreation/csv';
import { UserTemplate } from '@proton/components/containers/members/multipleUserCreation/types';
import { APP_NAMES } from '@proton/shared/lib/constants';
import { Domain } from '@proton/shared/lib/interfaces';
import {
InlineLinkButton,
ModalTwo as Modal,
ModalTwoContent as ModalContent,
ModalTwoFooter as ModalFooter,
ModalTwoHeader as ModalHeader,
ModalProps,
useModalState,
} from '../../components';
import { UserManagementMode } from './types';
enum Step {
INSTRUCTION,
SELECT_USER,
}
interface IntroModalProps extends ModalProps {
onBack: () => void;
onCSVFileUpload: (usersToImport: UserTemplate[]) => void;
}
const IntroModal = ({ onBack, onCSVFileUpload, ...rest }: IntroModalProps) => {
return (
<Modal {...rest}>
<ModalHeader
title={c('Title').t`Add user accounts`}
subline={c('Title').t`Upload CSV file to create multiple accounts`}
/>
<ModalContent className="pb-1">
<ol className="flex flex-column gap-2 pl-5 mb-6">
<li>
<InlineLinkButton onClick={downloadVPNB2BSampleCSV} color="norm" className="py-0">
{c('Action').t`Download our CSV template`}
</InlineLinkButton>
</li>
<li>{c('Info').t`Fill in user details`}</li>
<li>{c('Info').t`Upload your completed CSV file to create accounts`}</li>
</ol>
<SubUserCreateHint className="mt-2" />
</ModalContent>
<ModalFooter>
<Button onClick={onBack}>{c('Action').t`Back`}</Button>
<UploadCSVFileButton onUpload={onCSVFileUpload} color="norm" mode={UserManagementMode.VPN_B2B} />
</ModalFooter>
</Modal>
);
};
interface Props extends ModalProps {
onBack: () => void;
app: APP_NAMES;
verifiedDomains: Domain[];
}
const SubUserBulkCreateModal = ({ verifiedDomains, onBack, app, ...rest }: Props) => {
const [step, setStep] = useState<Step>(Step.INSTRUCTION);
const [usersToImport, setUsersToImport] = useState<UserTemplate[]>();
const [createUserAccountsModal, setCreateUserAccountsModal, renderCreateUserAccountsModal] = useModalState();
const onCSVFileUpload = (usersToImport: UserTemplate[]) => {
setUsersToImport(usersToImport);
setCreateUserAccountsModal(true);
setStep(Step.SELECT_USER);
};
if (step === Step.SELECT_USER && renderCreateUserAccountsModal && usersToImport) {
return (
<CreateUserAccountsModal
usersToImport={usersToImport}
app={app}
verifiedDomains={verifiedDomains}
{...createUserAccountsModal}
mode={UserManagementMode.VPN_B2B}
{...rest}
/>
);
}
return <IntroModal {...rest} onBack={onBack} onCSVFileUpload={onCSVFileUpload} />;
};
export default SubUserBulkCreateModal;
| 6,453
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/SubUserCreateHint.tsx
|
import { c } from 'ttag';
import { Icon } from '@proton/components/components';
import clsx from '@proton/utils/clsx';
const SubUserCreateHint = ({ className }: { className?: string }) => {
return (
<div className={clsx([className, 'py-2 px-3 bg-weak rounded flex flex-nowrap'])}>
<Icon name="info-circle" className="mr-2 mt-0.5 flex-item-noshrink" />
<span>{c('Info').t`Remember to share the user's sign in details with them.`}</span>
</div>
);
};
export default SubUserCreateHint;
| 6,454
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/SubUserCreateModal.tsx
|
import { FormEvent, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { vpnB2bAdminTooltipTitle } from '@proton/components/containers/members/constants';
import { useLoading } from '@proton/hooks';
import {
checkMemberAddressAvailability,
createMember,
createMemberAddress,
updateRole,
} from '@proton/shared/lib/api/members';
import {
APP_NAMES,
DEFAULT_ENCRYPTION_CONFIG,
ENCRYPTION_CONFIGS,
GIGA,
MEMBER_ROLE,
VPN_CONNECTIONS,
} from '@proton/shared/lib/constants';
import { getEmailParts, validateEmailAddress } from '@proton/shared/lib/helpers/email';
import {
confirmPasswordValidator,
passwordLengthValidator,
requiredValidator,
} from '@proton/shared/lib/helpers/formValidators';
import { Address, CachedOrganizationKey, Domain, Member, Organization } from '@proton/shared/lib/interfaces';
import { setupMemberKeys } from '@proton/shared/lib/keys';
import { srpVerify } from '@proton/shared/lib/srp';
import clamp from '@proton/utils/clamp';
import isTruthy from '@proton/utils/isTruthy';
import {
DropdownSizeUnit,
Icon,
InputFieldTwo,
ModalTwo as Modal,
ModalTwoContent as ModalContent,
ModalTwoFooter as ModalFooter,
ModalTwoHeader as ModalHeader,
ModalProps,
Option,
PasswordInputTwo,
SelectTwo,
Toggle,
Tooltip,
useFormErrors,
useModalState,
} from '../../components';
import { useApi, useEventManager, useGetAddresses, useGetUser, useGetUserKeys, useNotifications } from '../../hooks';
import { useKTVerifier } from '../keyTransparency';
import MemberStorageSelector, { getStorageRange, getTotalStorage } from './MemberStorageSelector';
import SubUserBulkCreateModal from './SubUserBulkCreateModal';
import SubUserCreateHint from './SubUserCreateHint';
import { UserManagementMode } from './types';
import validateAddUser from './validateAddUser';
enum Step {
SINGLE,
BULK,
}
interface Props extends ModalProps {
organization: Organization;
organizationKey: CachedOrganizationKey;
verifiedDomains: Domain[];
mode?: UserManagementMode;
app: APP_NAMES;
}
const SubUserCreateModal = ({
organization,
organizationKey,
verifiedDomains,
mode = UserManagementMode.DEFAULT,
onClose,
app,
...rest
}: Props) => {
const { createNotification } = useNotifications();
const { call } = useEventManager();
const api = useApi();
const getAddresses = useGetAddresses();
const getUserKeys = useGetUserKeys();
const storageSizeUnit = GIGA;
const storageRange = getStorageRange({}, organization);
const [step, setStep] = useState<Step>(Step.SINGLE);
const hasVPN = !!organization.MaxVPN;
const [model, setModel] = useState({
name: '',
private: false,
admin: false,
password: '',
confirm: '',
address: '',
domain: verifiedDomains[0]?.DomainName ?? null,
vpn: hasVPN && organization.MaxVPN - organization.UsedVPN >= VPN_CONNECTIONS,
storage: clamp(5 * GIGA, storageRange.min, storageRange.max),
});
const { keyTransparencyVerify, keyTransparencyCommit } = useKTVerifier(api, useGetUser());
const [submitting, withLoading] = useLoading();
const { validator, onFormSubmit } = useFormErrors();
const [bulkUserCreateModalProps, setBulkUserModalOpen] = useModalState();
const domainOptions = verifiedDomains.map(({ DomainName }) => ({ text: DomainName, value: DomainName }));
const handleChange = (key: keyof typeof model) => (value: (typeof model)[typeof key]) =>
setModel({ ...model, [key]: value });
const getNormalizedAddress = () => {
if (model.domain) {
return { Local: model.address, Domain: model.domain };
}
const [Local, Domain] = getEmailParts(model.address);
return { Local, Domain };
};
const save = async () => {
const normalizedAddress = getNormalizedAddress();
await api(checkMemberAddressAvailability(normalizedAddress));
const userKeys = await getUserKeys();
const { Member } = await srpVerify<{ Member: Member }>({
api,
credentials: { password: model.password },
config: createMember({
Name: model.name || model.address,
Private: +model.private,
MaxSpace: +model.storage,
MaxVPN: model.vpn ? VPN_CONNECTIONS : 0,
}),
});
const { Address } = await api<{ Address: Address }>(createMemberAddress(Member.ID, normalizedAddress));
if (!model.private) {
if (!organizationKey.privateKey) {
throw new Error('Organization key is not decrypted');
}
const ownerAddresses = await getAddresses();
await setupMemberKeys({
api,
ownerAddresses,
member: Member,
memberAddresses: [Address],
organizationKey: organizationKey.privateKey,
encryptionConfig: ENCRYPTION_CONFIGS[DEFAULT_ENCRYPTION_CONFIG],
password: model.password,
keyTransparencyVerify,
});
await keyTransparencyCommit(userKeys);
}
if (model.admin) {
await api(updateRole(Member.ID, MEMBER_ROLE.ORGANIZATION_ADMIN));
}
};
const validate = () => {
const error = validateAddUser({
privateUser: model.private,
organization,
organizationKey,
verifiedDomains,
mode,
});
if (error) {
return error;
}
const normalizedAddress = getNormalizedAddress();
if (!validateEmailAddress(`${normalizedAddress.Local}@${normalizedAddress.Domain}`)) {
return c('Error').t`Email address is invalid`;
}
};
const handleSubmit = async () => {
await save();
await call();
onClose?.();
createNotification({ text: c('Success').t`User created` });
};
const setBulkStep = () => {
setBulkUserModalOpen(true);
setStep(Step.BULK);
};
const setSingleStep = () => {
setBulkUserModalOpen(false);
setStep(Step.SINGLE);
};
const handleClose = () => {
if (!submitting) {
onClose?.();
setSingleStep();
}
};
const isVpnB2B = mode === UserManagementMode.VPN_B2B;
const isDefault = mode === UserManagementMode.DEFAULT;
if (step === Step.BULK) {
return (
<SubUserBulkCreateModal
verifiedDomains={verifiedDomains}
{...bulkUserCreateModalProps}
onBack={setSingleStep}
onClose={handleClose}
app={app}
/>
);
}
const addressSuffix = (() => {
if (domainOptions.length === 0) {
// there is no domains for vpn-b2b mode
return null;
}
if (domainOptions.length === 1) {
return (
<span className="text-ellipsis" title={`@${domainOptions[0].value}`}>
@{domainOptions[0].value}
</span>
);
}
return (
<SelectTwo
unstyled
originalPlacement="bottom-end"
size={{ width: DropdownSizeUnit.Static }}
value={model.domain}
onChange={({ value }) => handleChange('domain')(value)}
>
{domainOptions.map((option) => (
<Option key={option.value} value={option.value} title={option.text}>
@{option.text}
</Option>
))}
</SelectTwo>
);
})();
return (
<Modal
as="form"
{...rest}
onClose={handleClose}
onSubmit={(event: FormEvent) => {
event.preventDefault();
event.stopPropagation();
if (!onFormSubmit()) {
return;
}
const error = validate();
if (error) {
return createNotification({ type: 'error', text: error });
}
void withLoading(handleSubmit());
}}
>
<ModalHeader title={c('Title').t`Add new user`} />
<ModalContent>
{mode !== UserManagementMode.VPN_B2B && (
<p className="color-weak">
{c('Info').t`Create a new account and share the email address and password with the user.`}
</p>
)}
<InputFieldTwo
id="name"
autoFocus
value={model.name}
hint={isVpnB2B ? c('Info').t`Optional` : undefined}
error={validator([isDefault && requiredValidator(model.name)].filter(isTruthy))}
onValue={handleChange('name')}
label={c('Label').t`Name`}
/>
<InputFieldTwo
id="address"
value={model.address}
error={validator([requiredValidator(model.address)])}
onValue={handleChange('address')}
label={isVpnB2B ? c('Label').t`Email` : c('Label').t`Address`}
suffix={addressSuffix}
/>
<InputFieldTwo
id="password"
as={PasswordInputTwo}
value={model.password}
error={validator([requiredValidator(model.password), passwordLengthValidator(model.password)])}
onValue={handleChange('password')}
label={c('Label').t`Create password`}
/>
<InputFieldTwo
id="confirm-password"
as={PasswordInputTwo}
value={model.confirm}
error={validator([
requiredValidator(model.confirm),
confirmPasswordValidator(model.password, model.confirm),
])}
onValue={handleChange('confirm')}
label={c('Label').t`Confirm password`}
/>
{!isVpnB2B && (
<>
<MemberStorageSelector
className="mb-5"
value={model.storage}
sizeUnit={storageSizeUnit}
range={storageRange}
totalStorage={getTotalStorage({}, organization)}
onChange={handleChange('storage')}
/>
{hasVPN && (
<div className="flex flex-align-center mb-5">
<label className="text-semibold mr-4" htmlFor="vpn-toggle">
{c('Label for new member').t`VPN connections`}
</label>
<Toggle
id="vpn-toggle"
checked={model.vpn}
onChange={({ target }) => handleChange('vpn')(target.checked)}
/>
</div>
)}
<div className="flex flex-align-center mb-6">
<label className="text-semibold mr-4" htmlFor="private-toggle">
{c('Label for new member').t`Private`}
</label>
<Toggle
id="private-toggle"
checked={model.private}
onChange={({ target }) => handleChange('private')(target.checked)}
/>
</div>
</>
)}
<div className="flex flex-align-items-center mb-6">
<label className="text-semibold mr-1" htmlFor="admin-toggle">
{c('Label for new member').t`Admin`}
</label>
{isVpnB2B && (
<Tooltip title={vpnB2bAdminTooltipTitle}>
<Icon name="info-circle" className="color-primary" />
</Tooltip>
)}
<Toggle
id="admin-toggle"
className="ml-2"
checked={model.admin}
onChange={({ target }) => handleChange('admin')(target.checked)}
/>
</div>
{isVpnB2B && <SubUserCreateHint className="mt-8" />}
</ModalContent>
<ModalFooter>
{isVpnB2B ? (
<Button onClick={setBulkStep} disabled={submitting}>
{c('Action').t`Add multiple users`}
</Button>
) : (
<Button onClick={handleClose} disabled={submitting}>
{c('Action').t`Cancel`}
</Button>
)}
<Button loading={submitting} type="submit" color="norm">
{c('Action').t`Create user`}
</Button>
</ModalFooter>
</Modal>
);
};
export default SubUserCreateModal;
| 6,455
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/SubUserDeleteModal.tsx
|
import { FormEvent, useState } from 'react';
import { c } from 'ttag';
import { Button, Card } from '@proton/atoms';
import { Prompt } from '@proton/components/components';
import { useLoading } from '@proton/hooks';
import { NAME_PLACEHOLDER } from '@proton/shared/lib/constants';
import { requiredValidator } from '@proton/shared/lib/helpers/formValidators';
import { removeDiacritics } from '@proton/shared/lib/helpers/string';
import { Member } from '@proton/shared/lib/interfaces/Member';
import {
Alert,
InputFieldTwo,
ModalProps,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
useFormErrors,
} from '../../components';
import { UserManagementMode } from './types';
const clean = (value: string) => {
return removeDiacritics(value.toLowerCase().replace(/\s+/g, ''));
};
interface Props extends ModalProps<'form'> {
member: Member;
onDelete: (member: Member) => Promise<void>;
mode: UserManagementMode;
}
const SubUserDeleteModal = ({ member, onDelete, mode, ...rest }: Props) => {
const [username, setUsername] = useState('');
const isValid = clean(username) === clean(member.Name);
const { validator, onFormSubmit } = useFormErrors();
const [loading, withLoading] = useLoading();
const handleClose = loading ? undefined : rest.onClose;
if (mode === UserManagementMode.VPN_B2B) {
const handleDelete = async () => {
await withLoading(onDelete(member));
rest.onClose?.();
};
return (
<Prompt
title={c('Title').t`Delete user?`}
open={rest.open}
onClose={rest.onClose}
buttons={[
<Button color="danger" loading={loading} onClick={handleDelete}>{c('Action')
.t`Delete user`}</Button>,
<Button disabled={loading} onClick={handleClose}>{c('Action').t`Cancel`}</Button>,
]}
>
<p>{c('Info').t`They will be removed from your organization`}</p>
</Prompt>
);
}
return (
<ModalTwo
as="form"
{...rest}
onSubmit={async (event: FormEvent) => {
event.preventDefault();
if (!onFormSubmit()) {
return;
}
await withLoading(onDelete(member));
rest.onClose?.();
}}
onClose={handleClose}
>
<ModalTwoHeader title={c('Title').t`Delete user`} />
<ModalTwoContent>
<div className="mb-4">
{c('Info')
.t`This will permanently delete the data and all email addresses associated with this user.`}
</div>
<Card rounded className="text-pre-wrap break user-select mb-4">
{member.Name}
</Card>
<Alert className="mb-4" type="error">{c('Info')
.t`To confirm, please enter the name of the user you wish to delete.`}</Alert>
<InputFieldTwo
autoComplete="false"
value={username}
onValue={setUsername}
label={c('Label').t`Name`}
placeholder={NAME_PLACEHOLDER}
error={validator([requiredValidator(username), !isValid ? c('Error').t`Name does not match` : ''])}
autoFocus
data-testid="deleteMemberModal:username-input"
/>
</ModalTwoContent>
<ModalTwoFooter>
<Button disabled={loading} onClick={handleClose}>{c('Action').t`Cancel`}</Button>
<Button color="danger" loading={loading} type="submit">{c('Action').t`Delete`}</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default SubUserDeleteModal;
| 6,456
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/SubUserEditModal.tsx
|
import { FormEvent, useMemo, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { vpnB2bAdminTooltipTitle } from '@proton/components/containers/members/constants';
import { useLoading } from '@proton/hooks';
import { privatizeMember, updateName, updateQuota, updateRole, updateVPN } from '@proton/shared/lib/api/members';
import {
GIGA,
MEMBER_PRIVATE,
MEMBER_ROLE,
MEMBER_SUBSCRIBER,
NAME_PLACEHOLDER,
VPN_CONNECTIONS,
} from '@proton/shared/lib/constants';
import { requiredValidator } from '@proton/shared/lib/helpers/formValidators';
import { Member } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import {
Alert,
ConfirmModal,
Icon,
InputFieldTwo,
ModalTwo as Modal,
ModalTwoContent as ModalContent,
ModalTwoFooter as ModalFooter,
ModalTwoHeader as ModalHeader,
ModalProps,
Toggle,
Tooltip,
useFormErrors,
} from '../../components';
import { useApi, useEventManager, useModals, useNotifications, useOrganization } from '../../hooks';
import Addresses from '../addresses/Addresses';
import MemberStorageSelector, { getStorageRange, getTotalStorage } from './MemberStorageSelector';
import { UserManagementMode } from './types';
interface Props extends ModalProps<'form'> {
member: Member;
mode: UserManagementMode;
}
const SubUserEditModal = ({ member, mode, ...rest }: Props) => {
const [organization] = useOrganization();
const storageSizeUnit = GIGA;
const { call } = useEventManager();
const { createModal } = useModals();
const { validator, onFormSubmit } = useFormErrors();
const initialModel = useMemo(
() => ({
name: member.Name,
storage: member.MaxSpace,
vpn: !!member.MaxVPN,
private: !!member.Private,
admin: member.Role === MEMBER_ROLE.ORGANIZATION_ADMIN,
}),
[member]
);
const [model, updateModel] = useState(initialModel);
const [submitting, withLoading] = useLoading();
const { createNotification } = useNotifications();
const api = useApi();
const hasVPN = Boolean(organization.MaxVPN);
const canMakePrivate = member.Private === MEMBER_PRIVATE.READABLE;
const canMakeAdmin = !member.Self && member.Role === MEMBER_ROLE.ORGANIZATION_MEMBER;
const canRevokeAdmin = !member.Self && member.Role === MEMBER_ROLE.ORGANIZATION_ADMIN;
const isVpnB2B = mode === UserManagementMode.VPN_B2B;
const isDefault = mode === UserManagementMode.DEFAULT;
const updatePartialModel = (partial: Partial<typeof model>) => {
updateModel({ ...model, ...partial });
};
const handleSubmit = async () => {
let hasChanges = false;
if (initialModel.name !== model.name) {
await api(updateName(member.ID, model.name));
hasChanges = true;
}
if (initialModel.storage !== model.storage) {
await api(updateQuota(member.ID, model.storage));
hasChanges = true;
}
if (hasVPN && initialModel.vpn !== model.vpn) {
await api(updateVPN(member.ID, model.vpn ? VPN_CONNECTIONS : 0));
hasChanges = true;
}
if (canMakePrivate && model.private && model.private !== initialModel.private) {
await api(privatizeMember(member.ID));
hasChanges = true;
}
if (canMakeAdmin && model.admin && model.admin !== initialModel.admin) {
await api(updateRole(member.ID, MEMBER_ROLE.ORGANIZATION_ADMIN));
hasChanges = true;
}
if (canRevokeAdmin && !model.admin && model.admin !== initialModel.admin) {
try {
await new Promise((resolve, reject) => {
createModal(
<ConfirmModal
onClose={reject}
onConfirm={() => resolve(undefined)}
title={c('Title').t`Change role`}
>
<Alert className="mb-4">
{member.Subscriber === MEMBER_SUBSCRIBER.PAYER
? c('Info')
.t`This user is currently responsible for payments for your organization. By demoting this member, you will become responsible for payments for your organization.`
: c('Info')
.t`Are you sure you want to remove administrative privileges from this user?`}
</Alert>
</ConfirmModal>
);
});
await api(updateRole(member.ID, MEMBER_ROLE.ORGANIZATION_MEMBER));
hasChanges = true;
} catch (e) {
/* do nothing, user declined confirm-modal to revoke admin rights from member */
}
}
await call();
rest.onClose?.();
if (hasChanges) {
createNotification({ text: c('Success').t`User updated` });
}
};
const handleClose = submitting ? undefined : rest.onClose;
return (
<Modal
as="form"
size="large"
{...rest}
onSubmit={(event: FormEvent) => {
event.preventDefault();
event.stopPropagation();
if (!onFormSubmit()) {
return;
}
withLoading(handleSubmit());
}}
onClose={handleClose}
>
<ModalHeader title={c('Title').t`Edit user`} />
<ModalContent>
<InputFieldTwo
id="name"
value={model.name}
error={validator([requiredValidator(model.name)])}
onValue={(value: string) => updatePartialModel({ name: value })}
label={c('Label').t`Name`}
placeholder={NAME_PLACEHOLDER}
/>
{isDefault && (
<MemberStorageSelector
className="mb-5"
value={model.storage}
sizeUnit={storageSizeUnit}
totalStorage={getTotalStorage(member, organization)}
range={getStorageRange(member, organization)}
onChange={(storage) => updatePartialModel({ storage })}
/>
)}
{hasVPN && isDefault ? (
<div className="flex flex-align-center mb-5">
<label className="text-semibold mr-4" htmlFor="vpn-toggle">
{c('Label for new member').t`VPN connections`}
</label>
<Toggle
id="vpn-toggle"
checked={model.vpn}
onChange={({ target }) => updatePartialModel({ vpn: target.checked })}
/>
</div>
) : null}
{canMakePrivate && isDefault && (
<div className="flex flex-align-center mb-6">
<label className="text-semibold mr-4" htmlFor="private-toggle">
{c('Label for new member').t`Private`}
</label>
<Toggle
id="private-toggle"
checked={model.private}
onChange={({ target }) => updatePartialModel({ private: target.checked })}
/>
</div>
)}
{(canMakeAdmin || canRevokeAdmin) && (
<div className="flex flex-align-items-center mb-6">
<label className={clsx(['text-semibold', isVpnB2B ? 'mr-1' : 'mr-4'])} htmlFor="admin-toggle">
{c('Label for new member').t`Admin`}
</label>
{isVpnB2B && (
<Tooltip title={vpnB2bAdminTooltipTitle}>
<Icon name="info-circle" className="mr-2 color-primary" />
</Tooltip>
)}
<Toggle
id="admin-toggle"
checked={model.admin}
onChange={({ target }) => updatePartialModel({ admin: target.checked })}
/>
</div>
)}
{isDefault && (
<div>
<h3 className="text-strong">{c('Label').t`Addresses`}</h3>
<div>
<Addresses organization={organization} memberID={member.ID} />
</div>
</div>
)}
</ModalContent>
<ModalFooter>
<Button className={clsx([isVpnB2B && 'visibility-hidden'])} onClick={handleClose} disabled={submitting}>
{c('Action').t`Cancel`}
</Button>
<Button loading={submitting} type="submit" color="norm">
{c('Action').t`Save`}
</Button>
</ModalFooter>
</Modal>
);
};
export default SubUserEditModal;
| 6,457
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/UserInviteOrEditModal.tsx
|
import { FormEvent, useMemo, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { useLoading } from '@proton/hooks';
import { editMemberInvitation, inviteMember, updateQuota, updateRole, updateVPN } from '@proton/shared/lib/api/members';
import { GIGA, MAIL_APP_NAME, MEMBER_ROLE, MEMBER_SUBSCRIBER, VPN_CONNECTIONS } from '@proton/shared/lib/constants';
import { emailValidator, requiredValidator } from '@proton/shared/lib/helpers/formValidators';
import { Domain, FAMILY_PLAN_INVITE_STATE, Member, Organization } from '@proton/shared/lib/interfaces';
import clamp from '@proton/utils/clamp';
import {
Alert,
ConfirmModal,
InputFieldTwo,
ModalTwo as Modal,
ModalTwoContent as ModalContent,
ModalTwoFooter as ModalFooter,
ModalTwoHeader as ModalHeader,
ModalStateProps,
Toggle,
useFormErrors,
} from '../../components';
import { useApi, useEventManager, useModals, useNotifications } from '../../hooks';
import Addresses from '../addresses/Addresses';
import MemberStorageSelector, { getStorageRange, getTotalStorage } from './MemberStorageSelector';
interface Props extends ModalStateProps {
organization: Organization;
domains: Domain[];
member: Member | null;
}
const UserInviteOrEditModal = ({ organization, domains, member, ...modalState }: Props) => {
const api = useApi();
const { call } = useEventManager();
const { createModal } = useModals();
const [submitting, withLoading] = useLoading();
const { createNotification } = useNotifications();
const { validator, onFormSubmit } = useFormErrors();
const totalStorage = getTotalStorage(member ?? {}, organization);
const storageRange = getStorageRange(member ?? {}, organization);
const storageSizeUnit = GIGA;
const isEditing = !!member?.ID;
const isInvitationPending = member?.State === FAMILY_PLAN_INVITE_STATE.STATUS_INVITED;
const hasVPN = Boolean(organization.MaxVPN);
const canMakeAdmin = !member?.Self && !isInvitationPending && member?.Role === MEMBER_ROLE.ORGANIZATION_MEMBER;
const canRevokeAdmin = !member?.Self && !isInvitationPending && member?.Role === MEMBER_ROLE.ORGANIZATION_ADMIN;
const canUpdateVPNConnection = isEditing && !isInvitationPending && hasVPN;
const initialModel = useMemo(
() => ({
address: '',
storage: member ? member.MaxSpace : clamp(500 * GIGA, storageRange.min, storageRange.max),
vpn: !!member?.MaxVPN,
admin: member?.Role === MEMBER_ROLE.ORGANIZATION_ADMIN,
}),
[member]
);
const [model, setModel] = useState(initialModel);
const handleClose = () => {
if (submitting) {
return;
}
modalState.onClose();
};
const handleChange = (key: keyof typeof model) => (value: (typeof model)[typeof key]) => {
setModel({ ...model, [key]: value });
};
const sendInvitation = async () => {
await api(inviteMember(model.address, model.storage));
createNotification({ text: c('Success').t`Invitation sent` });
};
const revokeAdmin = async () => {
await new Promise((resolve, reject) => {
createModal(
<ConfirmModal onClose={reject} onConfirm={() => resolve(undefined)} title={c('Title').t`Change role`}>
<Alert className="mb-4">
{member!.Subscriber === MEMBER_SUBSCRIBER.PAYER
? c('Info')
.t`This user is currently responsible for payments for your organization. By demoting this member, you will become responsible for payments for your organization.`
: c('Info').t`Are you sure you want to remove administrative privileges from this user?`}
</Alert>
</ConfirmModal>
);
});
await api(updateRole(member!.ID, MEMBER_ROLE.ORGANIZATION_MEMBER));
};
const editInvitation = async () => {
let updated = false;
// Editing a pending invitation uses a different endpoint than updating a user that accepted the invite
if (isInvitationPending) {
await api(editMemberInvitation(member!.ID, model.storage));
updated = true;
} else {
// Make consecutive API calls to update the member (API restriction)
if (initialModel.storage !== model.storage) {
await api(updateQuota(member!.ID, model.storage));
updated = true;
}
if (canUpdateVPNConnection && initialModel.vpn !== model.vpn) {
await api(updateVPN(member!.ID, model.vpn ? VPN_CONNECTIONS : 0));
updated = true;
}
if (canMakeAdmin && model.admin && initialModel.admin !== model.admin) {
await api(updateRole(member!.ID, MEMBER_ROLE.ORGANIZATION_ADMIN));
updated = true;
}
if (canRevokeAdmin && !model.admin && initialModel.admin !== model.admin) {
try {
await revokeAdmin();
updated = true;
} catch (error) {
/* do nothing, user declined confirm-modal to revoke admin rights from member */
}
}
}
if (updated) {
createNotification({ text: c('familyOffer_2023:Success').t`Member updated` });
}
};
const handleSubmit = async () => {
if (isEditing) {
await editInvitation();
} else {
await sendInvitation();
}
await call();
modalState.onClose();
};
const mailFieldValidator = isEditing ? [requiredValidator(model.address), emailValidator(model.address)] : [];
const modalTitle = isEditing
? c('familyOffer_2023:Title').t`Edit user storage`
: c('familyOffer_2023:Title').t`Invite a user`;
const modalDescription = isEditing
? c('familyOffer_2023:Info').t`You can increase or reduce the storage for this user.`
: c('familyOffer_2023:Info')
.t`If the user already has a ${MAIL_APP_NAME} address, enter it here. Otherwise they need to create an account first.`;
return (
<Modal
as="form"
size="large"
{...modalState}
onClose={handleClose}
onSubmit={(event: FormEvent) => {
event.preventDefault();
event.stopPropagation();
if (!onFormSubmit()) {
return;
}
void withLoading(handleSubmit());
}}
>
<ModalHeader title={modalTitle} />
<ModalContent>
<p className="color-weak">{modalDescription}</p>
{!isEditing && (
<InputFieldTwo
id="email-address"
type="email"
autoCapitalize="off"
autoComplete="off"
autoCorrect="off"
value={model.address}
error={validator(mailFieldValidator)}
onValue={handleChange('address')}
label={c('Label').t`Email address`}
placeholder="thomas.anderson@proton.me"
disableChange={submitting}
autoFocus
required
/>
)}
<MemberStorageSelector
value={model.storage}
disabled={submitting}
sizeUnit={storageSizeUnit}
range={storageRange}
totalStorage={totalStorage}
onChange={handleChange('storage')}
/>
{canUpdateVPNConnection ? (
<div className="flex flex-align-center mb-5">
<label className="text-semibold mr-4" htmlFor="vpn-toggle">
{c('Label for new member').t`VPN connections`}
</label>
<Toggle
id="vpn-toggle"
checked={model.vpn}
onChange={({ target }) => setModel({ ...model, vpn: target.checked })}
/>
</div>
) : null}
{(canMakeAdmin || canRevokeAdmin) && (
<div className="flex flex-align-center mb-6">
<label className="text-semibold mr-4" htmlFor="admin-toggle">
{c('Label for new member').t`Admin`}
</label>
<Toggle
id="admin-toggle"
checked={model.admin}
onChange={({ target }) => setModel({ ...model, admin: target.checked })}
/>
</div>
)}
{isEditing && member.State === FAMILY_PLAN_INVITE_STATE.STATUS_ENABLED && (
<div>
<h3 className="text-strong">{c('Label').t`Addresses`}</h3>
<div>
<Addresses organization={organization} memberID={member.ID} />
</div>
</div>
)}
</ModalContent>
<ModalFooter>
<Button onClick={handleClose} disabled={submitting}>
{c('Action').t`Cancel`}
</Button>
<Button loading={submitting} type="submit" color="norm">
{isEditing ? c('Action').t`Save` : c('Action').t`Invite`}
</Button>
</ModalFooter>
</Modal>
);
};
export default UserInviteOrEditModal;
| 6,458
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/UserRemoveModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { useLoading } from '@proton/hooks';
import { deleteMember } from '@proton/shared/lib/api/members';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { FAMILY_PLAN_INVITE_STATE, Member, Organization } from '@proton/shared/lib/interfaces';
import { ModalProps, Prompt } from '../../components';
import { useApi, useEventManager, useNotifications } from '../../hooks';
interface Props extends ModalProps {
member: Member;
organization: Organization;
}
const UserRemoveModal = ({ member, organization, ...rest }: Props) => {
const api = useApi();
const { call } = useEventManager();
const [submitting, withLoading] = useLoading();
const { createNotification } = useNotifications();
const isInvitationPending = !!(member.State === FAMILY_PLAN_INVITE_STATE.STATUS_INVITED);
const handleClose = () => {
if (submitting) {
return undefined;
}
rest?.onClose?.();
};
const handleDelete = async () => {
if (!member?.ID) {
createNotification({
text: c('familyOffer_2023:Success').t`An error occurred, please try again`,
type: 'error',
});
return;
}
await api(deleteMember(member?.ID));
await call();
rest?.onClose?.();
createNotification({
// translator: Success message when a user has been removed from an organization. Looks like: 'John Doe has been removed from Bernie's Family'
text: c('familyOffer_2023:Success').t`${member.Name} has been removed from ${organization.Name}`,
});
};
const description = isInvitationPending
? // translator: Info message when a user has been invited to an organization. Looks like: 'The invitation will be cancelled and the user won't be able to join Bernie's Family.'
c('familyOffer_2023:Info')
.t`The invitation will be cancelled and the user won't be able to join ${organization.Name}.`
: c('familyOffer_2023:Info')
.t`The user's account will be moved to a ${BRAND_NAME} Unlimited plan for a 30-day free trial*.`;
return (
<Prompt
{...rest}
title={c('Title').t`Remove user?`}
footnote={isInvitationPending ? undefined : c('familyOffer_2023:Info').t`*Only one free trial per user.`}
buttons={[
<Button
color="danger"
loading={submitting}
onClick={() => {
void withLoading(handleDelete);
}}
>{c('Action').t`Remove`}</Button>,
<Button onClick={handleClose} disabled={submitting}>{c('Action').t`Cancel`}</Button>,
]}
>
<p>{description}</p>
</Prompt>
);
};
export default UserRemoveModal;
| 6,459
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/constants.ts
|
import { c } from 'ttag';
export const vpnB2bAdminTooltipTitle = (() => {
return c('Tooltip')
.t`Admins can make changes to your subscription, manage user accounts and passwords, and give admin privileges to other users.`;
})();
| 6,460
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/index.ts
|
export { default as MemberActions } from './MemberActions';
export { default as MemberAddresses } from './MemberAddresses';
export { default as MemberFeatures } from './MemberFeatures';
export { default as MemberRole } from './MemberRole';
export { default as MemberStorageSelector } from './MemberStorageSelector';
export { default as SubUserCreateModal } from './SubUserCreateModal';
export { default as SubUserEditModal } from './SubUserEditModal';
export { default as UsersAndAddressesSection } from './UsersAndAddressesSection/UsersAndAddressesSection';
export { default as MultiUserCreationSection } from './multipleUserCreation/MultiUserCreationSection';
| 6,461
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/types.ts
|
export enum UserManagementMode {
DEFAULT,
VPN_B2B,
}
| 6,462
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/validateAddUser.ts
|
import { c } from 'ttag';
import { CachedOrganizationKey, Domain, Organization } from '@proton/shared/lib/interfaces';
import { getOrganizationKeyInfo } from '@proton/shared/lib/organization/helper';
import { UserManagementMode } from './types';
export const getDomainError = () => {
return c('Error').t`Please configure a custom domain before adding users to your organization.`;
};
const validateAddUser = ({
privateUser,
organization,
organizationKey,
verifiedDomains,
mode,
}: {
privateUser: boolean;
organization: Organization;
organizationKey: CachedOrganizationKey | undefined;
verifiedDomains: Domain[];
mode: UserManagementMode;
}) => {
const organizationKeyInfo = getOrganizationKeyInfo(organization, organizationKey);
const { MaxMembers, HasKeys, UsedMembers, MaxAddresses, UsedAddresses, MaxSpace, AssignedSpace } = organization;
const shouldValidateSpace = mode === UserManagementMode.DEFAULT;
const shouldValidateDomain = mode === UserManagementMode.DEFAULT;
if (MaxMembers === 1) {
return c('Error').t`Please upgrade to a business plan with more than 1 user to manage multiple users.`;
}
if (!HasKeys) {
return c('Error').t`Please enable multi-user support before adding users to your organization.`;
}
if (shouldValidateDomain && !verifiedDomains.length) {
return getDomainError();
}
if (MaxMembers - UsedMembers < 1) {
return c('Error').t`You have used all users in your plan. Please upgrade your plan to add a new user.`;
}
if (MaxAddresses - UsedAddresses < 1) {
return c('Error').t`You have used all addresses in your plan. Please upgrade your plan to add a new address.`;
}
if (shouldValidateSpace && MaxSpace - AssignedSpace < 1) {
return c('Error').t`All storage space has been allocated. Please reduce storage allocated to other users.`;
}
if (!privateUser) {
if (organizationKeyInfo.userNeedsToActivateKey) {
return c('Error').t`The organization key must be activated first.`;
}
if (organizationKeyInfo.userNeedsToReactivateKey) {
return c('Error').t`The organization key must be activated first.`;
}
if (!organizationKey?.privateKey) {
return c('Error').t`Organization key is not decrypted.`;
}
}
};
export default validateAddUser;
| 6,463
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/UsersAndAddressesSection/UsersAndAddressesSection.tsx
|
import { useMemo, useState } from 'react';
import { c, msgid } from 'ttag';
import { Avatar, Button } from '@proton/atoms';
import { revokeSessions } from '@proton/shared/lib/api/memberSessions';
import { removeMember, updateRole } from '@proton/shared/lib/api/members';
import { APP_NAMES, MEMBER_ROLE, MEMBER_TYPE } from '@proton/shared/lib/constants';
import { hasOrganizationSetup, hasOrganizationSetupWithKeys } from '@proton/shared/lib/helpers/organization';
import { getInitials, normalize } from '@proton/shared/lib/helpers/string';
import { getHasVpnB2BPlan, hasFamily, hasNewVisionary, hasVisionary } from '@proton/shared/lib/helpers/subscription';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { FAMILY_PLAN_INVITE_STATE, Member } from '@proton/shared/lib/interfaces';
import { getIsDomainActive } from '@proton/shared/lib/organization/helper';
import clsx from '@proton/utils/clsx';
import {
Badge,
Block,
Info,
SearchInput,
Table,
TableBody,
TableCell,
TableRow,
useModalState,
} from '../../../components';
import {
useApi,
useDomains,
useEventManager,
useMemberAddresses,
useMembers,
useNotifications,
useOrganization,
useOrganizationKey,
useSubscription,
useUser,
} from '../../../hooks';
import { SettingsParagraph, SettingsSectionWide } from '../../account';
import { AddressModal } from '../../addresses';
import RestoreAdministratorPrivileges from '../../organization/RestoreAdministratorPrivileges';
import { SUBSCRIPTION_STEPS, useSubscriptionModal } from '../../payments/subscription';
import ChangeMemberPasswordModal from '../ChangeMemberPasswordModal';
import InviteUserCreateSubUserModal from '../InviteUserCreateSubUserModal';
import LoginMemberModal, { validateMemberLogin } from '../LoginMemberModal';
import MemberActions from '../MemberActions';
import MemberAddresses from '../MemberAddresses';
import MemberFeatures from '../MemberFeatures';
import MemberRole from '../MemberRole';
import SubUserCreateModal from '../SubUserCreateModal';
import SubUserDeleteModal from '../SubUserDeleteModal';
import SubUserEditModal from '../SubUserEditModal';
import UserInviteOrEditModal from '../UserInviteOrEditModal';
import UserRemoveModal from '../UserRemoveModal';
import { UserManagementMode } from '../types';
import { getDomainError } from '../validateAddUser';
import UsersAndAddressesSectionHeader from './UsersAndAddressesSectionHeader';
const UsersAndAddressesSection = ({ app }: { app: APP_NAMES }) => {
const [organization, loadingOrganization] = useOrganization();
const [organizationKey, loadingOrganizationKey] = useOrganizationKey(organization);
const [domains, loadingDomains] = useDomains();
const [members, loadingMembers] = useMembers();
const [subscription] = useSubscription();
const [user] = useUser();
const [openSubscriptionModal] = useSubscriptionModal();
const [memberAddressesMap] = useMemberAddresses(members, true);
const [keywords, setKeywords] = useState('');
const [tmpMember, setTmpMember] = useState<Member | null>(null);
const api = useApi();
const { call } = useEventManager();
const hasReachedLimit = organization.InvitationsRemaining === 0;
const hasSetupOrganization = hasOrganizationSetup(organization);
const hasSetupOrganizationWithKeys = hasOrganizationSetupWithKeys(organization);
const hasVpnB2BPlan = getHasVpnB2BPlan(subscription);
const mode = hasVpnB2BPlan ? UserManagementMode.VPN_B2B : UserManagementMode.DEFAULT;
const canInviteProtonUsers = hasNewVisionary(subscription) || hasFamily(subscription);
const { createNotification } = useNotifications();
const cleanOption = {
onClose: () => setTmpMember(null),
};
const [addAddressModalProps, setAddAddressModalOpen, renderAddAddressModal] = useModalState();
const [subUserCreateModalProps, setSubUserCreateModalOpen, renderSubUserCreateModal] = useModalState();
const [subUserEditModalProps, setSubUserEditModalOpen, renderSubUserEditModal] = useModalState(cleanOption);
const [loginMemberModalProps, setLoginMemberModalOpen, renderLoginMemberModal] = useModalState(cleanOption);
const [changeMemberPasswordModalProps, setChangeMemberPasswordModalOpen, renderChangeMemberPasswordModal] =
useModalState(cleanOption);
const [subUserDeleteModalProps, setSubUserDeleteModalOpen, renderSubUserDeleteModal] = useModalState(cleanOption);
const [userRemoveModalProps, setUserRemoveModalOpen, renderUserRemoveModal] = useModalState(cleanOption);
const [inviteOrCreateUserModalProps, setInviteOrCreateUserModalOpen, renderInviteOrCreateUserModal] =
useModalState(cleanOption);
const [userInviteOrEditModalProps, setUserInviteOrEditModalOpen, renderUserInviteOrEditModal] =
useModalState(cleanOption);
const verifiedDomains = useMemo(() => (domains || []).filter(getIsDomainActive), [domains]);
const handleSearch = (value: string) => setKeywords(value);
const membersSelected = useMemo(() => {
if (!members) {
return [];
}
if (!keywords) {
return members;
}
const normalizedWords = normalize(keywords, true);
return members.filter((member) => {
const memberAddresses = memberAddressesMap?.[member.ID] || [];
const addressMatch = memberAddresses?.some((address) =>
normalize(address.Email, true).includes(normalizedWords)
);
const nameMatch = normalize(member.Name, true).includes(normalizedWords);
return addressMatch || nameMatch;
});
}, [keywords, members]);
const handleDeleteUserConfirm = async (member: Member) => {
if (member.Role === MEMBER_ROLE.ORGANIZATION_ADMIN) {
await api(updateRole(member.ID, MEMBER_ROLE.ORGANIZATION_MEMBER));
}
await api(removeMember(member.ID));
await call();
createNotification({ text: c('Success message').t`User deleted` });
};
const handleDeleteUser = (member: Member) => {
setTmpMember(member);
// We can remove members if the user is a Proton member (excluding logged user)
if (canInviteProtonUsers && member.Type === MEMBER_TYPE.PROTON && !member.Self) {
setUserRemoveModalOpen(true);
} else {
setSubUserDeleteModalOpen(true);
}
};
const handleRevokeUserSessions = async (member: Member) => {
await api(revokeSessions(member.ID));
await call();
createNotification({ text: c('Success message').t`Sessions revoked` });
};
const handleInviteUser = () => {
setUserInviteOrEditModalOpen(true);
};
const handleAddAddress = () => {
setAddAddressModalOpen(true);
};
const handleEditUser = (member: Member) => {
setTmpMember(member);
// We can open the invite modal if the user is a Proton member (excluding logged user)
if (canInviteProtonUsers && member.Type === MEMBER_TYPE.PROTON && !member.Self) {
setUserInviteOrEditModalOpen(true);
} else {
setSubUserEditModalOpen(true);
}
};
const handleAddUser = () => {
// Visionary can either create a sub user or invite existing users
if (hasVisionary(subscription) || hasNewVisionary(subscription) || hasFamily(subscription)) {
setInviteOrCreateUserModalOpen(true);
} else {
if (mode === UserManagementMode.DEFAULT && !verifiedDomains.length) {
createNotification({ text: getDomainError(), type: 'error' });
return;
}
setSubUserCreateModalOpen(true);
}
};
const handleLoginUser = (member: Member) => {
const error = validateMemberLogin(organization, organizationKey);
if (error) {
return createNotification({ type: 'error', text: error });
}
setTmpMember(member);
setLoginMemberModalOpen(true);
};
const handleChangeMemberPassword = (member: Member) => {
const error = validateMemberLogin(organization, organizationKey);
if (error) {
return createNotification({ type: 'error', text: error });
}
setTmpMember(member);
setChangeMemberPasswordModalOpen(true);
};
const handleGetMoreLicense = () => {
openSubscriptionModal({
step: SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION,
disablePlanSelection: true,
metrics: {
source: 'vpn-um-get-more',
},
});
};
const userFound = membersSelected.length;
const tableLabel = [
'',
<>
<span className="mr-2">{c('Title header for members table').t`Role`}</span>
<Info url={getKnowledgeBaseUrl('/user-roles')} />
</>,
c('Title header for members table').t`Addresses`,
c('Title header for members table').t`Features`,
'',
];
const disableInviteUserButton = loadingOrganization || loadingDomains || hasReachedLimit;
const disableAddUserButton =
loadingOrganization ||
loadingDomains ||
loadingOrganizationKey ||
organization.UsedMembers === organization.MaxMembers;
const loadingAddAddresses = loadingOrganization || loadingDomains || loadingOrganizationKey || loadingMembers;
const settingsTitle = (() => {
if (hasFamily(subscription)) {
return c('familyOffer_2023:Info for members section')
.t`Add, remove, and make changes to user accounts in your family group.`;
}
if (hasVpnB2BPlan) {
return c('Info').ngettext(
msgid`You are currently using ${organization.UsedMembers} of your ${organization.MaxMembers} available user license.`,
`You are currently using ${organization.UsedMembers} of your ${organization.MaxMembers} available user licenses.`,
organization.MaxMembers
);
}
return c('familyOffer_2023:Info for members section')
.t`Add, remove, and make changes to user accounts in your organization.`;
})();
return (
<SettingsSectionWide>
<RestoreAdministratorPrivileges />
<SettingsParagraph large className="flex flex-align-items-baseline mb-6">
{settingsTitle}
{hasVpnB2BPlan && user.canPay && (
<Button className="ml-2" shape="outline" color="norm" size="small" onClick={handleGetMoreLicense}>
{c('Action').t`Get more licenses`}
</Button>
)}
</SettingsParagraph>
<Block className="flex flex-align-items-start">
{renderAddAddressModal && members && (
<AddressModal members={members} organizationKey={organizationKey} {...addAddressModalProps} />
)}
{renderSubUserDeleteModal && tmpMember && (
<SubUserDeleteModal
member={tmpMember}
onDelete={handleDeleteUserConfirm}
mode={mode}
{...subUserDeleteModalProps}
/>
)}
{renderUserRemoveModal && tmpMember && (
<UserRemoveModal member={tmpMember} organization={organization} {...userRemoveModalProps} />
)}
{renderSubUserCreateModal && organizationKey && (
<SubUserCreateModal
organization={organization}
organizationKey={organizationKey}
verifiedDomains={verifiedDomains}
mode={mode}
app={app}
{...subUserCreateModalProps}
/>
)}
{renderSubUserEditModal && tmpMember && (
<SubUserEditModal member={tmpMember} mode={mode} {...subUserEditModalProps} />
)}
{renderUserInviteOrEditModal && (
<UserInviteOrEditModal
member={tmpMember}
organization={organization}
domains={verifiedDomains}
{...userInviteOrEditModalProps}
/>
)}
{renderLoginMemberModal && tmpMember && (
<LoginMemberModal app={app} member={tmpMember} {...loginMemberModalProps} />
)}
{renderChangeMemberPasswordModal && tmpMember && (
<ChangeMemberPasswordModal member={tmpMember} {...changeMemberPasswordModalProps} />
)}
{renderInviteOrCreateUserModal && (
<InviteUserCreateSubUserModal
organization={organization}
organizationKey={organizationKey}
verifiedDomains={verifiedDomains}
onInviteUser={handleInviteUser}
app={app}
{...inviteOrCreateUserModalProps}
/>
)}
<div className="flex flex-align-items-center mb-6 lg:mb-0 gap-4">
{hasSetupOrganization && (
<Button color="norm" disabled={disableInviteUserButton} onClick={handleInviteUser}>
{c('Action').t`Invite user`}
</Button>
)}
{hasSetupOrganizationWithKeys && (
<Button color="norm" disabled={disableAddUserButton} onClick={handleAddUser}>
{c('Action').t`Add user`}
</Button>
)}
{/* Only family and visionary can invite existing Proton users */}
{canInviteProtonUsers &&
(hasReachedLimit ? (
<Info
className="color-danger"
title={c('familyOffer_2023:Family plan')
.t`You have reached the limit of 10 accepted invitations in 6 months.`}
/>
) : (
<Info
title={c('familyOffer_2023:Family plan')
.t`Only 10 accepted invitations are allowed in a 6-month period.`}
/>
))}
{hasVpnB2BPlan ? null : (
<Button shape="outline" disabled={loadingAddAddresses} onClick={handleAddAddress}>
{c('Action').t`Add address`}
</Button>
)}
</div>
<div className="ml-0 lg:ml-auto w-full lg:w-custom" style={{ '--lg-w-custom': '24em' }}>
<SearchInput
onChange={handleSearch}
placeholder={c('Placeholder').t`Search for a user or address`}
value={keywords}
aria-label={c('Placeholder').t`Search users`}
/>
</div>
</Block>
<span className="sr-only" aria-live="polite" aria-atomic="true">
{c('Info').ngettext(msgid`${userFound} user found`, `${userFound} users found`, userFound)}
</span>
<Table hasActions responsive="cards" data-testid="users-and-addresses-table">
<thead>
<tr>
<UsersAndAddressesSectionHeader mode={mode} />
</tr>
</thead>
<TableBody loading={loadingMembers} colSpan={hasVpnB2BPlan ? 4 : 5}>
{membersSelected.map((member) => {
const memberAddresses = memberAddressesMap?.[member.ID] || [];
const isInvitationPending = !!(member.State === FAMILY_PLAN_INVITE_STATE.STATUS_INVITED);
const roleCell = (
<TableCell
className="text-cut"
data-testid="users-and-addresses-table:memberRole"
style={{ verticalAlign: 'baseline' }}
>
<div className="flex flex-column flex-nowrap flex-item-align-baseline">
<MemberRole member={member} />
{isInvitationPending && (
<span>
<Badge type="origin" className="rounded-sm color-weak">{c(
'familyOffer_2023:Family plan'
).t`Pending`}</Badge>
</span>
)}
</div>
</TableCell>
);
const memberName = (() => {
if (hasFamily(subscription) && member.Role === MEMBER_ROLE.ORGANIZATION_ADMIN) {
return member?.Addresses?.[0]?.Email || member.Name;
}
return member.Name;
})();
return (
<TableRow
key={member.ID}
labels={tableLabel}
className={clsx('align-top', isInvitationPending && 'color-weak')}
>
<TableCell style={{ verticalAlign: 'baseline' }}>
<div className="flex flex-align-items-center gap-3">
<Avatar className="flex-item-noshrink text-rg" color="weak">
{getInitials(memberName)}
</Avatar>
<div
className="text-ellipsis flex-item-fluid min-w-custom"
style={{ '--min-w-custom': '6rem' }}
data-testid="users-and-addresses-table:memberName"
title={memberName}
>
{memberName}
</div>
<div className="flex flex-align-items-center gap-1">
{!hasVpnB2BPlan && Boolean(member.Private) && !hasFamily(subscription) && (
<Badge
type="origin"
className="rounded-sm"
data-testid="users-and-addresses-table:memberIsPrivate"
>
{c('Private Member').t`private`}
</Badge>
)}
{member['2faStatus'] > 0 && (
<Badge type="origin" className="rounded-sm">
{c('Enabled 2FA').t`2FA`}
</Badge>
)}
{member.SSO > 0 && (
<Badge
type="success"
className="rounded-sm"
tooltip={c('Users table: single sign-on tooltip')
.t`SSO user provided by your Identity Provider`}
>
{c('Users table: single sign-on enabled').t`SSO`}
</Badge>
)}
</div>
</div>
</TableCell>
{!hasVpnB2BPlan && roleCell}
<TableCell style={{ verticalAlign: 'baseline' }}>
<div>
{member.State && member.State === FAMILY_PLAN_INVITE_STATE.STATUS_INVITED ? (
<p className="m-0 text-ellipsis">{member.Name}</p>
) : (
<MemberAddresses addresses={memberAddresses} />
)}
</div>
</TableCell>
{hasVpnB2BPlan && roleCell}
{!hasVpnB2BPlan && (
<TableCell>
<MemberFeatures member={member} organization={organization} />
</TableCell>
)}
<TableCell style={{ verticalAlign: 'baseline' }}>
<MemberActions
onEdit={handleEditUser}
onDelete={handleDeleteUser}
onRevoke={handleRevokeUserSessions}
onLogin={handleLoginUser}
onChangePassword={handleChangeMemberPassword}
member={member}
addresses={memberAddresses}
organization={organization}
organizationKey={organizationKey}
mode={mode}
/>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</SettingsSectionWide>
);
};
export default UsersAndAddressesSection;
| 6,464
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/UsersAndAddressesSection/UsersAndAddressesSectionHeader.tsx
|
import React from 'react';
import { c } from 'ttag';
import { Info, TableCell } from '@proton/components/components';
import { vpnB2bAdminTooltipTitle } from '@proton/components/containers/members/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import isTruthy from '@proton/utils/isTruthy';
import { UserManagementMode } from '../types';
type HeaderCellItem = {
key: string;
node: string | React.JSX.Element;
className?: string;
style?: React.CSSProperties;
};
const UsersAndAddressesSectionHeader = ({ mode }: { mode: UserManagementMode }) => {
const roleCell: HeaderCellItem = {
key: 'role',
node: (
<div className="flex gap-2 flex-flex-children flex-align-items-center">
<span>{c('Title header for members table').t`Role`}</span>
<span className="hidden md:inline">
<Info
title={mode === UserManagementMode.VPN_B2B ? vpnB2bAdminTooltipTitle : undefined}
url={mode === UserManagementMode.DEFAULT ? getKnowledgeBaseUrl('/user-roles') : undefined}
/>
</span>
</div>
),
className: 'w-1/6',
};
const addressTitle =
mode === UserManagementMode.VPN_B2B
? c('Title header for members table').t`Email`
: c('Title header for members table').t`Addresses`;
const headerCells: HeaderCellItem[] = [
{ key: 'name', node: c('Title header for members table').t`Name`, className: 'w-3/10' },
mode === UserManagementMode.DEFAULT && roleCell,
{
key: 'addresses',
node: (
<>
<span className="text-ellipsis inline-block align-bottom max-w-full" title={addressTitle}>
{addressTitle}
</span>
</>
),
className: 'w-1/4',
},
mode === UserManagementMode.VPN_B2B && roleCell,
mode === UserManagementMode.DEFAULT && {
key: 'features',
node: (
<>
<span
className="text-ellipsis inline-block align-bottom max-w-full"
title={c('Title header for members table').t`Features`}
>{c('Title header for members table').t`Features`}</span>
</>
),
className: 'w-1/4',
},
{ key: 'actions', node: '', className: 'w-1/6' },
].filter(isTruthy);
return (
<>
{headerCells.map(({ key, node, className = '' }) => (
<TableCell key={key} className={className} type="header">
{node}
</TableCell>
))}
</>
);
};
export default UsersAndAddressesSectionHeader;
| 6,465
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/MultiUserCreationSection.tsx
|
import { useMemo, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { useModalState } from '@proton/components/components/modalTwo';
import { Tooltip } from '@proton/components/components/tooltip';
import { UserManagementMode } from '@proton/components/containers/members/types';
import useDomains from '@proton/components/hooks/useDomains';
import { APP_NAMES } from '@proton/shared/lib/constants';
import { getIsDomainActive } from '@proton/shared/lib/organization/helper';
import { SettingsParagraph, SettingsSectionWide } from '../../account';
import CreateUserAccountsModal from './CreateUserAccountsModal/CreateUserAccountsModal';
import UploadCSVFileButton from './UploadCSVFileButton';
import { downloadSampleCSV } from './csv';
import { UserTemplate } from './types';
const MultiUserCreationSection = ({ app }: { app: APP_NAMES }) => {
const [domains = []] = useDomains();
const [usersToImport, setUsersToImport] = useState<UserTemplate[]>();
const [createUserAccountsModal, setCreateUserAccountsModal, renderCreateUserAccountsModal] = useModalState();
const verifiedDomains = useMemo(() => (domains || []).filter(getIsDomainActive), [domains]);
const onCSVFileUpload = (usersToImport: UserTemplate[]) => {
setUsersToImport(usersToImport);
setCreateUserAccountsModal(true);
};
return (
<>
{renderCreateUserAccountsModal && usersToImport && (
<CreateUserAccountsModal
usersToImport={usersToImport}
app={app}
verifiedDomains={verifiedDomains}
{...createUserAccountsModal}
mode={UserManagementMode.DEFAULT}
/>
)}
<SettingsSectionWide>
<SettingsParagraph>{c('Info').t`Add multiple users to your organization at once.`}</SettingsParagraph>
<SettingsParagraph className="mb-4">
{c('Info')
.t`Download our CSV template, fill in the user details, and then upload your completed CSV file to create accounts for these users.`}
</SettingsParagraph>
<div className="flex flex-rows gap-4">
{verifiedDomains.length === 0 ? (
<Tooltip
title={c('familyOffer_2023:Family plan')
.t`You need to configure a custom domain before adding multiple users.`}
>
<span>
<Button disabled>{c('Select file').t`Upload CSV file`}</Button>
</span>
</Tooltip>
) : (
<UploadCSVFileButton onUpload={onCSVFileUpload} color="norm" />
)}
<Button onClick={downloadSampleCSV}>{c('Action').t`Download CSV sample`}</Button>
</div>
</SettingsSectionWide>
</>
);
};
export default MultiUserCreationSection;
| 6,466
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/constants.ts
|
import { BASE_SIZE } from '@proton/shared/lib/constants';
export const MAX_FILENAME_CHARS_DISPLAY = 100;
export const MAX_IMPORT_FILE_SIZE = 10 * BASE_SIZE ** 2;
export const MAX_IMPORT_FILE_SIZE_STRING = '10 MB';
export const MAX_NUMBER_OF_USER_ROWS = 750;
| 6,467
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/csv.test.ts
|
import { BASE_SIZE, GIGA } from '@proton/shared/lib/constants';
import { UserManagementMode } from '../types';
import { getSampleCSV, getVpnB2BSampleCSV, parseMultiUserCsv } from './csv';
import { CSV_CONVERSION_ERROR_TYPE } from './errors/CsvConversionError';
import { ExportedCSVUser, ExportedVpnB2BCSVUser } from './types';
describe('multi user upload csv.ts', () => {
const defaultFileName = 'filename';
const getFile = (fileContent: string, filename: string = defaultFileName) => {
const blob = new Blob([fileContent]);
return new File([blob], filename);
};
describe('parseMultiUserCsv (default)', () => {
const defaultUser: ExportedCSVUser = {
DisplayName: 'Alice',
EmailAddresses: 'alice@mydomain.com',
Password: 'alice_password',
TotalStorage: GIGA,
VPNAccess: 1,
PrivateSubUser: 0,
};
const defaultCsvFields = `DisplayName,EmailAddresses,Password,TotalStorage,VPNAccess,PrivateSubUser`;
const mode = UserManagementMode.DEFAULT;
describe('errors', () => {
it('throws error if no files are passed', async () => {
await expect(parseMultiUserCsv([], mode)).rejects.toThrow(
'An error occurred uploading your file. No file has been selected.'
);
});
it('throws error if file is empty', async () => {
const filename = 'filename';
const file = new File([], filename);
await expect(parseMultiUserCsv([file], mode)).rejects.toThrow('Your file "filename" is empty.');
});
it('throws error if file is > 10MB', async () => {
const file = getFile(getSampleCSV([defaultUser]));
/**
* Mock large file size
*/
Object.defineProperty(file, 'size', { value: 10 * BASE_SIZE ** 2 + 1 });
await expect(parseMultiUserCsv([file], mode)).rejects.toThrow(
'An error occurred uploading your file "filename". Maximum file size is 10 MB.'
);
});
it('does not throw error if file is <= 10MB', async () => {
const file = getFile(getSampleCSV([defaultUser]));
/**
* Mock ok file size
*/
Object.defineProperty(file, 'size', { value: 10 * BASE_SIZE ** 2 });
await expect(parseMultiUserCsv([file], mode)).resolves.not.toThrow(
'An error occurred uploading your file "filename". Maximum file size is 10 MB.'
);
});
it('throws error if there are > 750 rows', async () => {
const rows = Array.from({ length: 751 }, () => defaultUser);
const file = getFile(getSampleCSV(rows));
await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError(
'Upload a CSV file with 750 user accounts or less.'
);
});
it('does not throw error if there are <= 750 rows', async () => {
const rows = Array.from({ length: 750 }, () => defaultUser);
const file = getFile(getSampleCSV(rows));
await expect(parseMultiUserCsv([file], mode)).resolves.not.toThrowError(
'Upload a CSV file with 750 user accounts or less.'
);
});
it('throws error if the EmailAddress field is not defined', async () => {
const fileContent = ['Password', 'alice_password'].join('\n');
const file = getFile(fileContent);
await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError(
`It looks like your file is missing the 'EmailAddresses' header.`
);
});
it('throws error if the Password field is not defined', async () => {
const fileContent = ['EmailAddresses', 'alice@mydomain.com'].join('\n');
const file = getFile(fileContent);
await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError(
`It looks like your file is missing the 'Password' header.`
);
});
it('throws error if a row contains too few fields', async () => {
const fileContent = [defaultCsvFields, 'alice@mydomain.com,alice_password,1073741824,1,0'].join('\n');
const file = getFile(fileContent);
await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError('Error on row 1.');
});
it('throws error if a row contains too many fields', async () => {
const fileContent = [
defaultCsvFields,
'Alice,alice@mydomain.com,alice_password,1073741824,1,0' + ',ExtraItem',
].join('\n');
const file = getFile(fileContent);
await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError('Error on row 1.');
});
});
describe('parsing', () => {
it('parses the sample CSV with no errors', async () => {
const file = getFile(getSampleCSV());
const result = await parseMultiUserCsv([file], mode);
expect(result.errors.length).toBe(0);
});
it('trims whitespace', async () => {
const fileContent = [
` DisplayName , EmailAddresses,Password ,TotalStorage , VPNAccess,PrivateSubUser `,
/**
* `Alice,"` must be of this form - it will parse incorrectly if there is a space before the `"" ie `Alice, "`
*/
` Alice," alice1@mydomain.com , alice2@mydomain.com ",alice_password, 2 ,1 ,0 `,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.id).toBe('1');
expect(user.displayName).toBe('Alice');
expect(user.emailAddresses.length).toBe(2);
expect(user.emailAddresses[0]).toBe('alice1@mydomain.com');
expect(user.emailAddresses[1]).toBe('alice2@mydomain.com');
expect(user.password).toBe('alice_password');
expect(user.totalStorage).toBe(2 * GIGA);
expect(user.vpnAccess).toBe(true);
expect(user.privateSubUser).toBe(false);
});
describe('id', () => {
it('equals the row number', async () => {
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password,1073741824,1,0`,
`Bob,bob@mydomain.com,bob_password,1073741824,1,0`,
`Charlie,charlie@mydomain.com,charlie_password,1073741824,1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
expect(result.errors.length).toBe(0);
expect(result.users[0].id).toBe('1');
expect(result.users[1].id).toBe('2');
expect(result.users[2].id).toBe('3');
});
});
describe('displayName', () => {
it('returns no errors if display name is a string', async () => {
const displayName = 'Alice';
const fileContent = [
defaultCsvFields,
`${displayName},alice@mydomain.com,alice_password,1073741824,1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.displayName).toBe('Alice');
});
it('defaults to first address if DisplayName is missing', async () => {
const displayName = '';
const fileContent = [
defaultCsvFields,
`${displayName},alice@mydomain.com,alice_password,1073741824,1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.displayName).toBe('alice@mydomain.com');
});
it('casts to a string', async () => {
const displayName = 123;
const fileContent = [
defaultCsvFields,
`${displayName},alice@mydomain.com,alice_password,1073741824,1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.displayName).toBe('123');
});
});
describe('emailAddresses', () => {
it('adds error if no email addresses are defined', async () => {
const emailAddresses = '';
const fileContent = [
defaultCsvFields,
`Alice,${emailAddresses},alice_password,1073741824,1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
expect(result.errors.length).toBe(1);
expect(result.errors[0].rowNumber).toBe(1);
expect(result.errors[0].type).toBe(CSV_CONVERSION_ERROR_TYPE.EMAIL_REQUIRED);
});
it('returns no errors if emailAddresses is a string', async () => {
const emailAddresses = 'alice@mydomain.com';
const fileContent = [
defaultCsvFields,
`Alice,${emailAddresses},alice_password,1073741824,1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.emailAddresses.length).toBe(1);
expect(user.emailAddresses[0]).toBe('alice@mydomain.com');
});
it('parses a list of email addresses', async () => {
const emailAddresses = ['alice1@mydomain.com', 'alice2@mydomain.com'];
const fileContent = [
defaultCsvFields,
`Alice,"${emailAddresses.join(',')}",alice_password,1073741824,1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.emailAddresses.length).toBe(2);
expect(user.emailAddresses[0]).toBe('alice1@mydomain.com');
expect(user.emailAddresses[1]).toBe('alice2@mydomain.com');
});
it('is considered to be defined if set to falsy 0 value', async () => {
const emailAddresses = 0;
const fileContent = [
defaultCsvFields,
`Alice,${emailAddresses},alice_password,1073741824,1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.emailAddresses.length).toBe(1);
expect(user.emailAddresses[0]).toBe('0');
});
it('casts to a string', async () => {
const emailAddresses = 123;
const fileContent = [
defaultCsvFields,
`Alice,${emailAddresses},alice_password,1073741824,1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.emailAddresses.length).toBe(1);
expect(user.emailAddresses[0]).toBe('123');
});
});
describe('password', () => {
it('adds error if no password is defined', async () => {
const password = '';
const fileContent = [defaultCsvFields, `Alice,alice@mydomain.com,${password},1073741824,1,0`].join(
'\n'
);
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
expect(result.errors.length).toBe(1);
expect(result.errors[0].rowNumber).toBe(1);
expect(result.errors[0].type).toBe(CSV_CONVERSION_ERROR_TYPE.PASSWORD_REQUIRED);
});
it('returns no errors if password is a string', async () => {
const password = 'alice_password';
const fileContent = [defaultCsvFields, `Alice,alice@mydomain.com,${password},1073741824,1,0`].join(
'\n'
);
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.password).toBe('alice_password');
});
it('is considered to be defined if set to falsy 0 value', async () => {
const password = 0;
const fileContent = [defaultCsvFields, `Alice,alice@mydomain.com,${password},1073741824,1,0`].join(
'\n'
);
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.password).toBe(`0`);
});
it('casts to a string', async () => {
const password = 123;
const fileContent = [defaultCsvFields, `Alice,alice@mydomain.com,${password},1073741824,1,0`].join(
'\n'
);
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.password).toBe(`123`);
});
});
describe('totalStorage', () => {
it('returns no errors if set to a valid number', async () => {
const totalStorage = '123';
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password,${totalStorage},1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.totalStorage).toBe(123 * GIGA);
});
it('uses default if value is not a valid number', async () => {
const totalStorage = 'not a number';
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password,${totalStorage},1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.totalStorage).toBe(0);
});
it('defaults to 0', async () => {
const fileContent = ['EmailAddresses,Password', `alice@mydomain.com,alice_password`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.totalStorage).toBe(0);
});
it('allows decimal values', async () => {
const totalStorage = 1.5;
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password,${totalStorage},1,0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.totalStorage).toBe(1.5 * GIGA);
});
});
describe('vpnAccess', () => {
it('returns no errors if set to 0', async () => {
const vpnAccess = 0;
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password,1073741824,${vpnAccess},0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.vpnAccess).toBe(false);
});
it('returns no errors if set to 1', async () => {
const vpnAccess = 1;
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password,1073741824,${vpnAccess},0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.vpnAccess).toBe(true);
});
it('uses default if value is not a valid number', async () => {
const vpnAccess = 'not a number';
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password,1073741824,${vpnAccess},0`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.vpnAccess).toBe(false);
});
it('defaults to false', async () => {
const fileContent = ['EmailAddresses,Password', `alice@mydomain.com,alice_password`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.vpnAccess).toBe(false);
});
});
describe('privateSubUser', () => {
it('returns no errors if set to 0', async () => {
const privateSubUser = 0;
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password,1073741824,1,${privateSubUser}`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.privateSubUser).toBe(false);
});
it('returns no errors if set to 1', async () => {
const privateSubUser = 1;
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password,1073741824,1,${privateSubUser}`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.privateSubUser).toBe(true);
});
it('uses default if value is not a valid number', async () => {
const privateSubUser = 'not a number';
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password,1073741824,1,${privateSubUser}`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.privateSubUser).toBe(false);
});
it('defaults to false', async () => {
const fileContent = ['EmailAddresses,Password', `alice@mydomain.com,alice_password`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.privateSubUser).toBe(false);
});
});
});
});
describe('parseMultiUserCsv (VPN B2B)', () => {
const defaultUser: ExportedVpnB2BCSVUser = {
Name: 'Alice',
EmailAddress: 'alice@mydomain.com',
Password: 'alice_password',
};
const mode = UserManagementMode.VPN_B2B;
const defaultCsvFields = `Name,EmailAddress,Password`;
describe('errors', () => {
it('throws error if no files are passed', async () => {
await expect(parseMultiUserCsv([], mode)).rejects.toThrow(
'An error occurred uploading your file. No file has been selected.'
);
});
it('throws error if file is empty', async () => {
const filename = 'filename';
const file = new File([], filename);
await expect(parseMultiUserCsv([file], mode)).rejects.toThrow('Your file "filename" is empty.');
});
it('throws error if file is > 10MB', async () => {
const file = getFile(getVpnB2BSampleCSV([defaultUser]));
/**
* Mock large file size
*/
Object.defineProperty(file, 'size', { value: 10 * BASE_SIZE ** 2 + 1 });
await expect(parseMultiUserCsv([file], mode)).rejects.toThrow(
'An error occurred uploading your file "filename". Maximum file size is 10 MB.'
);
});
it('does not throw error if file is <= 10MB', async () => {
const file = getFile(getVpnB2BSampleCSV([defaultUser]));
/**
* Mock ok file size
*/
Object.defineProperty(file, 'size', { value: 10 * BASE_SIZE ** 2 });
await expect(parseMultiUserCsv([file], mode)).resolves.not.toThrow(
'An error occurred uploading your file "filename". Maximum file size is 10 MB.'
);
});
it('throws error if there are > 750 rows', async () => {
const rows = Array.from({ length: 751 }, () => defaultUser);
const file = getFile(getVpnB2BSampleCSV(rows));
await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError(
'Upload a CSV file with 750 user accounts or less.'
);
});
it('does not throw error if there are <= 750 rows', async () => {
const rows = Array.from({ length: 750 }, () => defaultUser);
const file = getFile(getVpnB2BSampleCSV(rows));
await expect(parseMultiUserCsv([file], mode)).resolves.not.toThrowError(
'Upload a CSV file with 750 user accounts or less.'
);
});
it('throws error if the EmailAddress field is not defined', async () => {
const fileContent = ['Password', 'alice_password'].join('\n');
const file = getFile(fileContent);
await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError(
`It looks like your file is missing the 'EmailAddress' header.`
);
});
it('throws error if the Password field is not defined', async () => {
const fileContent = ['EmailAddress', 'alice@mydomain.com'].join('\n');
const file = getFile(fileContent);
await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError(
`It looks like your file is missing the 'Password' header.`
);
});
it('throws error if a row contains too few fields', async () => {
const fileContent = [defaultCsvFields, 'alice@mydomain.com,alice_password'].join('\n');
const file = getFile(fileContent);
await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError('Error on row 1.');
});
it('throws error if a row contains too many fields', async () => {
const fileContent = [
defaultCsvFields,
'Alice,alice@mydomain.com,alice_password,1073741824,1,0' + ',ExtraItem',
].join('\n');
const file = getFile(fileContent);
await expect(parseMultiUserCsv([file], mode)).rejects.toThrowError('Error on row 1.');
});
});
describe('parsing', () => {
it('parses the sample CSV with no errors', async () => {
const file = getFile(getVpnB2BSampleCSV());
const result = await parseMultiUserCsv([file], mode);
expect(result.errors.length).toBe(0);
});
it('trims whitespace', async () => {
const fileContent = [
` Name , EmailAddress,Password `,
/**
* `Alice,"` must be of this form - it will parse incorrectly if there is a space before the `"" ie `Alice, "`
*/
` Alice, alice@mydomain.com ,alice_password`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.id).toBe('1');
expect(user.displayName).toBe('Alice');
expect(user.emailAddresses.length).toBe(1);
expect(user.emailAddresses[0]).toBe('alice@mydomain.com');
expect(user.password).toBe('alice_password');
});
describe('id', () => {
it('equals the row number', async () => {
const fileContent = [
defaultCsvFields,
`Alice,alice@mydomain.com,alice_password`,
`Bob,bob@mydomain.com,bob_password`,
`Charlie,charlie@mydomain.com,charlie_password`,
].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
expect(result.errors.length).toBe(0);
expect(result.users[0].id).toBe('1');
expect(result.users[1].id).toBe('2');
expect(result.users[2].id).toBe('3');
});
});
describe('name', () => {
it('returns no errors if Name is a string', async () => {
const name = 'Alice';
const fileContent = [defaultCsvFields, `${name},alice@mydomain.com,alice_password`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.displayName).toBe('Alice');
});
it('defaults to address if Name is missing', async () => {
const name = '';
const fileContent = [defaultCsvFields, `${name},alice@mydomain.com,alice_password`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.displayName).toBe('alice@mydomain.com');
});
it('casts to a string', async () => {
const name = 123;
const fileContent = [defaultCsvFields, `${name},alice@mydomain.com,alice_password`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.displayName).toBe('123');
});
});
describe('emailAddress', () => {
it('adds error if no email addresses are defined', async () => {
const emailAddress = '';
const fileContent = [defaultCsvFields, `Alice,${emailAddress},alice_password`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
expect(result.errors.length).toBe(1);
expect(result.errors[0].rowNumber).toBe(1);
expect(result.errors[0].type).toBe(CSV_CONVERSION_ERROR_TYPE.EMAIL_REQUIRED);
});
it('returns no errors if emailAddress is a string', async () => {
const emailAddress = 'alice@mydomain.com';
const fileContent = [defaultCsvFields, `Alice,${emailAddress},alice_password`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.emailAddresses.length).toBe(1);
expect(user.emailAddresses[0]).toBe('alice@mydomain.com');
});
it('should throw error if email address is a list', async () => {
const emailAddress = ['alice1@mydomain.com', 'alice2@mydomain.com'];
const fileContent = [defaultCsvFields, `Alice,"${emailAddress.join(',')}",alice_password`].join(
'\n'
);
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
expect(result.errors.length).toBe(1);
expect(result.errors[0].rowNumber).toBe(1);
expect(result.errors[0].type).toBe(CSV_CONVERSION_ERROR_TYPE.INVALID_TYPE);
});
it('is considered to be defined if set to falsy 0 value', async () => {
const emailAddresses = 0;
const fileContent = [defaultCsvFields, `Alice,${emailAddresses},alice_password`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.emailAddresses.length).toBe(1);
expect(user.emailAddresses[0]).toBe('0');
});
it('casts to a string', async () => {
const emailAddresses = 123;
const fileContent = [defaultCsvFields, `Alice,${emailAddresses},alice_password`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.emailAddresses.length).toBe(1);
expect(user.emailAddresses[0]).toBe('123');
});
});
describe('password', () => {
it('adds error if no password is defined', async () => {
const password = '';
const fileContent = [defaultCsvFields, `Alice,alice@mydomain.com,${password}`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
expect(result.errors.length).toBe(1);
expect(result.errors[0].rowNumber).toBe(1);
expect(result.errors[0].type).toBe(CSV_CONVERSION_ERROR_TYPE.PASSWORD_REQUIRED);
});
it('returns no errors if password is a string', async () => {
const password = 'alice_password';
const fileContent = [defaultCsvFields, `Alice,alice@mydomain.com,${password}`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.password).toBe('alice_password');
});
it('is considered to be defined if set to falsy 0 value', async () => {
const password = 0;
const fileContent = [defaultCsvFields, `Alice,alice@mydomain.com,${password}`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.password).toBe(`0`);
});
it('casts to a string', async () => {
const password = 123;
const fileContent = [defaultCsvFields, `Alice,alice@mydomain.com,${password}`].join('\n');
const file = getFile(fileContent);
const result = await parseMultiUserCsv([file], mode);
const user = result.users[0];
expect(result.errors.length).toBe(0);
expect(user.password).toBe(`123`);
});
});
});
});
});
| 6,468
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/csv.ts
|
import Papa, { ParseLocalConfig, ParseResult } from 'papaparse';
import { GIGA } from '@proton/shared/lib/constants';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import { UserManagementMode } from '../types';
import { MAX_IMPORT_FILE_SIZE, MAX_NUMBER_OF_USER_ROWS } from './constants';
import CsvConversionError, { CSV_CONVERSION_ERROR_TYPE } from './errors/CsvConversionError';
import { CSV_FORMAT_ERROR_TYPE, CsvFormatError, TooManyUsersError } from './errors/CsvFormatErrors';
import ImportFileError, { IMPORT_ERROR_TYPE } from './errors/ImportFileError';
import { ExportedCSVUser, ExportedVpnB2BCSVUser, ImportedCSVUser, UserTemplate } from './types';
const parseCsv = async <T>(file: File, config: Omit<ParseLocalConfig<T>, 'complete' | 'error'> = {}) =>
new Promise<ParseResult<T>>((resolve, reject) => {
Papa.parse(file, {
...config,
complete: resolve,
error: reject,
});
});
const toCsv = <T>(data: T[]) => Papa.unparse(data);
const convertCSVUser = (csvUser: ImportedCSVUser, rowNumber: number, mode: UserManagementMode) => {
const { EmailAddresses, Password, DisplayName, TotalStorage, VPNAccess = 0, PrivateSubUser = 0 } = csvUser;
if (!EmailAddresses || typeof EmailAddresses !== 'string') {
throw new CsvConversionError(CSV_CONVERSION_ERROR_TYPE.EMAIL_REQUIRED);
}
if (!Password || typeof Password !== 'string') {
throw new CsvConversionError(CSV_CONVERSION_ERROR_TYPE.PASSWORD_REQUIRED);
}
const emailAddresses = EmailAddresses.split(',').map((item) => item.trim());
if (mode === UserManagementMode.VPN_B2B && emailAddresses.length > 1) {
throw new CsvConversionError(CSV_CONVERSION_ERROR_TYPE.INVALID_TYPE);
}
const displayName = (() => {
if (!DisplayName || typeof DisplayName !== 'string') {
return emailAddresses[0];
}
return DisplayName;
})();
const totalStorage = (() => {
const totalStorageNumber = +TotalStorage;
if (isNaN(totalStorageNumber)) {
return 0;
}
return totalStorageNumber * GIGA;
})();
const vpnAccess = (() => {
const vpnAccessNumber = +VPNAccess;
if (isNaN(vpnAccessNumber)) {
return 0;
}
return vpnAccessNumber;
})();
if (vpnAccess !== 0 && vpnAccess !== 1) {
throw new CsvConversionError(CSV_CONVERSION_ERROR_TYPE.INVALID_TYPE);
}
const privateSubUser = (() => {
const privateSubUserNumber = +PrivateSubUser;
if (isNaN(privateSubUserNumber)) {
return 0;
}
return privateSubUserNumber;
})();
if (privateSubUser !== 0 && privateSubUser !== 1) {
throw new CsvConversionError(CSV_CONVERSION_ERROR_TYPE.INVALID_TYPE);
}
const user: UserTemplate = {
id: `${rowNumber}`,
emailAddresses,
password: Password,
displayName,
totalStorage,
vpnAccess: Boolean(vpnAccess),
privateSubUser: Boolean(privateSubUser),
};
return user;
};
const convertCSVUsers = (csvUsers: ImportedCSVUser[], mode: UserManagementMode) => {
const users: UserTemplate[] = [];
const errors: {
type: CSV_CONVERSION_ERROR_TYPE;
rowNumber: number;
}[] = [];
csvUsers.forEach((csvUser, index) => {
const rowNumber = index + 1;
try {
const convertedUser = convertCSVUser(csvUser, rowNumber, mode);
users.push(convertedUser);
} catch (error: any) {
if (error instanceof CsvConversionError) {
errors.push({
type: error.type,
rowNumber,
});
}
}
});
return {
users,
errors,
};
};
const headerMap: Record<UserManagementMode, Partial<Record<keyof ImportedCSVUser, string>>> = {
[UserManagementMode.DEFAULT]: {},
[UserManagementMode.VPN_B2B]: {
EmailAddresses: 'EmailAddress',
DisplayName: 'Name',
},
};
export const parseMultiUserCsv = async (files: File[], mode: UserManagementMode) => {
if (files.length === 0) {
throw new ImportFileError(IMPORT_ERROR_TYPE.NO_FILE_SELECTED);
}
const [file] = files;
const filename = file.name;
if (!file.size) {
throw new ImportFileError(IMPORT_ERROR_TYPE.FILE_EMPTY, filename);
}
if (file.size > MAX_IMPORT_FILE_SIZE) {
throw new ImportFileError(IMPORT_ERROR_TYPE.FILE_TOO_BIG, filename);
}
const {
data: csvUsers,
errors: parseCsvErrors,
meta,
} = await parseCsv<ImportedCSVUser>(file, {
header: true,
transformHeader: (originalValue) => {
const value = originalValue.trim();
for (const [fieldName, header] of Object.entries(headerMap[mode])) {
if (value === fieldName) {
return '';
} else if (value === header) {
return fieldName;
}
}
return value;
},
transform: (value) => value.trim(),
comments: '#',
skipEmptyLines: true,
});
/**
* Limit number of rows
*/
if (csvUsers.length > MAX_NUMBER_OF_USER_ROWS) {
throw new TooManyUsersError();
}
if (!meta.fields?.includes('EmailAddresses')) {
throw new CsvFormatError({
type: CSV_FORMAT_ERROR_TYPE.MISSING_REQUIRED_FIELD,
fieldName: headerMap[mode]?.EmailAddresses ?? 'EmailAddresses',
});
}
if (!meta.fields?.includes('Password')) {
throw new CsvFormatError({ type: CSV_FORMAT_ERROR_TYPE.MISSING_REQUIRED_FIELD, fieldName: 'Password' });
}
if (parseCsvErrors.length) {
const rowsThatErrored = parseCsvErrors.map(({ row }) => {
// Row is indexed by 0
const rowNumber = row + 1;
return `${rowNumber}`;
});
throw new CsvFormatError({ type: CSV_FORMAT_ERROR_TYPE.PARSED_CSV_ERRORS, rowsThatErrored });
}
return convertCSVUsers(csvUsers, mode);
};
const defaultSampleCSV: ExportedCSVUser[] = [
{
DisplayName: 'Alice',
EmailAddresses: 'alice@mydomain.com',
Password: 'alice_password',
TotalStorage: 1,
VPNAccess: 1,
PrivateSubUser: 0,
},
{
DisplayName: 'Bob',
EmailAddresses: 'bob@mydomain.com',
Password: 'bob_password',
TotalStorage: 1,
VPNAccess: 0,
PrivateSubUser: 1,
},
{
DisplayName: 'Charlie',
EmailAddresses: 'charlie@mydomain.com, anotheraddress@mydomain.com, notanotherone@mydomain.com',
Password: 'charlie_password',
TotalStorage: 1,
VPNAccess: 1,
PrivateSubUser: 1,
},
];
export const getSampleCSV = (userArray: ExportedCSVUser[] = defaultSampleCSV) => {
const commentLine = {
DisplayName: '# Display name for the user',
EmailAddresses:
'# Enter the email address you want to set up for this user. To add more than 1 email address for a user, separate the addresses with commas.',
Password: '# Add a password for their account',
TotalStorage: '# Amount of storage the user will have in GiB',
VPNAccess: '# Enter 1 to give the user a VPN account',
PrivateSubUser: '# Enter 1 to make the user account private',
};
return toCsv([commentLine, ...userArray]);
};
export const downloadSampleCSV = () => {
const csv = getSampleCSV();
const blob = new Blob([csv], { type: 'text/csv' });
downloadFile(blob, 'example_proton_bulk_user_upload.csv');
};
const defaultVpnB2BSampleCSV: ExportedVpnB2BCSVUser[] = [
{
Name: 'Alice',
EmailAddress: 'alice@mydomain.com',
Password: 'alice_password',
},
{
Name: 'Bob',
EmailAddress: 'bob@mydomain.com',
Password: 'bob_password',
},
{
Name: 'Charlie',
EmailAddress: 'charlie@mydomain.com',
Password: 'charlie_password',
},
];
export const getVpnB2BSampleCSV = (userArray: ExportedVpnB2BCSVUser[] = defaultVpnB2BSampleCSV) => {
const commentLine = {
Name: '# Names (optional) must be unique',
EmailAddress: '# Enter the email address you want to set up for this user',
Password: '# Add a password for their account',
};
return toCsv([commentLine, ...userArray]);
};
export const downloadVPNB2BSampleCSV = () => {
const csv = getVpnB2BSampleCSV();
const blob = new Blob([csv], { type: 'text/csv' });
downloadFile(blob, 'example_proton_bulk_user_upload.csv');
};
| 6,469
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/lib.ts
|
import { PrivateKeyReference } from '@proton/crypto';
import { checkMemberAddressAvailability, createMember, createMemberAddress } from '@proton/shared/lib/api/members';
import { ENCRYPTION_CONFIGS, ENCRYPTION_TYPES, VPN_CONNECTIONS } from '@proton/shared/lib/constants';
import { getEmailParts, validateEmailAddress } from '@proton/shared/lib/helpers/email';
import { Address, Api, KeyTransparencyVerify } from '@proton/shared/lib/interfaces';
import { GetAddresses } from '@proton/shared/lib/interfaces/hooks/GetAddresses';
import { setupMemberKeys } from '@proton/shared/lib/keys';
import { srpVerify } from '@proton/shared/lib/srp';
import { UserManagementMode } from '../types';
import InvalidAddressesError from './errors/InvalidAddressesError';
import UnavailableAddressesError from './errors/UnavailableAddressesError';
import { UserTemplate } from './types';
export const createUser = async ({
user,
api,
getAddresses,
organizationKey,
keyTransparencyVerify,
mode,
}: {
user: UserTemplate;
api: Api;
getAddresses: GetAddresses;
organizationKey: PrivateKeyReference | undefined;
keyTransparencyVerify: KeyTransparencyVerify;
mode: UserManagementMode;
}) => {
const { emailAddresses, password, displayName, totalStorage, vpnAccess, privateSubUser } = user;
const invalidAddresses: string[] = [];
const validAddresses: string[] = [];
const addressParts = emailAddresses.map((emailAddress) => {
const isValid = validateEmailAddress(emailAddress);
if (!isValid) {
invalidAddresses.push(emailAddress);
} else {
validAddresses.push(emailAddress);
}
const [Local, Domain] = getEmailParts(emailAddress);
return {
address: emailAddress,
Local,
Domain,
};
});
if (invalidAddresses.length) {
/**
* Throw if any of the addresses are not valid
*/
throw new InvalidAddressesError(invalidAddresses, validAddresses);
}
const unavailableAddresses: string[] = [];
const availableAddresses: string[] = [];
const [firstAddressParts, ...restAddressParts] = addressParts;
const checkAddressAvailability = async ({
address,
Local,
Domain,
}: {
address: string;
Local: string;
Domain: string;
}) => {
try {
await api(
checkMemberAddressAvailability({
Local,
Domain,
})
);
availableAddresses.push(address);
} catch (error: any) {
if (error.status === 409) {
/**
* Conflict error from address being not available
*/
unavailableAddresses.push(address);
return;
}
throw error;
}
};
/**
* Will prompt password prompt only once
*/
await checkAddressAvailability(firstAddressParts);
/**
* No more password prompts will be needed
*/
await Promise.all(restAddressParts.map(checkAddressAvailability));
if (unavailableAddresses.length) {
/**
* Throw if any of the addresses are not available
*/
throw new UnavailableAddressesError(unavailableAddresses, availableAddresses);
}
const { Member } = await srpVerify({
api,
credentials: { password },
config: createMember({
Name: displayName,
Private: +privateSubUser,
MaxSpace: mode === UserManagementMode.VPN_B2B ? 0 : Math.round(totalStorage),
MaxVPN: vpnAccess || mode === UserManagementMode.VPN_B2B ? VPN_CONNECTIONS : 0,
}),
});
/**
* Create addresses one at a time
*/
const memberAddresses: Address[] = [];
for (const { Local, Domain } of addressParts) {
const { Address } = await api<{ Address: Address }>(
createMemberAddress(Member.ID, {
Local,
Domain,
})
);
memberAddresses.push(Address);
}
if (!privateSubUser) {
if (!organizationKey) {
throw new Error('Organization key is not decrypted');
}
const ownerAddresses = await getAddresses();
await setupMemberKeys({
api,
ownerAddresses,
member: Member,
memberAddresses,
organizationKey: organizationKey,
encryptionConfig: ENCRYPTION_CONFIGS[ENCRYPTION_TYPES.CURVE25519],
password,
keyTransparencyVerify,
});
}
};
| 6,470
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/types.ts
|
export interface UserTemplate {
id: string;
emailAddresses: string[];
password: string;
displayName: string;
totalStorage: number;
vpnAccess: boolean;
privateSubUser: boolean;
}
export interface ImportedCSVUser {
EmailAddresses: any;
Password: any;
DisplayName: any;
TotalStorage: any;
VPNAccess: any;
PrivateSubUser: any;
}
export interface ExportedCSVUser {
EmailAddresses: string;
Password: string;
DisplayName: string;
TotalStorage: number;
VPNAccess: 1 | 0;
PrivateSubUser: 1 | 0;
}
export interface ExportedVpnB2BCSVUser {
EmailAddress: string;
Password: string;
Name: string;
}
| 6,471
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/CreateUserAccountsModal/CreateUserAccountsModal.tsx
|
import { ChangeEvent, useEffect, useMemo, useRef, useState } from 'react';
import { c, msgid } from 'ttag';
import { Button, Input } from '@proton/atoms';
import {
Checkbox,
Icon,
Marks,
ModalProps,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
Progress,
Table,
TableBody,
TableCell,
TableHeader,
useApi,
useBeforeUnload,
useEventManager,
useGetAddresses,
useGetUserKeys,
useKTVerifier,
useNotifications,
useOrganization,
useOrganizationKey,
useUser,
} from '@proton/components';
import { useLoading } from '@proton/hooks';
import { getIsOfflineError } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { getSilentApiWithAbort } from '@proton/shared/lib/api/helpers/customConfig';
import { APP_NAMES } from '@proton/shared/lib/constants';
import humanSize from '@proton/shared/lib/helpers/humanSize';
import { escapeRegex, getMatches } from '@proton/shared/lib/helpers/regex';
import { normalize } from '@proton/shared/lib/helpers/string';
import { Domain } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import isTruthy from '@proton/utils/isTruthy';
import removeIndex from '@proton/utils/removeIndex';
import { UserManagementMode } from '../../types';
import validateAddUser from '../../validateAddUser';
import InvalidAddressesError from '../errors/InvalidAddressesError';
import UnavailableAddressesError from '../errors/UnavailableAddressesError';
import { createUser } from '../lib';
import { UserTemplate } from '../types';
import OrganizationCapacityErrorModal from './OrganizationCapacityErrorModal';
import validateOrganizationCapacity, { OrganizationCapacityError } from './validateOrganizationCapacity';
enum STEPS {
SELECT_USERS,
IMPORT_USERS,
ORGANIZATION_VALIDATION_ERROR,
DONE_WITH_ERRORS,
}
const search = (text: string, regex: RegExp | undefined) => {
return {
text,
chunks: regex ? getMatches(regex, normalize(text, true)) : [],
};
};
const filterOptions = (searchValue: string, usersToImport: UserTemplate[]) => {
const normalizedSearchText = searchValue.length ? normalize(searchValue, true) : undefined;
const regex = normalizedSearchText?.length ? new RegExp(escapeRegex(normalizedSearchText), 'gi') : undefined;
return usersToImport
.map((option) => {
return {
...option,
displayName: search(option.displayName, regex),
emailAddresses: option.emailAddresses.map((emailAddress) => {
return search(emailAddress, regex);
}),
};
})
.filter(
({ displayName, emailAddresses }) =>
!normalizedSearchText?.length ||
displayName.chunks.length ||
emailAddresses.some((emailAddress) => emailAddress.chunks.length)
);
};
interface Props extends ModalProps {
usersToImport: UserTemplate[];
app: APP_NAMES;
mode: UserManagementMode;
verifiedDomains: Domain[];
}
const CreateUserAccountsModal = ({ verifiedDomains, usersToImport, app, onClose, mode, ...rest }: Props) => {
const api = useApi();
const getAddresses = useGetAddresses();
const [organization, loadingOrganization] = useOrganization();
const [organizationKey, loadingOrganizationKey] = useOrganizationKey(organization);
const [organizationCapacityError, setOrganizationCapacityError] = useState<OrganizationCapacityError>();
const [user] = useUser();
const getUserKeys = useGetUserKeys();
const { keyTransparencyVerify, keyTransparencyCommit } = useKTVerifier(api, async () => user);
const abortControllerRef = useRef<AbortController>();
const { createNotification } = useNotifications();
const { call } = useEventManager();
const [step, setStep] = useState<STEPS>(STEPS.SELECT_USERS);
const [searchValue, setSearchValue] = useState('');
const filteredOptions = useMemo(() => filterOptions(searchValue, usersToImport), [searchValue, usersToImport]);
const [selectedUserIds, setSelectedUserIds] = useState<string[]>(usersToImport.map((user) => user.id));
const [successfullyCreatedUsers, setSuccessfullyCreatedUsers] = useState<UserTemplate[]>([]);
const [currentProgress, setCurrentProgress] = useState(0);
const [failedUsers, setFailedUsers] = useState<UserTemplate[]>([]);
const [invalidAddresses, setInvalidAddresses] = useState<string[]>([]);
const [unavailableAddresses, setUnavailableAddresses] = useState<string[]>([]);
const [orphanedAddresses, setOrphanedAddresses] = useState<string[]>([]);
const [importing, withImporting] = useLoading();
const showStorageColumn = mode === UserManagementMode.DEFAULT;
const showPasswordColumn = mode === UserManagementMode.VPN_B2B;
const showRoleColumn = mode === UserManagementMode.VPN_B2B;
/**
* Prompt on browser instance closing if users are being imported
*/
useBeforeUnload(step === STEPS.IMPORT_USERS);
/**
* Setup abort controller used when importing users
*/
useEffect(() => {
return () => {
abortControllerRef.current?.abort();
};
}, []);
const handleSelectAllFilteredOptionsClick = (event: ChangeEvent<HTMLInputElement>) => {
const filteredOptionIds = filteredOptions.map(({ id }) => id);
if (event.target.checked) {
/**
* We want to only select the filtered options so we merge the
* currently filtered option ids with already selected user ids
*/
setSelectedUserIds((selectedUserIds) => {
return [...new Set([...selectedUserIds, ...filteredOptionIds])];
});
return;
}
/**
* We want to only unselect the filtered options so we remove the
* currently filtered option ids from the selected user ids
*/
setSelectedUserIds((selectedUserIds) => selectedUserIds.filter((id) => !filteredOptionIds.includes(id)));
};
const isSelectAllChecked = useMemo(() => {
/**
* Is checked if all filtered option ids are currently selected
*/
return filteredOptions.map(({ id }) => id).every((id) => selectedUserIds.includes(id));
}, [filteredOptions, selectedUserIds]);
const handleCheckboxChange = (userId: string) => {
const selectedIndex = selectedUserIds.indexOf(userId);
if (selectedIndex === -1) {
/**
* Item is not currently selected so we add it to selectedUserIds
*/
setSelectedUserIds((selectedUserIds) => [...selectedUserIds, userId]);
return;
}
/**
* Item selected so we remove it from selectedUserIds
*/
setSelectedUserIds((selectedUserIds) => removeIndex(selectedUserIds, selectedIndex));
};
const setImportUsersStep = () => {
setCurrentProgress(0);
setStep(STEPS.IMPORT_USERS);
};
const importUsers = async ({ skipCapacityValidation = false }: { skipCapacityValidation?: boolean } = {}) => {
const selectedUsers = usersToImport.filter((user) => selectedUserIds.includes(user.id));
const error = validateAddUser({
privateUser: selectedUsers.length > 0 && selectedUsers.every((user) => user.privateSubUser),
organization,
organizationKey,
verifiedDomains,
mode,
});
if (error) {
return createNotification({ type: 'error', text: error });
}
if (!skipCapacityValidation) {
try {
validateOrganizationCapacity(selectedUsers, organization);
} catch (error: any) {
if (error instanceof OrganizationCapacityError) {
setOrganizationCapacityError(error);
setStep(STEPS.ORGANIZATION_VALIDATION_ERROR);
return;
}
}
}
abortControllerRef.current = new AbortController();
setImportUsersStep();
const localSuccessfullyCreatedUsers: UserTemplate[] = [];
const localFailedUsers: UserTemplate[] = [];
const localInvalidAddresses: string[] = [];
const localUnavailableAddresses: string[] = [];
const localOrphanedAddresses: string[] = [];
const { signal } = abortControllerRef.current;
const syncState = () => {
setSuccessfullyCreatedUsers(localSuccessfullyCreatedUsers);
setFailedUsers(localFailedUsers);
setInvalidAddresses(localInvalidAddresses);
setUnavailableAddresses(localUnavailableAddresses);
setOrphanedAddresses(localOrphanedAddresses);
};
for (let i = 0; i < selectedUsers.length; i++) {
if (signal.aborted) {
return;
}
const user = selectedUsers[i];
try {
await createUser({
user,
api: getSilentApiWithAbort(api, signal),
getAddresses,
organizationKey: organizationKey?.privateKey,
keyTransparencyVerify,
mode,
});
localSuccessfullyCreatedUsers.push(user);
} catch (error: any) {
if (getIsOfflineError(error)) {
abortControllerRef.current.abort();
const unattemptedUsers = selectedUsers.slice(i);
localFailedUsers.push(...unattemptedUsers);
syncState();
setStep(STEPS.DONE_WITH_ERRORS);
} else if (error.cancel) {
/**
* Handle auth prompt cancel
*/
abortControllerRef.current.abort();
setStep(STEPS.SELECT_USERS);
} else if (error instanceof InvalidAddressesError) {
localInvalidAddresses.push(...error.invalidAddresses);
localOrphanedAddresses.push(...error.orphanedAddresses);
} else if (error instanceof UnavailableAddressesError) {
localUnavailableAddresses.push(...error.unavailableAddresses);
localOrphanedAddresses.push(...error.orphanedAddresses);
} else {
localFailedUsers.push(user);
localOrphanedAddresses.push(...user.emailAddresses);
}
}
setCurrentProgress((currentProgress) => currentProgress + 1);
}
const userKeys = await getUserKeys();
await keyTransparencyCommit(userKeys);
syncState();
await call();
if (localFailedUsers.length || localInvalidAddresses.length || localUnavailableAddresses.length) {
setStep(STEPS.DONE_WITH_ERRORS);
return;
}
createNotification({
type: 'success',
text: c('Title').ngettext(
msgid`Successfully created ${localSuccessfullyCreatedUsers.length} user account`,
`Successfully created ${localSuccessfullyCreatedUsers.length} user accounts`,
localSuccessfullyCreatedUsers.length
),
});
onClose?.();
};
if (organizationCapacityError && step === STEPS.ORGANIZATION_VALIDATION_ERROR) {
return (
<OrganizationCapacityErrorModal
error={organizationCapacityError}
onCancel={() => setStep(STEPS.SELECT_USERS)}
onContinue={() => importUsers({ skipCapacityValidation: true })}
app={app}
{...rest}
/>
);
}
const {
title,
additionalContent,
content,
footerClassName,
footer,
size = 'xlarge',
}: {
title: string;
additionalContent?: JSX.Element;
content?: JSX.Element;
footerClassName?: string;
footer: JSX.Element;
size?: ModalProps['size'];
} = (() => {
if (step === STEPS.SELECT_USERS) {
const isCreateUsersButtonDisabled =
loadingOrganization || loadingOrganizationKey || !selectedUserIds.length;
return {
title: c('Title').t`Create user accounts`,
additionalContent: (
<div className="flex flex-align-items-center flex-justify-end mt-4 px-3">
<Input
className="max-w-custom"
style={{ '--max-w-custom': '16.875rem' }}
placeholder={c('Placeholder').t`Search`}
prefix={<Icon name="magnifier" alt={c('Action').t`Search`} />}
value={searchValue}
onValue={setSearchValue}
/>
</div>
),
content: filteredOptions.length ? (
<Table className="table-auto simple-table--is-hoverable">
<TableHeader
cells={[
<Checkbox
id="selectAll"
checked={isSelectAllChecked}
onChange={handleSelectAllFilteredOptionsClick}
/>,
<div>
{mode === UserManagementMode.DEFAULT
? c('TableHeader').t`Display name`
: c('TableHeader').t`Name`}
</div>,
mode === UserManagementMode.DEFAULT
? c('TableHeader').t`Email addresses`
: c('TableHeader').t`Email address`,
showStorageColumn && (
<div className="text-right">{c('TableHeader').t`Total storage`}</div>
),
showPasswordColumn && <div>{c('TableHeader').t`Password`}</div>,
showRoleColumn && <div>{c('TableHeader').t`Role`}</div>,
].filter(isTruthy)}
/>
<TableBody colSpan={3}>
{filteredOptions.map(({ id, totalStorage, displayName, emailAddresses, password }) => {
const isItemSelected = selectedUserIds.indexOf(id) !== -1;
const checkboxId = `user-${id}`;
const humanReadableStorage = humanSize(totalStorage, 'GB');
return (
<tr key={id} onClick={() => handleCheckboxChange(id)}>
<TableCell key="displayName" className="align-top">
<Checkbox id={checkboxId} checked={isItemSelected} readOnly />
</TableCell>
<TableCell key="displayName" className="align-top">
<div title={displayName.text}>
<Marks chunks={displayName.chunks}>{displayName.text}</Marks>
</div>
</TableCell>
<TableCell key="emailAddresses" className="align-top">
<ul className="unstyled m-0">
{emailAddresses.map(({ chunks, text }) => (
<li key={text} className="text-ellipsis" title={text}>
<Marks chunks={chunks}>{text}</Marks>
</li>
))}
</ul>
</TableCell>
{showStorageColumn && (
<TableCell
key="totalStorage"
className="text-right text-no-wrap align-top"
title={humanReadableStorage}
>
{humanReadableStorage}
</TableCell>
)}
{showPasswordColumn && (
<TableCell key="password" className="align-top">
{password}
</TableCell>
)}
{showRoleColumn && (
<TableCell key="role" className="align-top">
{c('Info').t`Member`}
</TableCell>
)}
</tr>
);
})}
</TableBody>
</Table>
) : (
<div
className="flex flex-align-items-center flex-justify-center min-h-custom"
style={{ '--min-h-custom': '10em' }}
>
<p className="color-weak">{c('Create user accounts empty state').t`No search results found`}</p>
</div>
),
footer: (
<>
<Button onClick={onClose}>{c('Action').t`Cancel`}</Button>
<Button
color="norm"
onClick={() => withImporting(importUsers())}
loading={importing}
disabled={isCreateUsersButtonDisabled}
data-testid="multiUserUpload:createAccounts"
>
{selectedUserIds.length
? c('Title').ngettext(
msgid`Create ${selectedUserIds.length} user`,
`Create ${selectedUserIds.length} users`,
selectedUserIds.length
)
: c('Action').t`Create users`}
</Button>
</>
),
};
}
if (step === STEPS.IMPORT_USERS) {
const numberOfUsersToImport = selectedUserIds.length;
return {
size: 'small',
title: c('Title').t`Creating user accounts`,
content: (
<>
<Progress className="progress-bar--norm" value={currentProgress} max={numberOfUsersToImport} />
<span className="mt-2">
{currentProgress} / {numberOfUsersToImport}
</span>
<p className="mt-4 color-weak mb-0">
{c('Info')
.t`This could take some time. Please do not close this page or disconnect from the internet.`}
</p>
</>
),
footerClassName: 'flex-justify-end',
footer: <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>,
};
}
if (step === STEPS.DONE_WITH_ERRORS) {
const title = successfullyCreatedUsers.length
? c('Title').ngettext(
msgid`Successfully created ${successfullyCreatedUsers.length} user account`,
`Successfully created ${successfullyCreatedUsers.length} user accounts`,
successfullyCreatedUsers.length
)
: c('Title').t`Couldn’t create accounts`;
const renderAddressList = (addresses: string[]) => {
return (
<ul className="unstyled">
{addresses.map((address) => {
return (
<li key={address} className="mb-0 text-ellipsis" title={address}>
{address}
</li>
);
})}
</ul>
);
};
return {
size: 'small',
title,
content: (
<>
{failedUsers.length && !invalidAddresses.length && !unavailableAddresses.length ? (
<p className={clsx('mt-0', !orphanedAddresses.length && 'mb-0')}>
{c('Title').ngettext(
msgid`Failed to create ${failedUsers.length} user
account.`,
`Failed to create ${failedUsers.length} user accounts.`,
failedUsers.length
)}{' '}
{c('Info')
.t`Please check your file for errors, or contact customer support for more information.`}
</p>
) : null}
{invalidAddresses.length ? (
<>
<p className="mt-0">
{c('Info').ngettext(
msgid`The following address is invalid.`,
`The following addresses are invalid.`,
invalidAddresses.length
)}
</p>
{renderAddressList(invalidAddresses)}
</>
) : null}
{unavailableAddresses.length ? (
<>
<p className="mt-0">
{c('Info').ngettext(
msgid`The following address is unavailable.`,
`The following addresses are unavailable.`,
unavailableAddresses.length
)}
</p>
{renderAddressList(unavailableAddresses)}
</>
) : null}
{orphanedAddresses.length ? (
<>
<p className="mt-0">
{c('Info').ngettext(
msgid`The following address was not created.`,
`The following addresses were not created.`,
orphanedAddresses.length
)}
</p>
{renderAddressList(orphanedAddresses)}
</>
) : null}
</>
),
footerClassName: 'flex-justify-end',
footer: <Button onClick={onClose}>{c('Action').t`Got it`}</Button>,
};
}
throw Error('No step found');
})();
return (
<ModalTwo size={size} onClose={onClose} {...rest}>
<ModalTwoHeader title={title} additionalContent={additionalContent} />
<ModalTwoContent>{content}</ModalTwoContent>
<ModalTwoFooter className={footerClassName}>{footer}</ModalTwoFooter>
</ModalTwo>
);
};
export default CreateUserAccountsModal;
| 6,472
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/CreateUserAccountsModal/OrganizationCapacityErrorModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { ModalProps, Prompt, SettingsLink, useConfig } from '@proton/components';
import { useLoading } from '@proton/hooks';
import { APP_NAMES, SHARED_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants';
import { addUpsellPath, getUpsellRefFromApp } from '@proton/shared/lib/helpers/upsell';
import { ORGANIZATION_CAPACITY_ERROR_TYPE, OrganizationCapacityError } from './validateOrganizationCapacity';
interface Props extends ModalProps {
error: OrganizationCapacityError;
onCancel: () => void;
onContinue: () => Promise<any>;
app: APP_NAMES;
}
const OrganizationCapacityErrorModal = ({ error, onCancel, onContinue, app, ...rest }: Props) => {
const { APP_NAME } = useConfig();
const [loading, withLoading] = useLoading();
const upsellRef = getUpsellRefFromApp({
app: APP_NAME,
fromApp: app,
feature: SHARED_UPSELL_PATHS.ORGANIZATION_CAPACITY,
component: UPSELL_COMPONENT.MODAL,
});
const link = addUpsellPath('/dashboard', upsellRef);
const upgradeLink = <SettingsLink path={link}>{c('Link').t`Upgrade your plan`}</SettingsLink>;
const cta = (() => {
if (error.type === ORGANIZATION_CAPACITY_ERROR_TYPE.MEMBER) {
// translator: Full sentence "Upgrade your plan to add more users, or remove some user accounts to free up space."
return c('Organization capacity error')
.jt`${upgradeLink} to add more users, or remove some user accounts to free up space.`;
}
if (error.type === ORGANIZATION_CAPACITY_ERROR_TYPE.SPACE) {
// translator: Full sentence "Upgrade your plan to get more storage, or remove some storage to free up space."
return c('Organization capacity error')
.jt`${upgradeLink} to get more storage, or remove some storage to free up space.`;
}
if (error.type === ORGANIZATION_CAPACITY_ERROR_TYPE.ADDRESSES) {
// translator: Full sentence "Upgrade your plan to get more addresses, or remove some addresses to free up space."
return c('Organization capacity error')
.jt`${upgradeLink} to get more addresses, or remove some addresses to free up space.`;
}
if (error.type === ORGANIZATION_CAPACITY_ERROR_TYPE.VPNS) {
// translator: Full sentence "Upgrade your plan to get more accounts, or remove VPN access from some users."
return c('Organization capacity error')
.jt`${upgradeLink} to get more accounts, or remove VPN access from some users.`;
}
throw new Error(`ORGANIZATION_CAPACITY_ERROR_TYPE ${error.type} not handled`);
})();
return (
<Prompt
title={c('Title').t`Couldn’t create accounts`}
buttons={[
<Button color="norm" loading={loading} onClick={() => withLoading(onContinue())}>
{c('Action').t`Continue anyway`}
</Button>,
<Button onClick={onCancel}>{c('Action').t`Cancel`}</Button>,
]}
{...rest}
>
<p className="mt-0">{error.message}</p>
<p className="mb-0">{cta}</p>
</Prompt>
);
};
export default OrganizationCapacityErrorModal;
| 6,473
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/CreateUserAccountsModal/validateOrganizationCapacity.ts
|
import { c, msgid } from 'ttag';
import humanSize from '@proton/shared/lib/helpers/humanSize';
import { Organization } from '@proton/shared/lib/interfaces';
import { UserTemplate } from '../types';
export enum ORGANIZATION_CAPACITY_ERROR_TYPE {
MEMBER,
SPACE,
ADDRESSES,
VPNS,
}
export class OrganizationCapacityError extends Error {
type: ORGANIZATION_CAPACITY_ERROR_TYPE;
constructor(errorType: ORGANIZATION_CAPACITY_ERROR_TYPE, message: string) {
super(message);
this.type = errorType;
Object.setPrototypeOf(this, OrganizationCapacityError.prototype);
}
}
const validateOrganizationCapacity = (usersToImport: UserTemplate[], organization: Organization) => {
const availableNumberOfMembers = organization.MaxMembers - organization.UsedMembers;
if (usersToImport.length > availableNumberOfMembers) {
throw new OrganizationCapacityError(
ORGANIZATION_CAPACITY_ERROR_TYPE.MEMBER,
c('Organization capacity error').ngettext(
msgid`Your plan includes a maximum of ${availableNumberOfMembers} more organizational user.`,
`Your plan includes a maximum of ${availableNumberOfMembers} more organizational users.`,
availableNumberOfMembers
)
);
}
const { totalStorage, totalAddresses, totalVpnAccess } = usersToImport.reduce(
(acc, user) => {
return {
totalStorage: acc.totalStorage + user.totalStorage,
totalAddresses: acc.totalAddresses + user.emailAddresses.length,
totalVpnAccess: acc.totalVpnAccess + Number(user.vpnAccess),
};
},
{
totalStorage: 0,
totalAddresses: 0,
totalVpnAccess: 0,
}
);
const availableSpace = organization.MaxSpace - organization.UsedSpace;
if (totalStorage > availableSpace) {
const humanReadableAvailableSpace = humanSize(availableSpace);
throw new OrganizationCapacityError(
ORGANIZATION_CAPACITY_ERROR_TYPE.SPACE,
c('Organization capacity error')
.t`Your plan includes a maximum of ${humanReadableAvailableSpace} more storage.`
);
}
const availableAddresses = organization.MaxAddresses - organization.UsedAddresses;
if (totalAddresses > availableAddresses) {
throw new OrganizationCapacityError(
ORGANIZATION_CAPACITY_ERROR_TYPE.ADDRESSES,
c('Organization capacity error').ngettext(
msgid`Your plan includes a maximum of ${availableAddresses} more address.`,
`Your plan includes a maximum of ${availableAddresses} more addresses.`,
availableAddresses
)
);
}
const availableVPNAccess = organization.MaxVPN - organization.UsedVPN;
if (totalVpnAccess > availableVPNAccess) {
throw new OrganizationCapacityError(
ORGANIZATION_CAPACITY_ERROR_TYPE.VPNS,
c('Organization capacity error').ngettext(
msgid`Your plan includes a maximum of ${availableVPNAccess} more VPN account.`,
`Your plan includes a maximum of ${availableVPNAccess} more VPN accounts.`,
availableVPNAccess
)
);
}
};
export default validateOrganizationCapacity;
| 6,474
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/UploadCSVFileButton/CsvFormatErrorModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { ModalProps, Prompt } from '@proton/components';
const CsvFormatErrorModal = ({ onClose, children, ...rest }: ModalProps) => {
return (
<Prompt
title={c('Title').t`Couldn’t create accounts`}
buttons={[<Button onClick={onClose}>{c('Action').t`Got it`}</Button>]}
{...rest}
>
{children}
</Prompt>
);
};
export default CsvFormatErrorModal;
| 6,475
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/UploadCSVFileButton/UploadCSVFileButton.tsx
|
import { ReactNode, useState } from 'react';
import { c, msgid } from 'ttag';
import { ButtonProps } from '@proton/atoms';
import { useModals, useNotifications } from '@proton/components';
import clsx from '@proton/utils/clsx';
import { FileInput, InlineLinkButton } from '../../../../components';
import { UserManagementMode } from '../../types';
import { downloadSampleCSV, downloadVPNB2BSampleCSV, parseMultiUserCsv } from '../csv';
import CsvConversionError, { CSV_CONVERSION_ERROR_TYPE } from '../errors/CsvConversionError';
import { CsvFormatError, TooManyUsersError } from '../errors/CsvFormatErrors';
import { UserTemplate } from '../types';
import CsvFormatErrorModal from './CsvFormatErrorModal';
export interface Props {
onUpload: (data: UserTemplate[]) => void;
className?: string;
children?: ReactNode;
color?: ButtonProps['color'];
mode?: UserManagementMode;
}
const ImportCSVFileButton = ({
onUpload,
className,
children = c('Select file').t`Upload CSV file`,
color,
mode = UserManagementMode.DEFAULT,
}: Props) => {
const [importing, setImporting] = useState(false);
const { createNotification } = useNotifications();
const { createModal } = useModals();
const csvTemplateButton = (
<InlineLinkButton
key="csvTemplateButton"
onClick={() => {
if (mode === UserManagementMode.VPN_B2B) {
return downloadVPNB2BSampleCSV();
}
return downloadSampleCSV();
}}
>
{
// translator: full sentence is "Please check your file, or try using our CSV template."
c('CSV download button').t`CSV template`
}
</InlineLinkButton>
);
const pleaseCheckYourFileText =
// translator: full sentence is "Please check your file, or try using our CSV template."
c('Info').jt`Please check your file, or try using our ${csvTemplateButton}.`;
const handleFiles = async (files: File[]) => {
try {
const { users, errors } = await parseMultiUserCsv(files, mode);
if (errors.length) {
const requiredEmailErrors = errors.filter(
(error) => error.type === CSV_CONVERSION_ERROR_TYPE.EMAIL_REQUIRED
);
const requiredPasswordErrors = errors.filter(
(error) => error.type === CSV_CONVERSION_ERROR_TYPE.PASSWORD_REQUIRED
);
if (requiredEmailErrors.length || requiredPasswordErrors.length) {
return createModal(
<CsvFormatErrorModal>
{requiredEmailErrors.length > 0 ? (
<p className={clsx('mt-0', !requiredPasswordErrors.length && 'mb-0')}>
{c('Info').ngettext(
msgid`Please add an email address for the user on row`,
`Please add email addresses for the users on rows`,
requiredEmailErrors.length
)}{' '}
{requiredEmailErrors.map((error) => error.rowNumber).join(', ')}
</p>
) : null}
{requiredPasswordErrors.length > 0 ? (
<p className="my-0">
{c('Info').ngettext(
msgid`Please add a password for the user on row`,
`Please add passwords for the users on rows`,
requiredPasswordErrors.length
)}{' '}
{requiredPasswordErrors.map((error) => error.rowNumber).join(', ')}
</p>
) : null}
</CsvFormatErrorModal>
);
}
const invalidTypeErrors = errors.filter(
(error) => error.type === CSV_CONVERSION_ERROR_TYPE.INVALID_TYPE
);
if (invalidTypeErrors.length) {
return createModal(
<CsvFormatErrorModal>
<p className="mt-0">{c('Info').t`The format of your CSV file is incorrect.`}</p>
<p className="mb-0">{pleaseCheckYourFileText}</p>
</CsvFormatErrorModal>
);
}
}
onUpload(users);
} catch (error: any) {
if (!error.message) {
return;
}
if (error instanceof TooManyUsersError) {
createModal(
<CsvFormatErrorModal>
<p className="m-0">{error.message}</p>
</CsvFormatErrorModal>
);
return;
}
if (error instanceof CsvConversionError || error instanceof CsvFormatError) {
createModal(
<CsvFormatErrorModal>
<p className="mt-0">{error.message}</p>
<p className="mb-0">{pleaseCheckYourFileText}</p>
</CsvFormatErrorModal>
);
return;
}
createNotification({
type: 'error',
text: error.message,
});
}
};
return (
<>
<FileInput
className={className}
accept=".csv"
onChange={async ({ target }) => {
setImporting(true);
const files = Array.from(target.files as FileList);
await handleFiles(files);
setImporting(false);
}}
loading={importing}
color={color}
>
{children}
</FileInput>
</>
);
};
export default ImportCSVFileButton;
| 6,476
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/UploadCSVFileButton/index.ts
|
import UploadCSVFileButton from './UploadCSVFileButton';
export default UploadCSVFileButton;
| 6,477
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/errors/CsvConversionError.ts
|
export enum CSV_CONVERSION_ERROR_TYPE {
EMAIL_REQUIRED,
PASSWORD_REQUIRED,
INVALID_TYPE,
}
export default class CsvConversionError extends Error {
readonly type: CSV_CONVERSION_ERROR_TYPE;
constructor(errorType: CSV_CONVERSION_ERROR_TYPE) {
super();
this.type = errorType;
Object.setPrototypeOf(this, CsvConversionError.prototype);
}
}
| 6,478
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/errors/CsvFormatErrors.ts
|
import { c } from 'ttag';
import { MAX_NUMBER_OF_USER_ROWS } from '../constants';
export enum CSV_FORMAT_ERROR_TYPE {
MISSING_REQUIRED_FIELD,
PARSED_CSV_ERRORS,
}
const getCsvFormatErrorMessage = (options: CsvFormatErrorOptions) => {
if (options.type === CSV_FORMAT_ERROR_TYPE.MISSING_REQUIRED_FIELD) {
return c('CSV format error').t`It looks like your file is missing the '${options.fieldName}' header.`;
}
if (options.type === CSV_FORMAT_ERROR_TYPE.PARSED_CSV_ERRORS) {
if (options.rowsThatErrored.length > 3) {
return c('CSV format error')
.t`We detected errors in multiple rows during import, please review your CSV file.`;
}
const erroredRowsString = options.rowsThatErrored.join(', ');
return c('CSV format error').t`Error on row ${erroredRowsString}.`;
}
};
type CsvFormatErrorOptions =
| { type: CSV_FORMAT_ERROR_TYPE.MISSING_REQUIRED_FIELD; fieldName: string }
| { type: CSV_FORMAT_ERROR_TYPE.PARSED_CSV_ERRORS; rowsThatErrored: string[] };
export class CsvFormatError extends Error {
constructor(options: CsvFormatErrorOptions) {
super(getCsvFormatErrorMessage(options));
}
}
export class TooManyUsersError extends Error {
constructor() {
super(
// translator: variable here is the max number of user accounts the user can import. Currently this is 500.
c('Error importing users').t`Upload a CSV file with ${MAX_NUMBER_OF_USER_ROWS} user accounts or less.`
);
}
}
| 6,479
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/errors/ImportFileError.ts
|
import { c } from 'ttag';
import truncate from '@proton/utils/truncate';
import { MAX_FILENAME_CHARS_DISPLAY, MAX_IMPORT_FILE_SIZE_STRING } from '../constants';
export enum IMPORT_ERROR_TYPE {
NO_FILE_SELECTED,
FILE_EMPTY,
FILE_TOO_BIG,
FILE_CORRUPTED,
}
const getImportFileErrorMessage = (errorType: IMPORT_ERROR_TYPE, filename = '') => {
const formattedFilename = truncate(filename, MAX_FILENAME_CHARS_DISPLAY);
if (errorType === IMPORT_ERROR_TYPE.NO_FILE_SELECTED) {
return c('Error importing users').t`An error occurred uploading your file. No file has been selected.`;
}
if (errorType === IMPORT_ERROR_TYPE.FILE_EMPTY) {
return c('Error importing users').t`Your file "${formattedFilename}" is empty.`;
}
if (errorType === IMPORT_ERROR_TYPE.FILE_TOO_BIG) {
return c('Error importing users')
.t`An error occurred uploading your file "${formattedFilename}". Maximum file size is ${MAX_IMPORT_FILE_SIZE_STRING}.`;
}
if (errorType === IMPORT_ERROR_TYPE.FILE_CORRUPTED) {
return c('Error importing users')
.t`An error occurred reading your file "${ formattedFilename }". Incorrect file format.`;
}
};
export default class ImportFileError extends Error {
constructor(errorType: IMPORT_ERROR_TYPE, filename?: string) {
super(getImportFileErrorMessage(errorType, filename));
Object.setPrototypeOf(this, ImportFileError.prototype);
}
}
| 6,480
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/errors/InvalidAddressesError.ts
|
export default class InvalidAddressesError extends Error {
readonly invalidAddresses: string[];
readonly orphanedAddresses: string[];
constructor(
/**
* Addresses that are consider invalid through client side validation
*/
invalidAddresses: string[],
/**
* Extra addresses for the user that was not created
*/
orphanedAddresses: string[]
) {
super();
this.invalidAddresses = invalidAddresses;
this.orphanedAddresses = orphanedAddresses;
Object.setPrototypeOf(this, InvalidAddressesError.prototype);
}
}
| 6,481
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/members/multipleUserCreation/errors/UnavailableAddressesError.ts
|
export default class UnavailableAddressesError extends Error {
readonly unavailableAddresses: string[];
readonly orphanedAddresses: string[];
constructor(
/**
* Addresses that are not available for use
*/
unavailableAddresses: string[],
/**
* Extra addresses for the user that was not created
*/
orphanedAddresses: string[]
) {
super();
this.unavailableAddresses = unavailableAddresses;
this.orphanedAddresses = orphanedAddresses;
Object.setPrototypeOf(this, UnavailableAddressesError.prototype);
}
}
| 6,482
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/AlmostAllMailToggle.tsx
|
import { c } from 'ttag';
import { useLoading } from '@proton/hooks';
import { updateShowAlmostAllMail } from '@proton/shared/lib/api/mailSettings';
import { Toggle } from '../../components';
import { useApi, useEventManager, useNotifications, useToggle } from '../../hooks';
interface Props {
id: string;
showAlmostAllMail: number;
}
const AlmostAllMailToggle = ({ id, showAlmostAllMail }: Props) => {
const { createNotification } = useNotifications();
const [loading, withLoading] = useLoading();
const { call } = useEventManager();
const api = useApi();
const { state, toggle } = useToggle(Boolean(showAlmostAllMail));
const handleChange = async (checked: boolean) => {
const bit = +checked;
await api(updateShowAlmostAllMail(bit));
await call();
toggle();
createNotification({ text: c('Success').t`Preference saved` });
};
return (
<Toggle
id={id}
checked={state}
onChange={({ target }) => withLoading(handleChange(target.checked))}
loading={loading}
/>
);
};
export default AlmostAllMailToggle;
| 6,483
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/AutoDeleteSetting.tsx
|
import React from 'react';
import { c } from 'ttag';
import UpsellIcon from '@proton/components/components/upsell/UpsellIcon';
import { useLoading } from '@proton/hooks';
import { updateAutoDelete } from '@proton/shared/lib/api/mailSettings';
import { AUTO_DELETE_SPAM_AND_TRASH_DAYS } from '@proton/shared/lib/mail/mailSettings';
import { AutoDeleteUpsellModal, Info, Toggle, useModalState } from '../../components';
import { useApi, useEventManager, useFeature, useUser } from '../../hooks';
import { SettingsLayout, SettingsLayoutLeft, SettingsLayoutRight } from '../account';
import { FeatureCode } from '../features';
interface Props {
onSaved: () => void;
settingValue: AUTO_DELETE_SPAM_AND_TRASH_DAYS | null;
}
const AutoDeleteSetting = ({ settingValue = AUTO_DELETE_SPAM_AND_TRASH_DAYS.DISABLED, onSaved }: Props) => {
const api = useApi();
const { feature: autoDeleteFeature } = useFeature(FeatureCode.AutoDelete);
const [{ hasPaidMail }, userLoading] = useUser();
const { call } = useEventManager();
const [loadingAutoDelete, withLoadingAutoDelete] = useLoading();
const [upsellModalProps, toggleUpsellModal, renderUpsellModal] = useModalState();
const handleChangeAutoDelete = async (autoDelete: AUTO_DELETE_SPAM_AND_TRASH_DAYS) => {
await api(updateAutoDelete(autoDelete));
await call();
onSaved();
};
const disabled = userLoading || !hasPaidMail;
return autoDeleteFeature?.Value === true ? (
<>
{renderUpsellModal && <AutoDeleteUpsellModal modalProps={upsellModalProps} />}
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="autoDelete" className="text-semibold flex flex-nowrap flex-align-items-start">
<span className="mr-2 flex-item-fluid">
<span className="mr-2">{c('Label').t`Auto-delete unwanted messages`}</span>
<Info
className="flex-item-noshrink"
title={c('Tooltip')
.t`Delete trash and spam messages after 30 days. Turning on auto-delete gives messages already in trash/spam a deletion date based on the date they were moved there.`}
/>
</span>
{!hasPaidMail && <UpsellIcon className="mt-1" />}
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="pt-2">
<Toggle
id="autoDelete"
loading={loadingAutoDelete}
checked={!!settingValue}
onChange={({ target }) => {
/* Didn't used disabled attr because need to catch label and input click */
if (disabled) {
toggleUpsellModal(true);
return;
}
void withLoadingAutoDelete(
handleChangeAutoDelete(
target.checked
? AUTO_DELETE_SPAM_AND_TRASH_DAYS.ACTIVE
: AUTO_DELETE_SPAM_AND_TRASH_DAYS.DISABLED
)
);
}}
data-testid="message-setting:auto-delete-toggle"
/>
</SettingsLayoutRight>
</SettingsLayout>
</>
) : null;
};
export default AutoDeleteSetting;
| 6,484
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/DelaySendSecondsSelect.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { useLoading } from '@proton/hooks';
import { updateDelaySend } from '@proton/shared/lib/api/mailSettings';
import { DELAY_IN_SECONDS } from '@proton/shared/lib/mail/mailSettings';
import { Select } from '../../components';
import { useApi, useEventManager, useNotifications } from '../../hooks';
interface Props {
id: string;
delaySendSeconds: number;
}
const DelaySendSecondsSelect = ({ id, delaySendSeconds }: Props) => {
const { createNotification } = useNotifications();
const [loading, withLoading] = useLoading();
const { call } = useEventManager();
const api = useApi();
const [delay, setDelay] = useState(delaySendSeconds);
const options = [
{ text: c('Option delay send seconds').t`0 seconds`, value: DELAY_IN_SECONDS.NONE },
{ text: c('Option delay send seconds').t`5 seconds`, value: DELAY_IN_SECONDS.SMALL },
{ text: c('Option delay send seconds').t`10 seconds`, value: DELAY_IN_SECONDS.MEDIUM },
{ text: c('Option delay send seconds').t`20 seconds`, value: DELAY_IN_SECONDS.LARGE },
];
const handleChange = async (delay: number) => {
await api(updateDelaySend(delay));
await call();
setDelay(delay);
createNotification({ text: c('Success').t`Preference saved` });
};
return (
<Select
id={id}
value={delay}
options={options}
onChange={({ target }) => withLoading(handleChange(+target.value))}
loading={loading}
/>
);
};
export default DelaySendSecondsSelect;
| 6,485
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/EmbeddedToggle.tsx
|
import { c } from 'ttag';
import { useLoading } from '@proton/hooks';
import { updateHideEmbeddedImages } from '@proton/shared/lib/api/mailSettings';
import { SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings';
import { Toggle } from '../../components';
import { useApi, useEventManager, useNotifications, useToggle } from '../../hooks';
interface Props {
id: string;
hideEmbeddedImages: number;
onChange: (value: number) => void;
}
const EmbeddedToggle = ({ id, hideEmbeddedImages, onChange }: Props) => {
const { createNotification } = useNotifications();
const [loading, withLoading] = useLoading();
const { call } = useEventManager();
const api = useApi();
const { state, toggle } = useToggle(hideEmbeddedImages === SHOW_IMAGES.SHOW);
const handleChange = async (checked: boolean) => {
const bit = checked ? SHOW_IMAGES.SHOW : SHOW_IMAGES.HIDE;
await api(updateHideEmbeddedImages(bit));
await call();
toggle();
onChange(bit);
createNotification({ text: c('Success').t`Preference saved` });
};
return (
<Toggle
id={id}
checked={state}
onChange={({ target }) => withLoading(handleChange(target.checked))}
loading={loading}
/>
);
};
export default EmbeddedToggle;
| 6,486
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/MessagesGeneralSection.tsx
|
import { MouseEvent } from 'react';
import { c } from 'ttag';
import { patchNews } from '@proton/shared/lib/api/settings';
import {
APPS,
MAIL_APP_NAME,
NEWSLETTER_SUBSCRIPTIONS,
NEWSLETTER_SUBSCRIPTIONS_BITS,
} from '@proton/shared/lib/constants';
import { hasBit } from '@proton/shared/lib/helpers/bitset';
import { getStaticURL } from '@proton/shared/lib/helpers/url';
import { SETTINGS_STATUS } from '@proton/shared/lib/interfaces';
import { Info, SettingsLink, useModalState } from '../../components';
import Icon from '../../components/icon/Icon';
import { useApi, useEventManager, useNotifications, useUser, useUserSettings } from '../../hooks';
import SettingsLayout from '../account/SettingsLayout';
import SettingsLayoutLeft from '../account/SettingsLayoutLeft';
import SettingsLayoutRight from '../account/SettingsLayoutRight';
import SettingsSection from '../account/SettingsSection';
import ShortcutsToggle from '../general/ShortcutsToggle';
import { MailShortcutsModal } from '../mail';
import DailyEmailNotificationToggle from '../recovery/DailyEmailNotificationToggle';
import RecoveryEmail from '../recovery/email/RecoveryEmail';
const MessagesGeneralSection = () => {
const [userSettings] = useUserSettings();
const [user, userLoading] = useUser();
const api = useApi();
const { call } = useEventManager();
const { createNotification } = useNotifications();
const [mailShortcutsProps, setMailShortcutsModalOpen] = useModalState();
const handleOpenShortcutsModal = (e: MouseEvent) => {
e.preventDefault();
setMailShortcutsModalOpen(true);
};
const showRecoveryEmailInput = !user.isPrivate;
const canEnableDailyEmails = !!userSettings?.Email?.Value;
const isDailyEmailEnabled =
canEnableDailyEmails && hasBit(userSettings.News, NEWSLETTER_SUBSCRIPTIONS_BITS.NEW_EMAIL_NOTIF);
const handleChangeEmailNotify = async () => {
if (!canEnableDailyEmails) {
createNotification({
type: 'error',
text: c('Error').t`Please set a recovery/notification email first`,
});
return;
}
await api(
patchNews({
[NEWSLETTER_SUBSCRIPTIONS.NEW_EMAIL_NOTIF]: !isDailyEmailEnabled,
})
);
await call();
};
return (
<>
<MailShortcutsModal {...mailShortcutsProps} />
<SettingsSection>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="shortcutsToggle" className="flex-item-fluid">
<span className="text-semibold">{c('Title').t`Keyboard shortcuts`}</span>
<button
type="button"
className="ml-2 inline-flex relative interactive-pseudo-protrude interactive--no-background"
onClick={handleOpenShortcutsModal}
>
<Icon
className="color-primary"
name="info-circle"
alt={c('Action').t`More info: Keyboard shortcuts`}
size={16}
/>
</button>
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="flex flex-item-fluid flex-align-items-center">
<ShortcutsToggle className="mr-4" id="shortcutsToggle" />
</SettingsLayoutRight>
</SettingsLayout>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="dailyNotificationsToggle" className="flex-item-fluid">
<span className="pr-2 text-semibold">{c('Label').t`Daily email notifications`}</span>
<Info
url={getStaticURL('/support/notification-email')}
title={c('Info')
.t`When notifications are enabled, we'll send an alert to your recovery email address if you have new messages in your ${MAIL_APP_NAME} account.`}
/>
</label>
{!userLoading && !showRecoveryEmailInput && (
<div className="text-sm">
<SettingsLink path="/recovery#account" app={APPS.PROTONMAIL}>
{isDailyEmailEnabled && userSettings?.Email?.Status === SETTINGS_STATUS.UNVERIFIED
? c('Action').t`Requires a verified recovery email address`
: c('Link').t`Set email address`}
</SettingsLink>{' '}
</div>
)}
</SettingsLayoutLeft>
<SettingsLayoutRight className="flex flex-item-fluid flex-align-items-center">
{!userLoading && showRecoveryEmailInput && (
<RecoveryEmail
className="mb-4 md:mb-0"
email={userSettings.Email}
hasReset={!!userSettings.Email.Reset}
hasNotify={!!userSettings.Email.Notify}
/>
)}
<div className="flex flex-align-items-center">
<DailyEmailNotificationToggle
id="dailyNotificationsToggle"
className="mr-2"
isEnabled={isDailyEmailEnabled}
canEnable={canEnableDailyEmails}
onChange={handleChangeEmailNotify}
/>
{!userLoading && showRecoveryEmailInput && (
<label htmlFor="dailyNotificationsToggle" className="flex-item-fluid">
{c('Label').t`Allow notifications by email`}
</label>
)}
</div>
</SettingsLayoutRight>
</SettingsLayout>
</SettingsSection>
</>
);
};
export default MessagesGeneralSection;
| 6,487
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/MessagesSection.test.tsx
|
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {
mockUseApi,
mockUseEventManager,
mockUseFeature,
mockUseMailSettings,
mockUseNotifications,
mockUseUser,
} from '@proton/testing/index';
import { FeatureCode } from '../features';
import MessagesSection from './MessagesSection';
describe('MessagesSection', () => {
let mockedApi: jest.Mock;
let mockedCall: jest.Mock;
beforeEach(() => {
mockedApi = jest.fn();
mockedCall = jest.fn();
mockUseApi(mockedApi);
mockUseEventManager({ call: mockedCall });
mockUseMailSettings();
mockUseNotifications();
mockUseFeature();
mockUseUser();
});
describe('when AlmostAllMail is not enabled', () => {
it('should not render AlmostAllMail toggle', () => {
mockUseFeature().mockImplementation((code) => {
if (code === FeatureCode.AlmostAllMail) {
return { feature: { Value: false } } as any;
}
return { feature: { Value: true } } as any;
});
render(<MessagesSection />);
expect(screen.queryByText('Exclude Spam/Trash from All mail')).not.toBeInTheDocument();
});
});
describe('when AlmostAllMail is enabled', () => {
beforeEach(() => {
mockUseFeature({ feature: { Value: true } });
});
it('should render AlmostAllMail toggle', () => {
render(<MessagesSection />);
expect(screen.getByText('Exclude Spam/Trash from All mail')).toBeInTheDocument();
});
it('should toggle setting on click', async () => {
render(<MessagesSection />);
const setting = screen.getByText('Exclude Spam/Trash from All mail');
await userEvent.click(setting);
await waitFor(() => {
expect(mockedApi).toHaveBeenCalledTimes(1);
});
expect(mockedApi).toHaveBeenCalledWith({
data: { AlmostAllMail: 1 },
method: 'put',
url: 'mail/v4/settings/almost-all-mail',
});
await userEvent.click(setting);
await waitFor(() => {
expect(mockedApi).toHaveBeenCalledTimes(2);
});
expect(mockedApi).toHaveBeenLastCalledWith({
data: { AlmostAllMail: 0 },
method: 'put',
url: 'mail/v4/settings/almost-all-mail',
});
});
});
});
| 6,488
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/MessagesSection.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { useLoading } from '@proton/hooks';
import { updateSpamAction, updateStickyLabels, updateViewMode } from '@proton/shared/lib/api/mailSettings';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { DEFAULT_MAILSETTINGS, SPAM_ACTION, STICKY_LABELS, VIEW_MODE } from '@proton/shared/lib/mail/mailSettings';
import { Info } from '../../components';
import { useApi, useEventManager, useFeature, useMailSettings, useNotifications } from '../../hooks';
import SettingsLayout from '../account/SettingsLayout';
import SettingsLayoutLeft from '../account/SettingsLayoutLeft';
import SettingsLayoutRight from '../account/SettingsLayoutRight';
import { FeatureCode } from '../features';
import StickyLabelsToggle from '../layouts/StickyLabelsToggle';
import ViewModeToggle from '../layouts/ViewModeToggle';
import AlmostAllMailToggle from './AlmostAllMailToggle';
import AutoDeleteSetting from './AutoDeleteSetting';
import EmbeddedToggle from './EmbeddedToggle';
import RequestLinkConfirmationToggle from './RequestLinkConfirmationToggle';
import ShowMovedToggle from './ShowMovedToggle';
import SpamActionSelect from './SpamActionSelect';
const MessagesSection = () => {
const [
{
ViewMode,
StickyLabels,
HideEmbeddedImages,
ConfirmLink,
SpamAction,
AutoDeleteSpamAndTrashDays,
AlmostAllMail,
} = DEFAULT_MAILSETTINGS,
] = useMailSettings();
const [hideEmbeddedImages, setHideEmbeddedImages] = useState(HideEmbeddedImages);
const { createNotification } = useNotifications();
const isAlmostAllMailEnabled = !!useFeature(FeatureCode.AlmostAllMail).feature?.Value;
const { call } = useEventManager();
const api = useApi();
const [loadingViewMode, withLoadingViewMode] = useLoading();
const [loadingStickyLabels, withLoadingStickyLabels] = useLoading();
const [loadingSpamAction, withLoadingSpamAction] = useLoading();
const handleChangeHideEmbedded = (newValue: number) => setHideEmbeddedImages(newValue);
const notifyPreferenceSaved = () => createNotification({ text: c('Success').t`Preference saved` });
const handleToggleStickyLabels = async (value: number) => {
await api(updateStickyLabels(value));
await call();
notifyPreferenceSaved();
};
const handleChangeViewMode = async (mode: VIEW_MODE) => {
if (mode === VIEW_MODE.SINGLE) {
await api(updateStickyLabels(STICKY_LABELS.DISABLED));
}
await api(updateViewMode(mode));
await call();
notifyPreferenceSaved();
};
const handleChangeSpamAction = async (spamAction: SPAM_ACTION | null) => {
await api(updateSpamAction(spamAction));
await call();
notifyPreferenceSaved();
};
return (
<>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="embeddedToggle" className="text-semibold">
<span className="mr-2">{c('Label').t`Auto show embedded images`}</span>
<Info
url={getKnowledgeBaseUrl('/images-by-default')}
title={c('Info')
.t`When disabled, this prevents image files from loading on your device without your knowledge.`}
/>
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="pt-2">
<EmbeddedToggle
id="embeddedToggle"
hideEmbeddedImages={hideEmbeddedImages}
onChange={handleChangeHideEmbedded}
/>
</SettingsLayoutRight>
</SettingsLayout>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="showMovedToggle" className="text-semibold">
<span className="mr-2">{c('Label').t`Keep messages in Sent/Drafts`}</span>
<Info
title={c('Tooltip')
.t`Messages in the Sent or Drafts folder will continue to appear in that folder, even if you move them to another folder.`}
/>
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="pt-2">
<ShowMovedToggle id="showMovedToggle" />
</SettingsLayoutRight>
</SettingsLayout>
<SettingsLayout>
{isAlmostAllMailEnabled && (
<>
<SettingsLayoutLeft>
<label htmlFor="almostAllMail" className="text-semibold">
<span className="mr-2">{c('Label').t`Exclude Spam/Trash from All mail`}</span>
<Info title={c('Info').t`Not yet available in our Android mobile app.`} />
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="pt-2">
<AlmostAllMailToggle id="almostAllMail" showAlmostAllMail={AlmostAllMail} />
</SettingsLayoutRight>
</>
)}
</SettingsLayout>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="requestLinkConfirmationToggle" className="text-semibold">
<span className="mr-2">{c('Label').t`Confirm link URLs`}</span>
<Info
title={c('Tooltip')
.t`When you click on a link, this anti-phishing feature will ask you to confirm the URL of the web page.`}
/>
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="pt-2">
<RequestLinkConfirmationToggle confirmLink={ConfirmLink} id="requestLinkConfirmationToggle" />
</SettingsLayoutRight>
</SettingsLayout>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="viewMode" className="text-semibold">
<span className="mr-2">{c('Label').t`Conversation grouping`}</span>
<Info
title={c('Tooltip')
.t`Group emails in the same conversation together in your Inbox or display them separately.`}
/>
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="pt-2">
<ViewModeToggle
id="viewMode"
viewMode={ViewMode}
loading={loadingViewMode}
onToggle={(value) => withLoadingViewMode(handleChangeViewMode(value))}
data-testid="appearance:conversation-group-toggle"
/>
</SettingsLayoutRight>
</SettingsLayout>
<AutoDeleteSetting settingValue={AutoDeleteSpamAndTrashDays} onSaved={notifyPreferenceSaved} />
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="stickyLabelsToggle" className="text-semibold">
<span className="mr-2">{c('Label').t`Sticky labels`}</span>
<Info
title={c('Tooltip')
.t`When you add a label to a message in a conversation, it will automatically be applied to all future messages you send or receive in that conversation.`}
/>
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight className="pt-2">
<StickyLabelsToggle
id="stickyLabelsToggle"
stickyLabels={StickyLabels}
loading={loadingStickyLabels}
onToggle={(value) => withLoadingStickyLabels(handleToggleStickyLabels(value))}
data-testid="appearance:sticky-labels-toggle"
disabled={ViewMode !== VIEW_MODE.GROUP}
/>
</SettingsLayoutRight>
</SettingsLayout>
<SettingsLayout>
<SettingsLayoutLeft>
<label htmlFor="spamActionLabelSelect" className="text-semibold">
<span className="mr-2">{c('Label').t`Auto-unsubscribe`}</span>
<Info
title={c('Tooltip')
.t`When you move an email to spam, you’ll automatically be unsubscribed from the sender’s mailing lists.`}
/>
</label>
</SettingsLayoutLeft>
<SettingsLayoutRight>
<SpamActionSelect
id="spamActionLabelSelect"
value={SpamAction}
onChange={(value) => withLoadingSpamAction(handleChangeSpamAction(value))}
loading={loadingSpamAction}
/>
</SettingsLayoutRight>
</SettingsLayout>
</>
);
};
export default MessagesSection;
| 6,489
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/RequestLinkConfirmationToggle.tsx
|
import { c } from 'ttag';
import { useLoading } from '@proton/hooks';
import { updateConfirmLink } from '@proton/shared/lib/api/mailSettings';
import { Toggle } from '../../components';
import { useApi, useEventManager, useNotifications, useToggle } from '../../hooks';
interface Props {
id: string;
confirmLink: number;
}
const RequestLinkConfirmationToggle = ({ id, confirmLink }: Props) => {
const { createNotification } = useNotifications();
const [loading, withLoading] = useLoading();
const { call } = useEventManager();
const api = useApi();
const { state, toggle } = useToggle(!!confirmLink);
const handleChange = async (checked: boolean) => {
await api(updateConfirmLink(+checked));
await call();
toggle();
createNotification({ text: c('Success').t`Preference saved` });
};
return (
<Toggle
id={id}
checked={state}
onChange={({ target }) => withLoading(handleChange(target.checked))}
loading={loading}
/>
);
};
export default RequestLinkConfirmationToggle;
| 6,490
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/SenderImagesToggle.tsx
|
import { c } from 'ttag';
import { useLoading } from '@proton/hooks';
import { updateHideSenderImages } from '@proton/shared/lib/api/mailSettings';
import { Toggle } from '../../components';
import { useApi, useEventManager, useMailSettings, useNotifications, useToggle } from '../../hooks';
interface Props {
id?: string;
className?: string;
}
const SenderImagesToggle = ({ id, className }: Props) => {
const [mailSettings] = useMailSettings();
const { state, toggle } = useToggle(!mailSettings?.HideSenderImages);
const { call } = useEventManager();
const { createNotification } = useNotifications();
const api = useApi();
const [loading, withLoading] = useLoading();
const handleChange = async (checked: boolean) => {
await api(updateHideSenderImages(+!checked));
await call();
toggle();
createNotification({ text: c('Success').t`Preference saved` });
};
return (
<Toggle
id={id}
className={className}
checked={state}
onChange={({ target }) => withLoading(handleChange(target.checked))}
loading={loading}
/>
);
};
export default SenderImagesToggle;
| 6,491
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/ShowMovedToggle.tsx
|
import { c } from 'ttag';
import { useLoading } from '@proton/hooks';
import { updateShowMoved } from '@proton/shared/lib/api/mailSettings';
import { DEFAULT_MAILSETTINGS, SHOW_MOVED } from '@proton/shared/lib/mail/mailSettings';
import { Toggle } from '../../components';
import { useApi, useEventManager, useMailSettings, useNotifications, useToggle } from '../../hooks';
const { DRAFTS_AND_SENT, NONE } = SHOW_MOVED;
interface Props {
id: string;
}
const ShowMovedToggle = ({ id }: Props) => {
const [loading, withLoading] = useLoading();
const { createNotification } = useNotifications();
const api = useApi();
const [{ ShowMoved } = DEFAULT_MAILSETTINGS] = useMailSettings();
const { call } = useEventManager();
const { state, toggle } = useToggle(!!ShowMoved);
const handleChange = async (checked: boolean) => {
await api(updateShowMoved(checked ? DRAFTS_AND_SENT : NONE));
await call();
toggle();
createNotification({ text: c('Success').t`Preference saved` });
};
return (
<Toggle
id={id}
checked={state}
onChange={({ target }) => withLoading(handleChange(target.checked))}
loading={loading}
/>
);
};
export default ShowMovedToggle;
| 6,492
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/SpamActionSelect.tsx
|
import { c } from 'ttag';
import { SPAM_ACTION } from '@proton/shared/lib/mail/mailSettings';
import { Option, SelectTwo } from '../../components';
interface Props {
onChange: (spamAction: SPAM_ACTION | null) => void;
value: SPAM_ACTION | null;
id?: string;
loading?: boolean;
}
const SpamActionSelect = ({ onChange, ...rest }: Props) => {
return (
<SelectTwo onChange={({ value }) => onChange(value as SPAM_ACTION | null)} {...rest}>
<Option title={c('Option').t`On`} value={SPAM_ACTION.JustSpam} />
<Option title={c('Option').t`Off`} value={SPAM_ACTION.SpamAndUnsub} />
<Option title={c('Option').t`Ask each time`} value={null} />
</SelectTwo>
);
};
export default SpamActionSelect;
| 6,493
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/messages/index.ts
|
export { default as EmbeddedToggle } from './EmbeddedToggle';
export { default as MessagesSection } from './MessagesSection';
export { default as MessagesGeneralSection } from './MessagesGeneralSection';
export { default as SenderImagesToggle } from './SenderImagesToggle';
| 6,494
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mnemonic/DisableMnemonicModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { disableMnemonicPhrase } from '@proton/shared/lib/api/settingsMnemonic';
import { ModalProps, Prompt, useModalState } from '../../components';
import { useEventManager, useNotifications } from '../../hooks';
import AuthModal from '../password/AuthModal';
interface DisableMnemonicModalProps {
onClose: ModalProps['onClose'];
onExit: ModalProps['onExit'];
open: ModalProps['open'];
}
const DisableMnemonicModal = ({ open, onClose, onExit }: DisableMnemonicModalProps) => {
const [authModalProps, setAuthModalOpen, renderAuthModal] = useModalState();
const { createNotification } = useNotifications();
const { call } = useEventManager();
return (
<>
{renderAuthModal && (
<AuthModal
config={disableMnemonicPhrase()}
{...authModalProps}
onCancel={undefined}
onSuccess={async () => {
await call();
onClose?.();
createNotification({ text: c('Info').t`Recovery phrase has been disabled` });
}}
/>
)}
<Prompt
open={open}
title={c('Action').t`Disable recovery phrase?`}
buttons={[
<Button color="danger" onClick={() => setAuthModalOpen(true)}>
{c('Action').t`Disable recovery phrase`}
</Button>,
<Button onClick={onClose}>{c('Action').t`Cancel`}</Button>,
]}
onClose={onClose}
onExit={onExit}
>
<p className="mt-0">{c('Info')
.t`This will disable your current recovery phrase. You won't be able to use it to access your account or decrypt your data.`}</p>
<p className="mb-0">{c('Info')
.t`Enabling recovery by phrase again will generate a new recovery phrase.`}</p>
</Prompt>
</>
);
};
export default DisableMnemonicModal;
| 6,495
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mnemonic/GenerateMnemonicModal.tsx
|
import { useEffect, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { useLoading } from '@proton/hooks';
import { reactivateMnemonicPhrase, updateMnemonicPhrase } from '@proton/shared/lib/api/settingsMnemonic';
import { lockSensitiveSettings, unlockPasswordChanges } from '@proton/shared/lib/api/user';
import { MNEMONIC_STATUS } from '@proton/shared/lib/interfaces';
import { MnemonicData, generateMnemonicPayload, generateMnemonicWithSalt } from '@proton/shared/lib/mnemonic';
import noop from '@proton/utils/noop';
import {
ModalTwo as Modal,
ModalTwoContent as ModalContent,
ModalTwoFooter as ModalFooter,
ModalTwoHeader as ModalHeader,
ModalProps,
Prompt,
useModalState,
} from '../../components';
import { useApi, useEventManager, useGetUserKeys, useUser } from '../../hooks';
import AuthModal from '../password/AuthModal';
import { MnemonicPhraseStepButtons, MnemonicPhraseStepContent } from './MnemonicPhraseStep';
enum STEPS {
CONFIRM,
AUTH,
MNEMONIC_PHRASE,
}
interface Props {
confirmStep?: boolean;
open: ModalProps['open'];
onClose: ModalProps['onClose'];
onExit: ModalProps['onExit'];
}
const GenerateMnemonicModal = ({ confirmStep = false, open, onClose, onExit }: Props) => {
const [{ Name, MnemonicStatus }] = useUser();
const callReactivateEndpoint =
MnemonicStatus === MNEMONIC_STATUS.ENABLED ||
MnemonicStatus === MNEMONIC_STATUS.OUTDATED ||
MnemonicStatus === MNEMONIC_STATUS.PROMPT;
const [authModalProps, setAuthModalOpen, renderAuthModal] = useModalState();
const nonConfirmStep = callReactivateEndpoint ? STEPS.MNEMONIC_PHRASE : STEPS.AUTH;
const [step, setStep] = useState(confirmStep ? STEPS.CONFIRM : nonConfirmStep);
const api = useApi();
const { call } = useEventManager();
const getUserKeys = useGetUserKeys();
const [generating, withGenerating] = useLoading();
const [reactivating, withReactivating] = useLoading();
const [mnemonicData, setMnemonicData] = useState<MnemonicData>();
const getPayload = async (data: MnemonicData) => {
const userKeys = await getUserKeys();
const { randomBytes, salt } = data;
return generateMnemonicPayload({ randomBytes, salt, userKeys, api, username: Name });
};
const handleReactivate = async (data: MnemonicData) => {
try {
const payload = await getPayload(data);
await api(reactivateMnemonicPhrase(payload));
await call();
if (confirmStep) {
setStep(STEPS.MNEMONIC_PHRASE);
}
} catch (error: any) {
onClose?.();
}
};
useEffect(() => {
const generateMnemonicData = async () => {
const data = await generateMnemonicWithSalt();
setMnemonicData(data);
if (step === STEPS.AUTH) {
setAuthModalOpen(true);
return;
}
if (!confirmStep && callReactivateEndpoint) {
await handleReactivate(data);
}
};
void withGenerating(generateMnemonicData());
}, []);
const authenticating = step === STEPS.AUTH;
const handleClose = generating ? noop : onClose;
return (
<>
{renderAuthModal && mnemonicData && (
<AuthModal
config={unlockPasswordChanges()}
{...authModalProps}
onCancel={onClose}
onSuccess={async () => {
try {
const payload = await getPayload(mnemonicData);
await api(updateMnemonicPhrase(payload));
await call();
await api(lockSensitiveSettings());
setStep(STEPS.MNEMONIC_PHRASE);
} catch (e) {
onClose?.();
}
}}
/>
)}
{step === STEPS.CONFIRM && (
<Prompt
open={open}
title={c('Title').t`Generate new recovery phrase?`}
buttons={[
<Button
color="norm"
disabled={!mnemonicData}
loading={reactivating}
onClick={() => {
if (!mnemonicData) {
return;
}
if (callReactivateEndpoint) {
void withReactivating(handleReactivate(mnemonicData));
} else {
setAuthModalOpen(true);
}
}}
>
{c('Action').t`Generate recovery phrase`}
</Button>,
<Button disabled={reactivating} onClick={onClose}>
{c('Action').t`Cancel`}
</Button>,
]}
onExit={onExit}
>
<p className="m-0">{c('Info').t`Generating a new recovery phrase will deactivate your old one.`}</p>
</Prompt>
)}
{(step === STEPS.MNEMONIC_PHRASE || authenticating) && (
<Modal size="small" open={open} onClose={handleClose} onExit={onExit}>
<ModalHeader title={c('Info').t`Your recovery phrase`} />
<ModalContent>
<MnemonicPhraseStepContent
mnemonic={mnemonicData?.mnemonic}
loading={generating || authenticating}
/>
</ModalContent>
<ModalFooter>
<MnemonicPhraseStepButtons
mnemonic={mnemonicData?.mnemonic}
disabled={generating || authenticating}
onDone={onClose}
/>
</ModalFooter>
</Modal>
)}
</>
);
};
export default GenerateMnemonicModal;
| 6,496
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mnemonic/MnemonicInputField.tsx
|
import { useEffect, useState } from 'react';
import { c } from 'ttag';
import { validateMnemonic } from '@proton/shared/lib/mnemonic';
import { InputFieldTwo, TextAreaTwo } from '../../components';
import { InputFieldProps } from '../../components/v2/field/InputField';
export const useMnemonicInputValidation = (mnemonic: string) => {
const InvalidPassphraseError = c('Error').t`Wrong recovery phrase. Try again or use another recovery method.`;
const [mnemonicError, setMnemonicError] = useState('');
useEffect(() => {
validateMnemonic(mnemonic)
.then((isValid) => setMnemonicError(!isValid ? InvalidPassphraseError : ''))
.catch(() => setMnemonicError(''));
}, [mnemonic]);
return [
(() => {
const splitWords = mnemonic.split(/\s+/);
return splitWords.length !== 12 ? InvalidPassphraseError : '';
})(),
(() => {
return mnemonicError;
})(),
];
};
interface Props extends Omit<InputFieldProps<typeof TextAreaTwo>, 'as'> {}
const MnemonicInputField = ({
id = 'mnemonic',
bigger = true,
rows = 3,
label = c('Label').t`Recovery phrase`,
assistiveText = c('Label').t`Phrase consists of 12 unique words in a specific order`,
onValue,
...rest
}: Props) => {
return (
<InputFieldTwo
id={id}
bigger={bigger}
as={TextAreaTwo}
rows={rows}
label={label}
assistiveText={assistiveText}
onValue={(newValue: string) => {
const splitWords = newValue.split(/\s+/);
const mnemonic = splitWords.slice(0, 12).join(' ');
return onValue?.(mnemonic);
}}
{...rest}
/>
);
};
export default MnemonicInputField;
| 6,497
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mnemonic/MnemonicPhraseStep.tsx
|
import { ReactNode } from 'react';
import { c } from 'ttag';
import { Button, Card } from '@proton/atoms';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import { Copy, Icon, Loader } from '../../components';
import { useNotifications } from '../../hooks';
export const MnemonicPhraseStepContent = ({
mnemonic,
loading,
children,
}: {
mnemonic?: string;
loading?: boolean;
children?: ReactNode;
}) => {
const { createNotification } = useNotifications();
const onCopy = () => {
createNotification({ text: c('Info').t`Recovery phrase copied to clipboard` });
};
return (
<>
{children ? (
children
) : (
<>
<p className="mt-0">
{c('Info').t`Your recovery phrase is a series of 12 words in a specific order.`}
</p>
<p className="color-warning">
<Icon className="mr-2 float-left mt-1" name="exclamation-circle-filled" />
{c('Info')
.t`Please keep it safe. You'll need it to access your account and decrypt your data in case of a password reset.`}
</p>
</>
)}
{!mnemonic || loading ? (
<Loader />
) : (
<>
<span className="text-semibold">{c('Label').t`Recovery phrase`}</span>
<Card
className="mt-2 flex flex-justify-space-between flex-align-items-center flex-nowrap"
bordered={false}
rounded
>
<span className="mr-2" data-testid="account:recovery:generatedRecoveryPhrase">
{mnemonic}
</span>
<Copy className="bg-norm flex-item-noshrink" value={mnemonic} onCopy={onCopy} />
</Card>
</>
)}
</>
);
};
interface MnemonicPhraseStepButtonsProps {
mnemonic?: string;
disabled?: boolean;
onDone?: () => void;
}
export const MnemonicPhraseStepButtons = ({ mnemonic, disabled, onDone }: MnemonicPhraseStepButtonsProps) => {
const { createNotification } = useNotifications();
const handleDownload = async () => {
if (!mnemonic) {
return;
}
const blob = new Blob([mnemonic], { type: 'text/plain;charset=utf-8' });
downloadFile(blob, `proton_recovery_phrase.txt`);
createNotification({ text: c('Info').t`Recovery phrase downloaded` });
};
return (
<>
<Button disabled={!mnemonic || disabled} onClick={onDone}>
{c('Action').t`Done`}
</Button>
<Button disabled={!mnemonic || disabled} onClick={handleDownload} color="norm">
{c('Action').t`Download`}
</Button>
</>
);
};
| 6,498
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/containers
|
petrpan-code/ProtonMail/WebClients/packages/components/containers/mnemonic/helper.ts
|
import { APPS, APP_NAMES } from '@proton/shared/lib/constants';
import { Address, MNEMONIC_STATUS, User } from '@proton/shared/lib/interfaces';
import { getHasMigratedAddressKeys } from '@proton/shared/lib/keys';
import { isPrivate } from '@proton/shared/lib/user/helpers';
export const getIsMnemonicAvailable = ({
addresses,
user,
app,
}: {
addresses: Address[];
user: User;
app: APP_NAMES;
}) => {
const hasMigratedKeys = getHasMigratedAddressKeys(addresses);
const isNonPrivateUser = !isPrivate(user);
return hasMigratedKeys && !isNonPrivateUser && app !== APPS.PROTONVPN_SETTINGS;
};
export const getCanReactiveMnemonic = (user: User) => {
return (
user.MnemonicStatus === MNEMONIC_STATUS.PROMPT ||
user.MnemonicStatus === MNEMONIC_STATUS.ENABLED ||
user.MnemonicStatus === MNEMONIC_STATUS.OUTDATED
);
};
| 6,499
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.