Skip to content

Per 10009 add get folder share links #193

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion packages/api/src/folder/controller/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ import {
extractUserEmailFromAuthToken,
verifyUserAuthentication,
} from "../../middleware";
import { patchFolder, getFolders, getFolderChildren } from "../service";
import {
patchFolder,
getFolders,
getFolderChildren,
getFolderShareLinks,
} from "../service";
import {
validatePatchFolderRequest,
validateFolderRequest,
Expand All @@ -19,6 +24,7 @@ import { isValidationError } from "../../validators/validator_util";
import {
validateOptionalAuthenticationValues,
validatePaginationParameters,
validateBodyFromAuthentication,
} from "../../validators/shared";

export const folderController = Router();
Expand Down Expand Up @@ -99,3 +105,25 @@ folderController.get(
}
}
);

folderController.get(
"/:folderId/share_links",
verifyUserAuthentication,
async (req: Request, res: Response, next: NextFunction) => {
try {
validateFolderRequest(req.params);
validateBodyFromAuthentication(req.body);
const shareLinks = await getFolderShareLinks(
req.body.emailFromAuthToken,
req.params.folderId
);
res.status(200).send({ items: shareLinks });
} catch (err) {
if (isValidationError(err)) {
res.status(400).json({ error: err.message });
return;
}
next(err);
}
}
);
2 changes: 1 addition & 1 deletion packages/api/src/folder/controller/get_folder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jest.mock("../../database");
jest.mock("../../middleware");
jest.mock("@stela/logger");

