mirror of
https://github.com/swissmakers/swiss-datashare.git
synced 2026-04-19 13:33:13 +02:00
Add feature to send share with email
This commit is contained in:
166
src/components/share/CreateUploadModalBody.tsx
Normal file
166
src/components/share/CreateUploadModalBody.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
import {
|
||||
Accordion,
|
||||
Button,
|
||||
Col,
|
||||
Grid,
|
||||
Group,
|
||||
MultiSelect,
|
||||
NumberInput,
|
||||
PasswordInput,
|
||||
Select,
|
||||
Text,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import { useForm, yupResolver } from "@mantine/form";
|
||||
import { useModals } from "@mantine/modals";
|
||||
import * as yup from "yup";
|
||||
import shareService from "../../services/share.service";
|
||||
import toast from "../../utils/toast.util";
|
||||
|
||||
const CreateUploadModalBody = ({
|
||||
mode,
|
||||
uploadCallback,
|
||||
}: {
|
||||
mode: "standard" | "email";
|
||||
uploadCallback: (
|
||||
id: string,
|
||||
expiration: number,
|
||||
security: { password?: string; maxVisitors?: number },
|
||||
emails?: string[]
|
||||
) => void;
|
||||
}) => {
|
||||
const modals = useModals();
|
||||
const validationSchema = yup.object().shape({
|
||||
link: yup.string().required().min(2).max(50),
|
||||
emails: mode == "email" ? yup.array().of(yup.string().email()).min(1) : yup.array(),
|
||||
password: yup.string().min(3).max(100),
|
||||
maxVisitors: yup.number().min(1),
|
||||
});
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
link: "",
|
||||
emails: [] as string[],
|
||||
password: undefined,
|
||||
maxVisitors: undefined,
|
||||
expiration: "1440",
|
||||
},
|
||||
schema: yupResolver(validationSchema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={form.onSubmit(async (values) => {
|
||||
if (await shareService.isIdAlreadyInUse(values.link)) {
|
||||
form.setFieldError("link", "Link already in use.");
|
||||
} else {
|
||||
modals.closeAll();
|
||||
uploadCallback(
|
||||
values.link,
|
||||
parseInt(values.expiration),
|
||||
{
|
||||
password: values.password,
|
||||
maxVisitors: values.maxVisitors,
|
||||
},
|
||||
values.emails
|
||||
);
|
||||
}
|
||||
})}
|
||||
>
|
||||
<Group direction="column" grow>
|
||||
<Grid align={form.errors.link ? "center" : "flex-end"}>
|
||||
<Col xs={9}>
|
||||
<TextInput
|
||||
variant="filled"
|
||||
label="Link"
|
||||
placeholder="myAwesomeShare"
|
||||
{...form.getInputProps("link")}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={3}>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
form.setFieldValue(
|
||||
"link",
|
||||
Buffer.from(Math.random().toString(), "utf8")
|
||||
.toString("base64")
|
||||
.substr(10, 7)
|
||||
)
|
||||
}
|
||||
>
|
||||
Generate
|
||||
</Button>
|
||||
</Col>
|
||||
</Grid>
|
||||
|
||||
<Text
|
||||
size="xs"
|
||||
sx={(theme) => ({
|
||||
color: theme.colors.gray[6],
|
||||
})}
|
||||
>
|
||||
{window.location.origin}/share/
|
||||
{form.values.link == "" ? "myAwesomeShare" : form.values.link}
|
||||
</Text>
|
||||
{mode == "email" && (
|
||||
<MultiSelect
|
||||
label="Email adresses"
|
||||
data={form.values.emails}
|
||||
placeholder="Email adresses"
|
||||
searchable
|
||||
creatable
|
||||
rightSection={<></>}
|
||||
getCreateLabel={(email) => `${email}`}
|
||||
onCreate={async (email) => {
|
||||
if (!(await shareService.doesUserExist(email))) {
|
||||
form.setFieldValue("emails", form.values.emails);
|
||||
toast.error(
|
||||
`${email} doesn't have an account at Pingvin Share.`
|
||||
);
|
||||
}
|
||||
}}
|
||||
{...form.getInputProps("emails")}
|
||||
/>
|
||||
)}
|
||||
<Select
|
||||
label="Expiration"
|
||||
{...form.getInputProps("expiration")}
|
||||
data={[
|
||||
{ value: "10", label: "10 Minutes" },
|
||||
{ value: "60", label: "1 Hour" },
|
||||
{ value: "1440", label: "1 Day" },
|
||||
{ value: "1080", label: "1 Week" },
|
||||
{ value: "43000", label: "1 Month" },
|
||||
]}
|
||||
/>
|
||||
<Accordion>
|
||||
<Accordion.Item
|
||||
label="Security options"
|
||||
sx={{ borderBottom: "none" }}
|
||||
>
|
||||
<Group direction="column" grow>
|
||||
{mode == "standard" && (
|
||||
<PasswordInput
|
||||
variant="filled"
|
||||
placeholder="No password"
|
||||
label="Password protection"
|
||||
{...form.getInputProps("password")}
|
||||
/>
|
||||
)}
|
||||
<NumberInput
|
||||
type="number"
|
||||
variant="filled"
|
||||
placeholder="No limit"
|
||||
label="Maximal views"
|
||||
{...form.getInputProps("maxVisitors")}
|
||||
/>
|
||||
</Group>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
<Button type="submit">Share</Button>
|
||||
</Group>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
export default CreateUploadModalBody;
|
||||
@@ -16,13 +16,21 @@ import toast from "../../utils/toast.util";
|
||||
const showCompletedUploadModal = (
|
||||
modals: ModalsContextProps,
|
||||
link: string,
|
||||
expiresAt: string
|
||||
expiresAt: string,
|
||||
mode: "email" | "standard"
|
||||
) => {
|
||||
return modals.openModal({
|
||||
closeOnClickOutside: false,
|
||||
withCloseButton: false,
|
||||
closeOnEscape: false,
|
||||
title: <Title order={4}>Share ready</Title>,
|
||||
title: (
|
||||
<Group grow direction="column" spacing={0}>
|
||||
<Title order={4}>Share ready</Title>
|
||||
{mode == "email" && (
|
||||
<Text size="sm"> Emails were sent to the to invited users.</Text>
|
||||
)}
|
||||
</Group>
|
||||
),
|
||||
children: <Body link={link} expiresAt={expiresAt} />,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,145 +1,22 @@
|
||||
import {
|
||||
Accordion,
|
||||
Button,
|
||||
Col,
|
||||
Grid,
|
||||
Group,
|
||||
NumberInput,
|
||||
PasswordInput,
|
||||
Select,
|
||||
Text,
|
||||
TextInput,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
import { useForm, yupResolver } from "@mantine/form";
|
||||
import { useModals } from "@mantine/modals";
|
||||
import { Title } from "@mantine/core";
|
||||
import { ModalsContextProps } from "@mantine/modals/lib/context";
|
||||
import * as yup from "yup";
|
||||
import shareService from "../../services/share.service";
|
||||
import CreateUploadModalBody from "../share/CreateUploadModalBody";
|
||||
|
||||
const showCreateUploadModal = (
|
||||
mode: "standard" | "email",
|
||||
modals: ModalsContextProps,
|
||||
uploadCallback: (
|
||||
id: string,
|
||||
expiration: number,
|
||||
security: { password?: string; maxVisitors?: number }
|
||||
security: { password?: string; maxVisitors?: number}, emails? : string[]
|
||||
) => void
|
||||
) => {
|
||||
return modals.openModal({
|
||||
title: <Title order={4}>Share</Title>,
|
||||
children: <Body uploadCallback={uploadCallback} />,
|
||||
children: (
|
||||
<CreateUploadModalBody mode={mode} uploadCallback={uploadCallback} />
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const Body = ({
|
||||
uploadCallback,
|
||||
}: {
|
||||
uploadCallback: (
|
||||
id: string,
|
||||
expiration: number,
|
||||
security: { password?: string; maxVisitors?: number }
|
||||
) => void;
|
||||
}) => {
|
||||
const modals = useModals();
|
||||
const validationSchema = yup.object().shape({
|
||||
link: yup.string().required().min(2).max(50),
|
||||
password: yup.string().min(3).max(100),
|
||||
maxVisitors: yup.number().min(1),
|
||||
});
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
link: "",
|
||||
password: undefined,
|
||||
maxVisitors: undefined,
|
||||
expiration: "1440",
|
||||
},
|
||||
schema: yupResolver(validationSchema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={form.onSubmit(async (values) => {
|
||||
if (await shareService.isIdAlreadyInUse(values.link)) {
|
||||
form.setFieldError("link", "Link already in use.");
|
||||
} else {
|
||||
modals.closeAll();
|
||||
uploadCallback(values.link, parseInt(values.expiration), {
|
||||
password: values.password,
|
||||
maxVisitors: values.maxVisitors,
|
||||
});
|
||||
}
|
||||
})}
|
||||
>
|
||||
<Group direction="column" grow>
|
||||
<Grid align={form.errors.link ? "center" : "flex-end"}>
|
||||
<Col xs={9}>
|
||||
<TextInput
|
||||
variant="filled"
|
||||
label="Link"
|
||||
placeholder="myAwesomeShare"
|
||||
{...form.getInputProps("link")}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={3}>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
form.setFieldValue(
|
||||
"link",
|
||||
Buffer.from(Math.random().toString(), "utf8")
|
||||
.toString("base64")
|
||||
.substr(10, 7)
|
||||
)
|
||||
}
|
||||
>
|
||||
Generate
|
||||
</Button>
|
||||
</Col>
|
||||
</Grid>
|
||||
|
||||
<Text
|
||||
size="xs"
|
||||
sx={(theme) => ({
|
||||
color: theme.colors.gray[6],
|
||||
})}
|
||||
>
|
||||
{window.location.origin}/share/
|
||||
{form.values.link == "" ? "myAwesomeShare" : form.values.link}
|
||||
</Text>
|
||||
<Select
|
||||
label="Expiration"
|
||||
{...form.getInputProps("expiration")}
|
||||
data={[
|
||||
{ value: "10", label: "10 Minutes" },
|
||||
{ value: "60", label: "1 Hour" },
|
||||
{ value: "1440", label: "1 Day" },
|
||||
{ value: "1080", label: "1 Week" },
|
||||
{ value: "43000", label: "1 Month" },
|
||||
]}
|
||||
/>
|
||||
<Accordion>
|
||||
<Accordion.Item label="Security" sx={{ borderBottom: "none" }}>
|
||||
<Group direction="column" grow>
|
||||
<PasswordInput
|
||||
variant="filled"
|
||||
placeholder="No password"
|
||||
label="Password protection"
|
||||
{...form.getInputProps("password")}
|
||||
/>
|
||||
<NumberInput
|
||||
type="number"
|
||||
variant="filled"
|
||||
placeholder="No limit"
|
||||
label="Maximal views"
|
||||
{...form.getInputProps("maxVisitors")}
|
||||
/>
|
||||
</Group>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
<Button type="submit">Share</Button>
|
||||
</Group>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
export default showCreateUploadModal;
|
||||
export default showCreateUploadModal;
|
||||
@@ -3,14 +3,30 @@ import { ShareDocument } from "../../../../types/Appwrite.type";
|
||||
import { AppwriteFileWithPreview } from "../../../../types/File.type";
|
||||
import awServer from "../../../../utils/appwriteServer.util";
|
||||
import { checkSecurity } from "../../../../utils/shares/security.util";
|
||||
import * as jose from "jose";
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const shareId = req.query.shareId as string;
|
||||
const fileList: AppwriteFileWithPreview[] = [];
|
||||
const hashedPassword = req.cookies[`${shareId}-password`];
|
||||
|
||||
if (!(await shareExists(shareId)))
|
||||
let shareDocument;
|
||||
try {
|
||||
shareDocument = await awServer.database.getDocument<ShareDocument>(
|
||||
"shares",
|
||||
shareId
|
||||
);
|
||||
} catch {
|
||||
return res.status(404).json({ message: "not_found" });
|
||||
}
|
||||
|
||||
if (!shareExists(shareDocument)) {
|
||||
return res.status(404).json({ message: "not_found" });
|
||||
}
|
||||
|
||||
if (!hasUserAccess(req.cookies.aw_token, shareDocument)) {
|
||||
return res.status(403).json({ message: "forbidden" });
|
||||
}
|
||||
|
||||
try {
|
||||
await checkSecurity(shareId, hashedPassword);
|
||||
@@ -20,8 +36,9 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
|
||||
addVisitorCount(shareId);
|
||||
|
||||
const fileListWithoutPreview = (await awServer.storage.listFiles(shareId, undefined, 100))
|
||||
.files;
|
||||
const fileListWithoutPreview = (
|
||||
await awServer.storage.listFiles(shareId, undefined, 100)
|
||||
).files;
|
||||
|
||||
for (const file of fileListWithoutPreview) {
|
||||
const filePreview = await awServer.storage.getFilePreview(
|
||||
@@ -39,18 +56,20 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
res.status(200).json(fileList);
|
||||
};
|
||||
|
||||
const shareExists = async (shareId: string) => {
|
||||
const hasUserAccess = (jwt: string, shareDocument: ShareDocument) => {
|
||||
if (shareDocument.users?.length == 0) return true;
|
||||
try {
|
||||
const shareDocument = await awServer.database.getDocument<ShareDocument>(
|
||||
"shares",
|
||||
shareId
|
||||
);
|
||||
return shareDocument.enabled && shareDocument.expiresAt > Date.now();
|
||||
} catch (e) {
|
||||
const userId = jose.decodeJwt(jwt).userId as string;
|
||||
return shareDocument.users?.includes(userId);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const shareExists = async (shareDocument: ShareDocument) => {
|
||||
return shareDocument.enabled && shareDocument.expiresAt > Date.now();
|
||||
};
|
||||
|
||||
const addVisitorCount = async (shareId: string) => {
|
||||
const currentDocument = await awServer.database.getDocument<ShareDocument>(
|
||||
"shares",
|
||||
|
||||
12
src/pages/api/user/exists/[email].ts
Normal file
12
src/pages/api/user/exists/[email].ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import awServer from "../../../../utils/appwriteServer.util";
|
||||
|
||||
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const email = req.query.email as string;
|
||||
|
||||
const doesExists = (await awServer.user.list(`"${email}"`)).total != 0;
|
||||
|
||||
res.status(200).json({ exists: doesExists });
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -8,6 +8,7 @@ import FileList from "../../components/share/FileList";
|
||||
import showEnterPasswordModal from "../../components/share/showEnterPasswordModal";
|
||||
import showShareNotFoundModal from "../../components/share/showShareNotFoundModal";
|
||||
import showVisitorLimitExceededModal from "../../components/share/showVisitorLimitExceededModal";
|
||||
import authService from "../../services/auth.service";
|
||||
import shareService from "../../services/share.service";
|
||||
import { AppwriteFileWithPreview } from "../../types/File.type";
|
||||
|
||||
@@ -24,7 +25,13 @@ const Share = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const getFiles = (password?: string) =>
|
||||
const getFiles = async (password?: string) => {
|
||||
try {
|
||||
await authService.createJWT();
|
||||
} catch {
|
||||
//
|
||||
}
|
||||
|
||||
shareService
|
||||
.get(shareId, password)
|
||||
.then((files) => {
|
||||
@@ -40,6 +47,7 @@ const Share = () => {
|
||||
showVisitorLimitExceededModal(modals);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getFiles();
|
||||
@@ -47,7 +55,10 @@ const Share = () => {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Meta title={`Share ${shareId}`} />
|
||||
<Meta
|
||||
title={`Share ${shareId}`}
|
||||
description="Look what I've shared with you."
|
||||
/>
|
||||
<Group position="right">
|
||||
<DownloadAllButton
|
||||
shareId={shareId}
|
||||
|
||||
@@ -11,31 +11,34 @@ import showCreateUploadModal from "../components/upload/showCreateUploadModal";
|
||||
import { FileUpload } from "../types/File.type";
|
||||
import aw from "../utils/appwrite.util";
|
||||
import { IsSignedInContext } from "../utils/auth.util";
|
||||
import { useConfig } from "../utils/config.util";
|
||||
import toast from "../utils/toast.util";
|
||||
|
||||
const Upload = () => {
|
||||
const router = useRouter();
|
||||
const modals = useModals();
|
||||
const config = useConfig();
|
||||
const isSignedIn = useContext(IsSignedInContext);
|
||||
const [files, setFiles] = useState<FileUpload[]>([]);
|
||||
const [isUploading, setisUploading] = useState(false);
|
||||
let shareMode: "email" | "standard";
|
||||
|
||||
const uploadFiles = async (
|
||||
id: string,
|
||||
expiration: number,
|
||||
security: { password?: string; maxVisitors?: number }
|
||||
security: { password?: string; maxVisitors?: number },
|
||||
emails?: string[]
|
||||
) => {
|
||||
setisUploading(true);
|
||||
try {
|
||||
files.forEach((file) => {
|
||||
file.uploadingState = "inProgress";
|
||||
});
|
||||
|
||||
const bucketId = JSON.parse(
|
||||
(
|
||||
await aw.functions.createExecution(
|
||||
"createShare",
|
||||
JSON.stringify({ id, security, expiration }),
|
||||
JSON.stringify({ id, security, expiration, emails }),
|
||||
false
|
||||
)
|
||||
).stdout
|
||||
@@ -56,7 +59,8 @@ const Upload = () => {
|
||||
showCompletedUploadModal(
|
||||
modals,
|
||||
`${window.location.origin}/share/${bucketId}`,
|
||||
new Date(Date.now() + expiration * 60 * 1000).toLocaleString()
|
||||
new Date(Date.now() + expiration * 60 * 1000).toLocaleString(),
|
||||
shareMode
|
||||
);
|
||||
setFiles([]);
|
||||
}
|
||||
@@ -96,11 +100,21 @@ const Upload = () => {
|
||||
>
|
||||
<Menu.Item
|
||||
icon={<Link size={16} />}
|
||||
onClick={() => showCreateUploadModal(modals, uploadFiles)}
|
||||
onClick={() => {
|
||||
shareMode = "standard";
|
||||
showCreateUploadModal(shareMode, modals, uploadFiles);
|
||||
}}
|
||||
>
|
||||
Share with link
|
||||
</Menu.Item>
|
||||
<Menu.Item disabled icon={<Mail size={16} />}>
|
||||
<Menu.Item
|
||||
disabled={!config.MAIL_SHARE_ENABLED}
|
||||
icon={<Mail size={16} />}
|
||||
onClick={() => {
|
||||
shareMode = "email";
|
||||
showCreateUploadModal(shareMode, modals, uploadFiles);
|
||||
}}
|
||||
>
|
||||
Share with email
|
||||
</Menu.Item>
|
||||
</Menu>
|
||||
|
||||
8
src/services/auth.service.ts
Normal file
8
src/services/auth.service.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import aw from "../utils/appwrite.util";
|
||||
|
||||
const createJWT = async () => {
|
||||
const jwt = (await aw.account.createJWT()).jwt;
|
||||
document.cookie = `aw_token=${jwt}; Max-Age=900; Path=/api`;
|
||||
};
|
||||
|
||||
export default { createJWT };
|
||||
@@ -10,9 +10,18 @@ const isIdAlreadyInUse = async (shareId: string) => {
|
||||
.exists as boolean;
|
||||
};
|
||||
|
||||
const doesUserExist = async (email: string) => {
|
||||
return (await axios.get(`/api/user/exists/${email}`)).data.exists as boolean;
|
||||
};
|
||||
|
||||
const authenticateWithPassword = async (shareId: string, password?: string) => {
|
||||
return (await axios.post(`/api/share/${shareId}/enterPassword`, { password }))
|
||||
.data as AppwriteFileWithPreview[];
|
||||
};
|
||||
|
||||
export default { get, authenticateWithPassword, isIdAlreadyInUse };
|
||||
export default {
|
||||
get,
|
||||
authenticateWithPassword,
|
||||
isIdAlreadyInUse,
|
||||
doesUserExist,
|
||||
};
|
||||
|
||||
@@ -6,10 +6,10 @@ export type ShareDocument = {
|
||||
expiresAt: number;
|
||||
visitorCount: number;
|
||||
enabled: boolean;
|
||||
users?: string[];
|
||||
} & Models.Document;
|
||||
|
||||
|
||||
export type SecurityDocument = {
|
||||
password: string;
|
||||
maxVisitors: number;
|
||||
} & Models.Document;
|
||||
password: string;
|
||||
maxVisitors: number;
|
||||
} & Models.Document;
|
||||
|
||||
@@ -7,6 +7,7 @@ const error = (message: string) =>
|
||||
color: "red",
|
||||
radius: "md",
|
||||
title: "Error",
|
||||
|
||||
message: message,
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user