mirror of
https://github.com/outline/outline.git
synced 2026-12-06 03:05:08 +03:00
expiring share links feature
This commit is contained in:
1 parent
4a5a616a21
commit
5bdafe721d
18 files changed
+539
-32
No files matched your search
@@ -5,7 +5,8 @@ import { CopyIcon, GlobeIcon } from "outline-icons";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { useTheme } from "styled-components";
|
||||
import styled, { useTheme } from "styled-components";
|
||||
import { differenceInCalendarDays, endOfDay } from "date-fns";
|
||||
import { errToString } from "@shared/utils/error";
|
||||
import Squircle from "@shared/components/Squircle";
|
||||
import { UrlHelper } from "@shared/utils/UrlHelper";
|
||||
@@ -14,6 +15,7 @@ import type Share from "~/models/Share";
|
||||
import { AvatarSize } from "~/components/Avatar";
|
||||
import CopyToClipboard from "~/components/CopyToClipboard";
|
||||
import Flex from "~/components/Flex";
|
||||
import { InputSelect, type Option } from "~/components/InputSelect";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import { ResizingHeightContainer } from "~/components/ResizingHeightContainer";
|
||||
import Switch from "~/components/Switch";
|
||||
@@ -22,9 +24,17 @@ import Tooltip from "~/components/Tooltip";
|
||||
import env from "~/env";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import useUserLocale from "~/hooks/useUserLocale";
|
||||
import { dateToExpiry } from "~/utils/date";
|
||||
import { ListItem } from "../components/ListItem";
|
||||
import ShareSettingsPopover from "../components/ShareSettingsPopover";
|
||||
import { DomainPrefix, ShareLinkInput, StyledInfoIcon } from "../components";
|
||||
import ExpiryDatePicker from "~/scenes/ApiKeyNew/components/ExpiryDatePicker";
|
||||
import {
|
||||
ExpiryType,
|
||||
ExpiryValues,
|
||||
calculateExpiryDate,
|
||||
} from "~/scenes/ApiKeyNew/utils";
|
||||
|
||||
type Props = {
|
||||
/** The collection to share. */
|
||||
@@ -47,11 +57,53 @@ function InnerPublicAccess(
|
||||
const collectionAbilities = usePolicy(collection);
|
||||
const canPublish = share ? can.update : collectionAbilities.share;
|
||||
const [creating, setCreating] = React.useState(false);
|
||||
const userLocale = useUserLocale();
|
||||
const currentDate = React.useRef<Date>(new Date());
|
||||
const [expiryType, setExpiryType] = React.useState<ExpiryType>(
|
||||
ExpiryType.Month
|
||||
);
|
||||
const [expiresAt, setExpiresAt] = React.useState<Date | undefined>(() =>
|
||||
calculateExpiryDate(currentDate.current, ExpiryType.Month)
|
||||
);
|
||||
|
||||
const expiryOptions = React.useMemo<Option[]>(
|
||||
() =>
|
||||
[...ExpiryValues.entries()].map(([expType, { label }]) => ({
|
||||
type: "item",
|
||||
label,
|
||||
value: expType,
|
||||
})),
|
||||
[]
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
setUrlId(share?.urlId);
|
||||
}, [share?.urlId]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!share?.expiresAt) {
|
||||
setExpiryType(ExpiryType.NoExpiration);
|
||||
setExpiresAt(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedExpiresAt = new Date(share.expiresAt);
|
||||
const daysUntilExpiry = differenceInCalendarDays(
|
||||
parsedExpiresAt,
|
||||
currentDate.current
|
||||
);
|
||||
|
||||
const matchedType = [
|
||||
ExpiryType.Week,
|
||||
ExpiryType.Month,
|
||||
ExpiryType.TwoMonths,
|
||||
ExpiryType.ThreeMonths,
|
||||
].find((type) => ExpiryValues.get(type)?.value === daysUntilExpiry);
|
||||
|
||||
setExpiresAt(parsedExpiresAt);
|
||||
setExpiryType(matchedType ?? ExpiryType.Custom);
|
||||
}, [share?.expiresAt]);
|
||||
|
||||
const handlePublishedChange = React.useCallback(
|
||||
async (checked: boolean) => {
|
||||
try {
|
||||
@@ -61,11 +113,15 @@ function InnerPublicAccess(
|
||||
type: "collection",
|
||||
collectionId: collection.id,
|
||||
published: true,
|
||||
expiresAt: expiresAt?.toISOString(),
|
||||
});
|
||||
copy(newShare.url);
|
||||
toast.success(t("Public link copied to clipboard"));
|
||||
} else if (share) {
|
||||
await share.save({ published: checked });
|
||||
await share.save({
|
||||
published: checked,
|
||||
expiresAt: expiresAt?.toISOString() ?? null,
|
||||
});
|
||||
if (checked) {
|
||||
copy(share.url);
|
||||
toast.success(t("Public link copied to clipboard"));
|
||||
@@ -77,7 +133,46 @@ function InnerPublicAccess(
|
||||
setCreating(false);
|
||||
}
|
||||
},
|
||||
[t, share, shares, collection]
|
||||
[t, share, shares, collection, expiresAt]
|
||||
);
|
||||
|
||||
const updateShareExpiry = React.useCallback(
|
||||
async (date?: Date) => {
|
||||
if (!share?.published) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await share.save({ expiresAt: date?.toISOString() ?? null });
|
||||
} catch (err) {
|
||||
toast.error(errToString(err));
|
||||
}
|
||||
},
|
||||
[share]
|
||||
);
|
||||
|
||||
const handleExpiryTypeChange = React.useCallback(
|
||||
async (value: string) => {
|
||||
const nextExpiryType = value as ExpiryType;
|
||||
const nextExpiresAt = calculateExpiryDate(
|
||||
currentDate.current,
|
||||
nextExpiryType
|
||||
);
|
||||
|
||||
setExpiryType(nextExpiryType);
|
||||
setExpiresAt(nextExpiresAt);
|
||||
await updateShareExpiry(nextExpiresAt);
|
||||
},
|
||||
[updateShareExpiry]
|
||||
);
|
||||
|
||||
const handleSelectCustomDate = React.useCallback(
|
||||
async (date: Date) => {
|
||||
const nextExpiresAt = endOfDay(date);
|
||||
setExpiresAt(nextExpiresAt);
|
||||
await updateShareExpiry(nextExpiresAt);
|
||||
},
|
||||
[updateShareExpiry]
|
||||
);
|
||||
|
||||
const handleUrlChange = React.useMemo(
|
||||
@@ -169,6 +264,26 @@ function InnerPublicAccess(
|
||||
</ShareLinkInput>
|
||||
<ShareSettingsPopover share={share} />
|
||||
</Flex>
|
||||
<Flex align="center" gap={8}>
|
||||
<StyledExpirySelect
|
||||
options={expiryOptions}
|
||||
value={expiryType}
|
||||
onChange={handleExpiryTypeChange}
|
||||
label={t("Expiration Date")}
|
||||
/>
|
||||
{expiryType === ExpiryType.Custom ? (
|
||||
<ExpiryDatePicker
|
||||
selectedDate={expiresAt}
|
||||
onSelect={handleSelectCustomDate}
|
||||
/>
|
||||
) : (
|
||||
<Text type="secondary" size="small">
|
||||
{expiresAt
|
||||
? `${dateToExpiry(expiresAt.toISOString(), t, userLocale)}.`
|
||||
: `${t("Never expires")}.`}
|
||||
</Text>
|
||||
)}
|
||||
</Flex>
|
||||
<Flex align="flex-start" gap={4}>
|
||||
<StyledInfoIcon color={theme.textTertiary} />
|
||||
<Text type="tertiary" size="xsmall">
|
||||
@@ -185,4 +300,9 @@ function InnerPublicAccess(
|
||||
);
|
||||
}
|
||||
|
||||
const StyledExpirySelect = styled(InputSelect)`
|
||||
width: 150px !important;
|
||||
margin-bottom: 0;
|
||||
`;
|
||||
|
||||
export const PublicAccess = observer(React.forwardRef(InnerPublicAccess));
|
||||
@@ -5,17 +5,21 @@ import { CopyIcon, GlobeIcon } from "outline-icons";
|
||||
import * as React from "react";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { useTheme } from "styled-components";
|
||||
import styled, { useTheme } from "styled-components";
|
||||
import { differenceInCalendarDays, endOfDay } from "date-fns";
|
||||
import { errToString } from "@shared/utils/error";
|
||||
import Flex from "@shared/components/Flex";
|
||||
import Squircle from "@shared/components/Squircle";
|
||||
import { UrlHelper } from "@shared/utils/UrlHelper";
|
||||
import type Document from "~/models/Document";
|
||||
import type Share from "~/models/Share";
|
||||
import { InputSelect, type Option } from "~/components/InputSelect";
|
||||
import Switch from "~/components/Switch";
|
||||
import env from "~/env";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import useUserLocale from "~/hooks/useUserLocale";
|
||||
import { dateToExpiry } from "~/utils/date";
|
||||
import { AvatarSize } from "../../Avatar";
|
||||
import CopyToClipboard from "../../CopyToClipboard";
|
||||
import NudeButton from "../../NudeButton";
|
||||
@@ -30,6 +34,12 @@ import {
|
||||
StyledInfoIcon,
|
||||
UnderlinedLink,
|
||||
} from "../components";
|
||||
import ExpiryDatePicker from "~/scenes/ApiKeyNew/components/ExpiryDatePicker";
|
||||
import {
|
||||
ExpiryType,
|
||||
ExpiryValues,
|
||||
calculateExpiryDate,
|
||||
} from "~/scenes/ApiKeyNew/utils";
|
||||
|
||||
type Props = {
|
||||
/** The document to share. */
|
||||
@@ -57,11 +67,53 @@ function PublicAccess(
|
||||
const documentAbilities = usePolicy(document);
|
||||
const canPublish = share ? can.update : documentAbilities.share;
|
||||
const [creating, setCreating] = React.useState(false);
|
||||
const userLocale = useUserLocale();
|
||||
const currentDate = React.useRef<Date>(new Date());
|
||||
const [expiryType, setExpiryType] = React.useState<ExpiryType>(
|
||||
ExpiryType.Month
|
||||
);
|
||||
const [expiresAt, setExpiresAt] = React.useState<Date | undefined>(() =>
|
||||
calculateExpiryDate(currentDate.current, ExpiryType.Month)
|
||||
);
|
||||
|
||||
const expiryOptions = React.useMemo<Option[]>(
|
||||
() =>
|
||||
[...ExpiryValues.entries()].map(([expType, { label }]) => ({
|
||||
type: "item",
|
||||
label,
|
||||
value: expType,
|
||||
})),
|
||||
[]
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
setUrlId(share?.urlId);
|
||||
}, [share?.urlId]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!share?.expiresAt) {
|
||||
setExpiryType(ExpiryType.NoExpiration);
|
||||
setExpiresAt(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedExpiresAt = new Date(share.expiresAt);
|
||||
const daysUntilExpiry = differenceInCalendarDays(
|
||||
parsedExpiresAt,
|
||||
currentDate.current
|
||||
);
|
||||
|
||||
const matchedType = [
|
||||
ExpiryType.Week,
|
||||
ExpiryType.Month,
|
||||
ExpiryType.TwoMonths,
|
||||
ExpiryType.ThreeMonths,
|
||||
].find((type) => ExpiryValues.get(type)?.value === daysUntilExpiry);
|
||||
|
||||
setExpiresAt(parsedExpiresAt);
|
||||
setExpiryType(matchedType ?? ExpiryType.Custom);
|
||||
}, [share?.expiresAt]);
|
||||
|
||||
const handlePublishedChange = React.useCallback(
|
||||
async (checked: boolean) => {
|
||||
try {
|
||||
@@ -71,11 +123,15 @@ function PublicAccess(
|
||||
type: "document",
|
||||
documentId: document.id,
|
||||
published: true,
|
||||
expiresAt: expiresAt?.toISOString(),
|
||||
});
|
||||
copy(newShare.url);
|
||||
toast.success(t("Public link copied to clipboard"));
|
||||
} else if (share) {
|
||||
await share.save({ published: checked });
|
||||
await share.save({
|
||||
published: checked,
|
||||
expiresAt: expiresAt?.toISOString() ?? null,
|
||||
});
|
||||
if (checked) {
|
||||
copy(share.url);
|
||||
toast.success(t("Public link copied to clipboard"));
|
||||
@@ -87,7 +143,46 @@ function PublicAccess(
|
||||
setCreating(false);
|
||||
}
|
||||
},
|
||||
[t, share, shares, document]
|
||||
[t, share, shares, document, expiresAt]
|
||||
);
|
||||
|
||||
const updateShareExpiry = React.useCallback(
|
||||
async (date?: Date) => {
|
||||
if (!share?.published) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await share.save({ expiresAt: date?.toISOString() ?? null });
|
||||
} catch (err) {
|
||||
toast.error(errToString(err));
|
||||
}
|
||||
},
|
||||
[share]
|
||||
);
|
||||
|
||||
const handleExpiryTypeChange = React.useCallback(
|
||||
async (value: string) => {
|
||||
const nextExpiryType = value as ExpiryType;
|
||||
const nextExpiresAt = calculateExpiryDate(
|
||||
currentDate.current,
|
||||
nextExpiryType
|
||||
);
|
||||
|
||||
setExpiryType(nextExpiryType);
|
||||
setExpiresAt(nextExpiresAt);
|
||||
await updateShareExpiry(nextExpiresAt);
|
||||
},
|
||||
[updateShareExpiry]
|
||||
);
|
||||
|
||||
const handleSelectCustomDate = React.useCallback(
|
||||
async (date: Date) => {
|
||||
const nextExpiresAt = endOfDay(date);
|
||||
setExpiresAt(nextExpiresAt);
|
||||
await updateShareExpiry(nextExpiresAt);
|
||||
},
|
||||
[updateShareExpiry]
|
||||
);
|
||||
|
||||
const handleUrlChange = React.useMemo(
|
||||
@@ -198,24 +293,46 @@ function PublicAccess(
|
||||
{copyButton}
|
||||
</ShareLinkInput>
|
||||
) : share?.published ? (
|
||||
<Flex align="center" gap={2}>
|
||||
<ShareLinkInput
|
||||
type="text"
|
||||
ref={inputRef}
|
||||
placeholder={share?.id}
|
||||
onChange={handleUrlChange}
|
||||
error={validationError}
|
||||
defaultValue={urlId}
|
||||
prefix={
|
||||
<DomainPrefix onClick={() => inputRef.current?.focus()}>
|
||||
{env.URL.replace(/https?:\/\//, "") + "/s/"}
|
||||
</DomainPrefix>
|
||||
}
|
||||
>
|
||||
{copyButton}
|
||||
</ShareLinkInput>
|
||||
<ShareSettingsPopover share={share} />
|
||||
</Flex>
|
||||
<>
|
||||
<Flex align="center" gap={2}>
|
||||
<ShareLinkInput
|
||||
type="text"
|
||||
ref={inputRef}
|
||||
placeholder={share?.id}
|
||||
onChange={handleUrlChange}
|
||||
error={validationError}
|
||||
defaultValue={urlId}
|
||||
prefix={
|
||||
<DomainPrefix onClick={() => inputRef.current?.focus()}>
|
||||
{env.URL.replace(/https?:\/\//, "") + "/s/"}
|
||||
</DomainPrefix>
|
||||
}
|
||||
>
|
||||
{copyButton}
|
||||
</ShareLinkInput>
|
||||
<ShareSettingsPopover share={share} />
|
||||
</Flex>
|
||||
<Flex align="center" gap={8}>
|
||||
<StyledExpirySelect
|
||||
options={expiryOptions}
|
||||
value={expiryType}
|
||||
onChange={handleExpiryTypeChange}
|
||||
label={t("Expiration")}
|
||||
/>
|
||||
{expiryType === ExpiryType.Custom ? (
|
||||
<ExpiryDatePicker
|
||||
selectedDate={expiresAt}
|
||||
onSelect={handleSelectCustomDate}
|
||||
/>
|
||||
) : (
|
||||
<Text type="secondary" size="small">
|
||||
{expiresAt
|
||||
? `${dateToExpiry(expiresAt.toISOString(), t, userLocale)}.`
|
||||
: `${t("Never expires")}.`}
|
||||
</Text>
|
||||
)}
|
||||
</Flex>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{share?.published && !share.includeChildDocuments ? (
|
||||
@@ -234,4 +351,9 @@ function PublicAccess(
|
||||
);
|
||||
}
|
||||
|
||||
const StyledExpirySelect = styled(InputSelect)`
|
||||
width: 150px !important;
|
||||
margin-bottom: 0;
|
||||
`;
|
||||
|
||||
export default observer(React.forwardRef(PublicAccess));
|
||||
@@ -27,6 +27,10 @@ class Share extends Model implements Searchable {
|
||||
@observable
|
||||
includeChildDocuments: boolean;
|
||||
|
||||
@Field
|
||||
@observable
|
||||
expiresAt: string | null;
|
||||
|
||||
/** The document ID that is shared. */
|
||||
@Field
|
||||
@observable
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import Button from "~/components/Button";
|
||||
import Empty from "~/components/Empty";
|
||||
import Heading from "~/components/Heading";
|
||||
import Scene from "~/components/Scene";
|
||||
import {
|
||||
navigateToHome,
|
||||
navigateToSearch,
|
||||
} from "~/actions/definitions/navigation";
|
||||
import { VStack } from "~/components/primitives/VStack";
|
||||
import { HStack } from "~/components/primitives/HStack";
|
||||
|
||||
const ErrorExpiredLink = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Scene title={t("Expired Link")}>
|
||||
<Heading>{t("Expired Link")}</Heading>
|
||||
<VStack spacing={20} style={{ maxWidth: 500 }} align="initial">
|
||||
<Empty size="large">
|
||||
<Trans>
|
||||
This Link has expired or has been deactivated. Please contact a
|
||||
document admin to restore access.
|
||||
</Trans>
|
||||
</Empty>
|
||||
<HStack>
|
||||
<Button action={navigateToHome} neutral hideIcon>
|
||||
{t("Home")}
|
||||
</Button>
|
||||
<Button action={navigateToSearch} neutral>
|
||||
{t("Search")}...
|
||||
</Button>
|
||||
</HStack>
|
||||
</VStack>
|
||||
</Scene>
|
||||
);
|
||||
};
|
||||
|
||||
export default ErrorExpiredLink;
|
||||
@@ -114,6 +114,28 @@ export function SharesTable({ data, canManage, ...rest }: Props) {
|
||||
) : null,
|
||||
width: "2fr",
|
||||
},
|
||||
{
|
||||
type: "data",
|
||||
id: "expiresAt",
|
||||
header: t("Expires"),
|
||||
accessor: (share) => share.expiresAt,
|
||||
component: (share) =>
|
||||
share.expiresAt ? (
|
||||
<Time
|
||||
dateTime={share.expiresAt}
|
||||
relative={false}
|
||||
format={{
|
||||
en_US: "MMM d, yyyy",
|
||||
en_GB: "d MMM yyyy",
|
||||
fr_FR: "d MMM yyyy",
|
||||
de_DE: "dd.MM.yyyy",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
t("None")
|
||||
),
|
||||
width: "2fr",
|
||||
},
|
||||
hasDomain
|
||||
? {
|
||||
type: "data",
|
||||
|
||||
@@ -26,7 +26,11 @@ import useRequest from "~/hooks/useRequest";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { Theme } from "~/stores/UiStore";
|
||||
import { client } from "~/utils/ApiClient";
|
||||
import { AuthorizationError, OfflineError } from "~/utils/errors";
|
||||
import {
|
||||
AuthorizationError,
|
||||
OfflineError,
|
||||
ResourceExpiredError,
|
||||
} from "~/utils/errors";
|
||||
import isCloudHosted from "~/utils/isCloudHosted";
|
||||
import { changeLanguage, detectLanguage } from "~/utils/language";
|
||||
import Loading from "../Document/components/Loading";
|
||||
@@ -37,6 +41,7 @@ import DelayedMount from "~/components/DelayedMount";
|
||||
import lazyWithRetry from "~/utils/lazyWithRetry";
|
||||
import { ShareContext } from "@shared/hooks/useShare";
|
||||
import ClickablePadding from "~/components/ClickablePadding";
|
||||
import ErrorExpiredLink from "../Errors/ErrorExpiredLink";
|
||||
|
||||
const Login = lazyWithRetry(() => import("../Login"));
|
||||
|
||||
@@ -232,6 +237,11 @@ function SharedScene() {
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
if (error instanceof ResourceExpiredError) {
|
||||
return <ErrorExpiredLink />;
|
||||
}
|
||||
|
||||
return <Error404 />;
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
PaymentRequiredError,
|
||||
RateLimitExceededError,
|
||||
RequestError,
|
||||
ResourceExpiredError,
|
||||
ServiceUnavailableError,
|
||||
UnprocessableEntityError,
|
||||
UpdateRequiredError,
|
||||
@@ -223,11 +224,9 @@ class ApiClient {
|
||||
let response;
|
||||
|
||||
try {
|
||||
response = await (
|
||||
options?.retry === false
|
||||
? fetchWithFreshCsrfToken
|
||||
: retry(fetchWithFreshCsrfToken)
|
||||
)(urlToFetch, {
|
||||
response = await (options?.retry === false
|
||||
? fetchWithFreshCsrfToken
|
||||
: retry(fetchWithFreshCsrfToken))(urlToFetch, {
|
||||
method,
|
||||
body,
|
||||
headers,
|
||||
@@ -364,6 +363,10 @@ class ApiClient {
|
||||
return new NotFoundError(message);
|
||||
}
|
||||
|
||||
if (status === 410) {
|
||||
throw new ResourceExpiredError(message);
|
||||
}
|
||||
|
||||
if (status === 503) {
|
||||
return new ServiceUnavailableError(message);
|
||||
}
|
||||
|
||||
@@ -68,3 +68,8 @@ export class RequestError extends ExtendableError {
|
||||
export class UpdateRequiredError extends ExtendableError {
|
||||
name = "UpdateRequiredError";
|
||||
}
|
||||
|
||||
/** Error thrown when the link is expired or has been deactivated. */
|
||||
export class ResourceExpiredError extends ExtendableError {
|
||||
name = "ResourceExpiredError";
|
||||
}
|
||||
@@ -329,6 +329,14 @@ describe("shareLoader", () => {
|
||||
await expect(loadPublicShare({ id: share.id })).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("should throw error when share is expired", async () => {
|
||||
const share = await buildShare({
|
||||
expiresAt: new Date(Date.now() - 60 * 1000),
|
||||
});
|
||||
|
||||
await expect(loadPublicShare({ id: share.id })).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("should throw error when team has disabled sharing", async () => {
|
||||
const team = await buildTeam({
|
||||
sharing: false,
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
InvalidRequestError,
|
||||
NotFoundError,
|
||||
PaymentRequiredError,
|
||||
ResourceExpiredError,
|
||||
} from "@server/errors";
|
||||
import type { User } from "@server/models";
|
||||
import { Collection, Document, Share } from "@server/models";
|
||||
@@ -68,6 +69,10 @@ export async function loadPublicShare({
|
||||
],
|
||||
});
|
||||
|
||||
if (share?.expiresAt && share.expiresAt < new Date()) {
|
||||
throw ResourceExpiredError("Share link has expired");
|
||||
}
|
||||
|
||||
if (
|
||||
!share ||
|
||||
!!share.team.suspendedAt ||
|
||||
|
||||
@@ -268,3 +268,10 @@ export function ClientClosedRequestError(
|
||||
isReportable: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function ResourceExpiredError(message = "Resource has expired") {
|
||||
return httpErrors(410, message, {
|
||||
id: "resource_expired",
|
||||
isReportable: false,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.addColumn("shares", "expiresAt", {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
});
|
||||
},
|
||||
down: async (queryInterface) => {
|
||||
await queryInterface.removeColumn("shares", "expiresAt");
|
||||
},
|
||||
};
|
||||
@@ -120,6 +120,10 @@ class Share extends IdModel<
|
||||
@Column(DataType.DATE)
|
||||
lastAccessedAt: Date | null;
|
||||
|
||||
@AllowNull
|
||||
@Column(DataType.DATE)
|
||||
expiresAt: Date | null;
|
||||
|
||||
/** Total count of times the shared link has been accessed */
|
||||
@Default(0)
|
||||
@Column(DataType.INTEGER)
|
||||
|
||||
@@ -31,6 +31,7 @@ export default function presentShare(share: Share, options: Options = {}) {
|
||||
? {}
|
||||
: { createdBy: presentUser(share.user) }),
|
||||
includeChildDocuments: share.includeChildDocuments,
|
||||
expiresAt: share.expiresAt,
|
||||
allowIndexing: share.allowIndexing,
|
||||
allowSubscriptions: share.allowSubscriptions,
|
||||
showLastUpdated: share.showLastUpdated,
|
||||
|
||||
@@ -53,6 +53,7 @@ export type SharesListReq = z.infer<typeof SharesListSchema>;
|
||||
export const SharesUpdateSchema = BaseSchema.extend({
|
||||
body: z.object({
|
||||
id: z.uuid(),
|
||||
expiresAt: z.coerce.date().nullish(),
|
||||
includeChildDocuments: z.boolean().optional(),
|
||||
published: z.boolean().optional(),
|
||||
allowIndexing: z.boolean().optional(),
|
||||
@@ -79,11 +80,27 @@ export const SharesUpdateSchema = BaseSchema.extend({
|
||||
|
||||
export type SharesUpdateReq = z.infer<typeof SharesUpdateSchema>;
|
||||
|
||||
const isTodayOrAfter = (value: Date) => {
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
const candidate = new Date(value);
|
||||
candidate.setHours(0, 0, 0, 0);
|
||||
|
||||
return candidate >= today;
|
||||
};
|
||||
|
||||
export const SharesCreateSchema = BaseSchema.extend({
|
||||
body: z
|
||||
.object({
|
||||
collectionId: zodIdType().optional(),
|
||||
documentId: zodIdType().optional(),
|
||||
expiresAt: z.coerce
|
||||
.date()
|
||||
.nullish()
|
||||
.refine((value) => !value || isTodayOrAfter(value), {
|
||||
error: "must be today or later",
|
||||
}),
|
||||
published: z.boolean().prefault(false),
|
||||
allowIndexing: z.boolean().optional(),
|
||||
allowSubscriptions: z.boolean().optional(),
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from "@server/test/factories";
|
||||
|
||||
import { getTestServer, withAPIContext } from "@server/test/support";
|
||||
import { subDays } from "date-fns";
|
||||
|
||||
const server = getTestServer();
|
||||
|
||||
@@ -141,6 +142,33 @@ describe("#shares.list", () => {
|
||||
expect(body.data.length).toEqual(0);
|
||||
});
|
||||
|
||||
it("should include expiresAt in list results", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
||||
const share = await buildShare({
|
||||
documentId: document.id,
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
expiresAt,
|
||||
});
|
||||
|
||||
const res = await server.post("/api/shares.list", user);
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
const listed = body.data.find(
|
||||
(item: { id: string; expiresAt: string }) => item.id === share.id
|
||||
);
|
||||
expect(listed).toBeTruthy();
|
||||
expect(new Date(listed.expiresAt).toISOString()).toEqual(
|
||||
expiresAt.toISOString()
|
||||
);
|
||||
});
|
||||
|
||||
it("should not return shares to deleted documents", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
@@ -311,6 +339,45 @@ describe("#shares.create", () => {
|
||||
expect(body.data.documentTitle).toBe(document.title);
|
||||
});
|
||||
|
||||
it("should allow creating a published share with expiresAt", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
const res = await server.post("/api/shares.create", user, {
|
||||
body: {
|
||||
documentId: document.id,
|
||||
published: true,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(new Date(body.data.expiresAt).toISOString()).toEqual(
|
||||
expiresAt.toISOString()
|
||||
);
|
||||
});
|
||||
|
||||
it("should reject create when expiresAt is in the past", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
|
||||
const res = await server.post("/api/shares.create", user, {
|
||||
body: {
|
||||
documentId: document.id,
|
||||
expiresAt: subDays(new Date(), 1).toISOString(),
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(400);
|
||||
});
|
||||
|
||||
it("should set includeChildDocuments when creating a published share", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
@@ -1032,6 +1099,58 @@ describe("#shares.update", () => {
|
||||
expect(body.data.urlId).toBeNull();
|
||||
});
|
||||
|
||||
it("should update expiresAt", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
const share = await buildShare({
|
||||
documentId: document.id,
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const expiresAt = new Date(Date.now() + 60 * 24 * 60 * 60 * 1000);
|
||||
|
||||
const res = await server.post("/api/shares.update", user, {
|
||||
body: {
|
||||
id: share.id,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(new Date(body.data.expiresAt).toISOString()).toEqual(
|
||||
expiresAt.toISOString()
|
||||
);
|
||||
});
|
||||
|
||||
it("should allow clearing expiresAt", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
});
|
||||
const share = await buildShare({
|
||||
documentId: document.id,
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
expiresAt: new Date(Date.now() + 60 * 24 * 60 * 60 * 1000),
|
||||
});
|
||||
|
||||
const res = await server.post("/api/shares.update", user, {
|
||||
body: {
|
||||
id: share.id,
|
||||
expiresAt: null,
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body.data.expiresAt).toBeNull();
|
||||
});
|
||||
|
||||
it("should update title and iconUrl", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({
|
||||
|
||||
@@ -270,6 +270,7 @@ router.post(
|
||||
const {
|
||||
collectionId,
|
||||
documentId,
|
||||
expiresAt,
|
||||
published,
|
||||
urlId,
|
||||
includeChildDocuments,
|
||||
@@ -321,6 +322,7 @@ router.post(
|
||||
allowSubscriptions,
|
||||
showLastUpdated,
|
||||
showTOC,
|
||||
expiresAt: expiresAt ?? null,
|
||||
urlId,
|
||||
},
|
||||
});
|
||||
@@ -355,6 +357,7 @@ router.post(
|
||||
async (ctx: APIContext<T.SharesUpdateReq>) => {
|
||||
const {
|
||||
id,
|
||||
expiresAt,
|
||||
includeChildDocuments,
|
||||
published,
|
||||
urlId,
|
||||
@@ -387,6 +390,10 @@ router.post(
|
||||
share.includeChildDocuments = includeChildDocuments;
|
||||
}
|
||||
|
||||
if (!isUndefined(expiresAt)) {
|
||||
share.expiresAt = expiresAt ?? null;
|
||||
}
|
||||
|
||||
if (!isUndefined(urlId)) {
|
||||
share.urlId = urlId;
|
||||
}
|
||||
|
||||
@@ -541,6 +541,8 @@
|
||||
"Publish to web": "Publish to web",
|
||||
"Allow anyone with the link to access": "Allow anyone with the link to access",
|
||||
"Publish to internet": "Publish to internet",
|
||||
"Expiration Date": "Expiration Date",
|
||||
"Never expires": "Never expires",
|
||||
"All documents in this collection will be shared on the web, including any new documents added later": "All documents in this collection will be shared on the web, including any new documents added later",
|
||||
"Invite": "Invite",
|
||||
"{{ userName }} was added to the collection": "{{ userName }} was added to the collection",
|
||||
@@ -598,6 +600,7 @@
|
||||
"Leave": "Leave",
|
||||
"Anyone with the link can access because the containing collection, <2>{sharedParent.sourceTitle}</2>, is shared": "Anyone with the link can access because the containing collection, <2>{sharedParent.sourceTitle}</2>, is shared",
|
||||
"Anyone with the link can access because the parent document, <2>{sharedParent.sourceTitle}</2>, is shared": "Anyone with the link can access because the parent document, <2>{sharedParent.sourceTitle}</2>, is shared",
|
||||
"Expiration": "Expiration",
|
||||
"Nested documents are not shared on the web. Toggle sharing to enable access, this will be the default behavior in the future": "Nested documents are not shared on the web. Toggle sharing to enable access, this will be the default behavior in the future",
|
||||
"{{ userName }} was added to the document": "{{ userName }} was added to the document",
|
||||
"{{ count }} people added to the document": "{{ count }} person added to the document",
|
||||
@@ -846,8 +849,6 @@
|
||||
"API key created. Please copy the value now as it will not be shown again.": "API key created. Please copy the value now as it will not be shown again.",
|
||||
"Scopes": "Scopes",
|
||||
"Space-separated scopes restrict the access of this API key to specific parts of the API. Leave blank for full access": "Space-separated scopes restrict the access of this API key to specific parts of the API. Leave blank for full access",
|
||||
"Expiration": "Expiration",
|
||||
"Never expires": "Never expires",
|
||||
"7 days": "7 days",
|
||||
"30 days": "30 days",
|
||||
"60 days": "60 days",
|
||||
@@ -1009,6 +1010,8 @@
|
||||
"Request access": "Request access",
|
||||
"Not found": "Not found",
|
||||
"The page you’re looking for cannot be found. It might have been deleted or the link is incorrect.": "The page you’re looking for cannot be found. It might have been deleted or the link is incorrect.",
|
||||
"Expired Link": "Expired Link",
|
||||
"This Link has expired or has been deactivated. Please contact a document admin to restore access.": "This Link has expired or has been deactivated. Please contact a document admin to restore access.",
|
||||
"We were unable to load the document while offline.": "We were unable to load the document while offline.",
|
||||
"Your account has been suspended": "Your account has been suspended",
|
||||
"Warning Sign": "Warning Sign",
|
||||
|
||||
Reference in new issue
Block a user