describe("GET /folder/{id}", () => {
describe("GET /folder", () => {
const agent = request(app);

beforeEach(async () => {
Expand Down
128 changes: 128 additions & 0 deletions packages/api/src/folder/controller/get_folder_share_links.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import type { NextFunction, Request } from "express";
import request from "supertest";
import { logger } from "@stela/logger";
import createError from "http-errors";
import { app } from "../../app";
import { db } from "../../database";
import { verifyUserAuthentication } from "../../middleware";
import type { ShareLink } from "../../share_link/models";
import { loadFixtures, clearDatabase } from "./utils_test";

jest.mock("../../database");
jest.mock("../../middleware");
jest.mock("@stela/logger");

describe("GET /folder/{id}/share_links", () => {
const agent = request(app);

beforeEach(async () => {
(verifyUserAuthentication as jest.Mock).mockImplementation(
async (
req: Request<
unknown,
unknown,
{ userSubjectFromAuthToken?: string; emailFromAuthToken?: string }
>,
__,
next: NextFunction
) => {
req.body.emailFromAuthToken = "[email protected]";
req.body.userSubjectFromAuthToken =
"b5461dc2-1eb0-450e-b710-fef7b2cafe1e";

next();
}
);
await clearDatabase();
await loadFixtures();
});

afterEach(async () => {
await clearDatabase();
jest.restoreAllMocks();
jest.clearAllMocks();
});

test("expect to return share links for a folder", async () => {
const response = await agent
.get("/api/v2/folder/2/share_links")
.expect(200);

const shareLinks = (response.body as { items: ShareLink[] }).items;
expect(shareLinks.length).toEqual(3);

const shareLink = shareLinks.find((link) => link.id === "1");
expect(shareLink?.id).toEqual("1");
expect(shareLink?.itemId).toEqual("2");
expect(shareLink?.itemType).toEqual("folder");
expect(shareLink?.token).toEqual("c0f523e4-48d8-4c39-8cda-5e95161532e4");
expect(shareLink?.permissionsLevel).toEqual("viewer");
expect(shareLink?.accessRestrictions).toEqual("none");
expect(shareLink?.maxUses).toEqual(null);
expect(shareLink?.usesExpended).toEqual(null);
expect(shareLink?.expirationTimestamp).toEqual(null);
});

test("expect an empty list if folder doesn't exist", async () => {
const response = await agent
.get("/api/v2/folder/999/share_links")
.expect(200);

const shareLinks = (response.body as { items: ShareLink[] }).items;
expect(shareLinks.length).toEqual(0);
});

test("expect empty list if user doesn't have access to the folder's share links", async () => {
(verifyUserAuthentication as jest.Mock).mockImplementation(
async (
req: Request<
unknown,
unknown,
{ userSubjectFromAuthToken?: string; emailFromAuthToken?: string }
>,
__,
next: NextFunction
) => {
req.body.emailFromAuthToken = "[email protected]";
req.body.userSubjectFromAuthToken =
"b5461dc2-1eb0-450e-b710-fef7b2cafe1e";

next();
}
);
const response = await agent
.get("/api/v2/folder/2/share_links")
.expect(200);

const shareLinks = (response.body as { items: ShareLink[] }).items;
expect(shareLinks.length).toEqual(0);
});

test("expect to log error and return 500 if database lookup fails", async () => {
const testError = new Error("test error");
jest.spyOn(db, "sql").mockImplementation(async () => {
throw testError;
});

await agent.get("/api/v2/folder/1/share_links").expect(500);
expect(logger.error).toHaveBeenCalledWith(testError);
});

test("expect 401 if not authenticated", async () => {
(verifyUserAuthentication as jest.Mock).mockImplementation(
(_, __, next: NextFunction) => {
next(createError.Unauthorized("Invalid auth token"));
}
);
await agent.get("/api/v2/folder/1/share_links").expect(401);
});

test("expect 400 if the header values are missing", async () => {
(verifyUserAuthentication as jest.Mock).mockImplementation(
(_, __, next: NextFunction) => {
next();
}
);
await agent.get("/api/v2/folder/1/share_links").expect(400);
});
});
20 changes: 15 additions & 5 deletions packages/api/src/folder/fixtures/create_test_shareby_urls.sql
Original file line number Diff line number Diff line change
@@ -1,46 +1,56 @@
INSERT INTO
shareby_url (
shareby_urlid,
folder_linkid,
urltoken,
shareurl,
byaccountid,
byarchiveid,
unrestricted,
expiresdt
expiresdt,
defaultaccessrole
)
VALUES (
1,
1,
'c0f523e4-48d8-4c39-8cda-5e95161532e4',
'https://local.permanent.org/share/c0f523e4-48d8-4c39-8cda-5e95161532e4',
2,
1,
true,
null
null,
'role.access.viewer'
),
(
2,
1,
'7d6412af-5abe-4acb-808a-64e9ce3b7535',
'https://local.permanent.org/share/7d6412af-5abe-4acb-808a-64e9ce3b7535',
2,
1,
false,
null
null,
'role.access.viewer'
),
(
3,
1,
'9cc057f0-d3e8-41df-94d6-9b315b4921af',
'https://local.permanent.org/share/9cc057f0-d3e8-41df-94d6-9b315b4921af',
2,
1,
true,
'2020-01-01'
'2020-01-01',
'role.access.viewer'
),
(
4,
3,
'56f7c246-e4ec-41f3-b117-6df4c9377075',
'https://local.permanent.org/share/56f7c246-e4ec-41f3-b117-6df4c9377075',
2,
1,
true,
null
null,
'role.access.viewer'
);
10 changes: 10 additions & 0 deletions packages/api/src/folder/queries/get_folder_share_links.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
SELECT shareby_url.shareby_urlid AS "id"
FROM
shareby_url
INNER JOIN
account ON shareby_url.byaccountid = account.accountid
INNER JOIN
folder_link ON shareby_url.folder_linkid = folder_link.folder_linkid
WHERE
folder_link.folderid = :folderId
AND account.primaryemail = :email;
27 changes: 27 additions & 0 deletions packages/api/src/folder/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { requestFieldsToDatabaseFields } from "./helper";
import { getFolderAccessRole, accessRoleLessThan } from "../access/permission";
import { AccessRole } from "../access/models";
import { getRecordById } from "../record/service";
import { shareLinkService } from "../share_link/service";
import type { ShareLink } from "../share_link/models";

export const prettifyFolderSortType = (
sortType: FolderSortOrder
Expand Down Expand Up @@ -253,3 +255,28 @@ export const patchFolder = async (
}
return result.rows[0].folderId;
};

export const getFolderShareLinks = async (
email: string,
folderId: string
): Promise<ShareLink[]> => {
const folderShareLinkIds = await db
.sql<{ id: string }>("folder.queries.get_folder_share_links", {
email,
folderId,
})
.catch((err) => {
logger.error(err);
throw new createError.InternalServerError(
"Failed to get folder share links"
);
});

const shareLinkIds = folderShareLinkIds.rows.map((row) => row.id);
const shareLinks = await shareLinkService.getShareLinks(
email,
[],
shareLinkIds
);
return shareLinks;
};
2 changes: 1 addition & 1 deletion packages/api/src/record/controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,7 @@ describe("PATCH /record", () => {
});
});

describe("GET /record/{id}/share_links", () => {
describe("GET /record/{id}/share-links", () => {
const agent = request(app);

beforeEach(async () => {
Expand Down