Files
swiss-datashare/src/pages/api/share/[shareId]/index.ts

84 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-04-25 15:15:17 +02:00
import type { NextApiRequest, NextApiResponse } from "next";
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";
2022-05-06 10:25:10 +02:00
import * as jose from "jose";
2022-04-25 15:15:17 +02:00
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const shareId = req.query.shareId as string;
const fileList: AppwriteFileWithPreview[] = [];
const hashedPassword = req.cookies[`${shareId}-password`];
2022-05-06 10:25:10 +02:00
let shareDocument;
try {
shareDocument = await awServer.database.getDocument<ShareDocument>(
"shares",
shareId
);
} catch {
2022-04-25 15:15:17 +02:00
return res.status(404).json({ message: "not_found" });
2022-05-06 10:25:10 +02:00
}
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" });
}
2022-04-25 15:15:17 +02:00
try {
await checkSecurity(shareId, hashedPassword);
} catch (e) {
return res.status(403).json({ message: e });
}
addVisitorCount(shareId);
2022-05-06 10:25:10 +02:00
const fileListWithoutPreview = (
await awServer.storage.listFiles(shareId, undefined, 100)
).files;
2022-04-25 15:15:17 +02:00
for (const file of fileListWithoutPreview) {
const filePreview = await awServer.storage.getFilePreview(
shareId,
file.$id
);
fileList.push({ ...file, preview: filePreview });
}
if (hashedPassword)
res.setHeader(
"Set-Cookie",
`${shareId}-password=${hashedPassword}; Path=/share/${shareId}; max-age=3600; HttpOnly`
);
res.status(200).json(fileList);
};
2022-05-06 10:25:10 +02:00
const hasUserAccess = (jwt: string, shareDocument: ShareDocument) => {
if (shareDocument.users?.length == 0) return true;
2022-04-25 15:15:17 +02:00
try {
2022-05-06 10:25:10 +02:00
const userId = jose.decodeJwt(jwt).userId as string;
return shareDocument.users?.includes(userId);
} catch {
2022-04-25 15:15:17 +02:00
return false;
}
};
2022-05-06 10:25:10 +02:00
const shareExists = async (shareDocument: ShareDocument) => {
return shareDocument.enabled && shareDocument.expiresAt > Date.now();
};
2022-04-25 15:15:17 +02:00
const addVisitorCount = async (shareId: string) => {
const currentDocument = await awServer.database.getDocument<ShareDocument>(
"shares",
shareId
);
currentDocument.visitorCount++;
awServer.database.updateDocument("shares", shareId, currentDocument);
};
export default handler;