Skip to content
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
2 changes: 1 addition & 1 deletion apps/docs-new/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"fumadocs-openapi": "^10.4.1",
"fumadocs-ui": "16.7.1",
"lucide-react": "^0.553.0",
"next": "^16.0.10",
"next": "^16.4.5",
"react": "19.2.0",
"react-dom": "19.2.0",
"shiki": "^4.0.2"
Expand Down
2 changes: 1 addition & 1 deletion apps/web/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,4 @@
# CACHE_DIR=/tmp

# If using standalone Mongo (no replica set)
# DB_TRANSACTION=false
# DB_TRANSACTIONS=false
21 changes: 18 additions & 3 deletions apps/web/app/api/download/[token]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,13 @@ export async function GET(
const zipFileAddress = await createArchive({
targetDirectory,
filesDirectory,
archiveName: course.title,
archiveName: "course",
});

const zipStream = createReadStream(zipFileAddress);
const headers = new Headers({
"Content-Type": "application/zip",
"Content-Disposition": `attachment; filename=${course.title}.zip`,
"Content-Disposition": getContentDisposition(course.title),
});

const webStream = new ReadableStream({
Expand Down Expand Up @@ -161,6 +161,17 @@ function createFolder(folderPath: string) {
}
}

function getContentDisposition(title: string) {
const fileName = `${title}.zip`;
const asciiFileName =
fileName.replace(/[^\x20-\x7e]|["\\/;]/g, "_").trim() || "course.zip";
const encodedFileName = encodeURIComponent(fileName).replace(
/['()*]/g,
(char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
);
return `attachment; filename="${asciiFileName}"; filename*=UTF-8''${encodedFileName}`;
}

function isDownloadableMedia(media: Media | Partial<Media>): media is Media {
return (
typeof media.mediaId === "string" &&
Expand All @@ -170,7 +181,11 @@ function isDownloadableMedia(media: Media | Partial<Media>): media is Media {
}

async function downloadFile(media: Media, folderPath: string) {
const filePath = path.join(folderPath, media.originalFileName);
const fileName = path.basename(media.originalFileName);
if (!fileName || fileName === "." || fileName === "..") {
throw new Error("Invalid file name");
}
const filePath = path.join(folderPath, fileName);

try {
const response: any = await fetch(media.file!);
Expand Down
125 changes: 125 additions & 0 deletions apps/web/app/api/lessons/[id]/scorm/upload/__tests__/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/**
* @jest-environment node
*/

import { NextRequest } from "next/server";
import DomainModel from "@models/Domain";
import User from "@models/User";
import Lesson from "@models/Lesson";
import CourseModel from "@models/Course";
import { auth } from "@/auth";
import { Constants, UIConstants } from "@courselit/common-models";

jest.mock("@models/Domain");
jest.mock("@models/User");
jest.mock("@models/Lesson");
jest.mock("@models/Course");
jest.mock("@config/constants", () => ({
__esModule: true,
default: { cacheEnabled: true },
}));
jest.mock("@/lib/scorm/extractor", () => ({
extractScormPackage: jest.fn(),
}));
jest.mock("medialit", () => ({
MediaLit: jest.fn(),
}));
jest.mock("@/auth", () => ({
auth: {
api: {
getSession: jest.fn(),
},
},
}));

const { permissions } = UIConstants;

const domain = { _id: "domain-id", name: "school" };

function request() {
return {
headers: {
get: jest.fn((name: string) =>
name === "domain" ? "school" : null,
),
},
json: jest.fn().mockResolvedValue({}),
} as unknown as NextRequest;
}

async function callUpload(req: NextRequest) {
const { POST } = await import("../route");
return POST(req, { params: Promise.resolve({ id: "lesson-1" }) });
}

function mockCourseCreator(creatorId: string) {
(CourseModel.findOne as jest.Mock).mockReturnValue({
select: jest.fn().mockResolvedValue({ creatorId }),
});
}

describe("POST /api/lessons/[id]/scorm/upload", () => {
beforeEach(() => {
jest.clearAllMocks();
(DomainModel.findOne as jest.Mock).mockResolvedValue(domain);
(auth.api.getSession as unknown as jest.Mock).mockResolvedValue({
user: { email: "creator@example.com" },
});
(User.findOne as jest.Mock).mockResolvedValue({
_id: "creator-object-id",
userId: "creator",
email: "creator@example.com",
permissions: [permissions.manageCourse],
});
(Lesson.findOne as jest.Mock).mockResolvedValue({
lessonId: "lesson-1",
courseId: "course-1",
type: Constants.LessonType.SCORM,
content: { mediaId: "victim-package" },
});
});

it("rejects creators uploading to another creator's lesson", async () => {
mockCourseCreator("someone-else");
const req = request();

const response = await callUpload(req);

expect(response.status).toBe(403);
expect(CourseModel.findOne).toHaveBeenCalledWith({
courseId: "course-1",
domain: domain._id,
});
expect(req.json).not.toHaveBeenCalled();
expect(Lesson.updateOne).not.toHaveBeenCalled();
});

it("lets creators upload to lessons in their own course", async () => {
mockCourseCreator("creator");
const req = request();

const response = await callUpload(req);

// Passes the ownership check and reaches body validation
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({
message: "mediaId is required",
});
});

it("lets users with manage any course permission upload to any lesson", async () => {
(User.findOne as jest.Mock).mockResolvedValue({
_id: "admin-object-id",
userId: "admin",
email: "creator@example.com",
permissions: [permissions.manageAnyCourse],
});
mockCourseCreator("someone-else");
const req = request();

const response = await callUpload(req);

expect(response.status).toBe(400);
expect(req.json).toHaveBeenCalled();
});
});
17 changes: 17 additions & 0 deletions apps/web/app/api/lessons/[id]/scorm/upload/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { UIConstants as constants, Constants } from "@courselit/common-models";
import DomainModel, { Domain } from "@models/Domain";
import User from "@models/User";
import Lesson from "@models/Lesson";
import CourseModel from "@models/Course";
import GQLContext from "@models/GQLContext";
import { canManageCourseInContext } from "@/graphql/courses/permissions";
import { extractScormPackage } from "@/lib/scorm/extractor";
import { MediaLit } from "medialit";
import { error as logError } from "@/services/logger";
Expand Down Expand Up @@ -78,6 +81,20 @@ export async function POST(
return Response.json({ message: "Lesson not found" }, { status: 404 });
}

const course = await CourseModel.findOne({
courseId: lesson.courseId,
domain: domain._id,
}).select("creatorId");
if (
!course ||
!canManageCourseInContext(course, {
user,
subdomain: domain,
} as unknown as GQLContext)
) {
return Response.json({ message: "Forbidden" }, { status: 403 });
}

// Check if lesson type is SCORM
if (lesson.type !== Constants.LessonType.SCORM) {
return Response.json(
Expand Down
168 changes: 168 additions & 0 deletions apps/web/app/api/media/[mediaId]/[type]/__tests__/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/**
* @jest-environment node
*/

import { NextRequest } from "next/server";
import DomainModel from "@models/Domain";
import UserModel from "@models/User";
import CommunityModel from "@models/Community";
import { auth } from "@/auth";
import * as medialitService from "@/services/medialit";
import { UIConstants } from "@courselit/common-models";

jest.mock("@models/Domain");
jest.mock("@models/User");
jest.mock("@models/Community");
jest.mock("@models/Course");
jest.mock("@models/Lesson");
jest.mock("@models/Page");
jest.mock("@models/CertificateTemplate");
jest.mock("@/services/medialit", () => ({
deleteMedia: jest.fn(),
}));
jest.mock("@/auth", () => ({
auth: {
api: {
getSession: jest.fn(),
},
},
}));

const { permissions } = UIConstants;

const domain = {
_id: "domain-id",
name: "school",
settings: {
logo: { mediaId: "school-logo" },
},
};

function request() {
return {
headers: {
get: jest.fn((name: string) =>
name === "domain" ? "school" : null,
),
},
} as unknown as NextRequest;
}

async function callDelete(mediaId: string, type: string) {
const { DELETE } = await import("../route");
return DELETE(request(), {
params: Promise.resolve({ mediaId, type }),
});
}

function signInAs(user: Record<string, unknown>) {
(auth.api.getSession as unknown as jest.Mock).mockResolvedValue({
user: { email: "admin@example.com" },
});
(UserModel.findOne as jest.Mock).mockResolvedValue({
userId: "admin",
email: "admin@example.com",
...user,
});
}

describe("DELETE /api/media/[mediaId]/[type]", () => {
beforeEach(() => {
jest.clearAllMocks();
(DomainModel.findOne as jest.Mock).mockResolvedValue(domain);
(medialitService.deleteMedia as jest.Mock).mockResolvedValue(true);
});

describe("domain media", () => {
const settingsAdmin = {
permissions: [permissions.manageMedia, permissions.manageSettings],
};

it("deletes the current school's logo", async () => {
signInAs(settingsAdmin);

const response = await callDelete("school-logo", "domain");

expect(response.status).toBe(200);
expect(medialitService.deleteMedia).toHaveBeenCalledWith(
"school-logo",
);
});

it("refuses to delete media that is not the current school's logo", async () => {
signInAs(settingsAdmin);

const response = await callDelete("other-school-logo", "domain");

expect(response.status).toBe(403);
expect(medialitService.deleteMedia).not.toHaveBeenCalled();
});
});

describe("community media", () => {
const communityAdmin = {
permissions: [permissions.manageMedia, permissions.manageCommunity],
};

it("deletes a featured image of a community in the current school", async () => {
signInAs(communityAdmin);
(CommunityModel.exists as jest.Mock).mockResolvedValue({
_id: "community",
});

const response = await callDelete("community-image", "community");

expect(response.status).toBe(200);
expect(CommunityModel.exists).toHaveBeenCalledWith({
domain: domain._id,
"featuredImage.mediaId": "community-image",
});
expect(medialitService.deleteMedia).toHaveBeenCalledWith(
"community-image",
);
});

it("refuses to delete media not used by a community in the current school", async () => {
signInAs(communityAdmin);
(CommunityModel.exists as jest.Mock).mockResolvedValue(null);

const response = await callDelete("foreign-image", "community");

expect(response.status).toBe(403);
expect(medialitService.deleteMedia).not.toHaveBeenCalled();
});
});

describe("user media", () => {
it("lets users delete their own avatar", async () => {
signInAs({
permissions: [permissions.manageMedia],
avatar: { mediaId: "my-avatar" },
});

const response = await callDelete("my-avatar", "user");

expect(response.status).toBe(200);
expect(UserModel.exists).not.toHaveBeenCalled();
expect(medialitService.deleteMedia).toHaveBeenCalledWith(
"my-avatar",
);
});

it("refuses to delete an avatar that does not belong to a user in the current school", async () => {
signInAs({
permissions: [permissions.manageMedia, permissions.manageUsers],
});
(UserModel.exists as jest.Mock).mockResolvedValue(null);

const response = await callDelete("foreign-avatar", "user");

expect(response.status).toBe(403);
expect(UserModel.exists).toHaveBeenCalledWith({
domain: domain._id,
"avatar.mediaId": "foreign-avatar",
});
expect(medialitService.deleteMedia).not.toHaveBeenCalled();
});
});
});
Loading
Loading