feat: move community supabase request to api layer (#612)

* feat: move community supabase request to api layer

* chore: pr review checkpoint

* chore: PR fixes

* feat: implement role-based authorization middleware and align the community features with the developer guide.

- Added role-based authorization middleware for organization and course membership checks, including `orgMemberMiddleware`, `orgTeamMemberMiddleware`, and `courseMemberMiddleware`.
- Introduced route-specific middleware for comment and question authorization, ensuring only authors or team members can modify content.
- Updated community routes to utilize the new middleware for enhanced security and access control.
- Refactored community services to streamline upvote functionality and improve error handling.
- Enhanced UI components for community interactions, including new comment and question pages, and improved state management for user actions.
- Updated documentation to reflect new middleware usage and best practices for authorization in the API layer.

* feat: enhance course and organization routes with middleware for improved access control

- Added `courseMemberMiddleware` to course download and clone routes to enforce membership checks.
- Updated lesson route to include `courseMemberMiddleware` for PDF downloads.
- Integrated `orgMemberMiddleware` into organization routes for team and audience access, ensuring only authorized members can retrieve data.
- Refactored lesson and organization routes for consistency and clarity in middleware usage.

* chore: streamline dashboard and API development scripts in package.json

- Consolidated dashboard and API development commands to include all relevant filters in a single line for improved clarity and ease of use.
- Removed redundant full command variants to simplify the script section.

---------

Co-authored-by: Rotimi Best <[email protected]>
This commit is contained in:
Adeyemi Adetunji
2025-12-22 19:57:27 +01:00
committed by GitHub
co-authored by Rotimi Best
parent 9fb6c7cbaa
commit bc9e3b41ae
41 changed files with 2699 additions and 1598 deletions
@@ -0,0 +1,254 @@
import { TCommunityAnswer, TCommunityQuestion, TNewCommunityQuestion } from '@db/types';
import {
communityAnswer,
communityQuestion,
course,
db,
desc,
eq,
inArray,
organization,
profile,
sql
} from '@db/drizzle';
export async function getCommunityQuestions(courseIdsFilter: string[]) {
const commentsCount = sql<number>`COUNT(${communityAnswer.id})`;
return db
.select({
organizationId: communityQuestion.organizationId,
courseId: communityQuestion.courseId,
title: communityQuestion.title,
votes: communityQuestion.votes,
createdAt: communityQuestion.createdAt,
slug: communityQuestion.slug,
comments: commentsCount,
authorFullname: profile.fullname,
courseTitle: course.title
})
.from(communityQuestion)
.innerJoin(course, eq(communityQuestion.courseId, course.id))
.leftJoin(communityAnswer, eq(communityAnswer.questionId, communityQuestion.id))
.leftJoin(profile, eq(profile.id, communityQuestion.authorProfileId))
.where(inArray(communityQuestion.courseId, courseIdsFilter))
.groupBy(
communityQuestion.organizationId,
communityQuestion.courseId,
communityQuestion.title,
communityQuestion.votes,
communityQuestion.createdAt,
communityQuestion.slug,
profile.fullname,
course.title
)
.orderBy(desc(communityQuestion.createdAt));
}
export async function getCommunityQuestion(slug: string) {
const questionRows = await db
.select({
id: communityQuestion.id,
title: communityQuestion.title,
body: communityQuestion.body,
votes: communityQuestion.votes,
createdAt: communityQuestion.createdAt,
courseId: communityQuestion.courseId,
slug: communityQuestion.slug,
authorId: profile.id,
authorName: profile.fullname,
authorAvatar: profile.avatarUrl,
courseTitle: course.title,
organizationId: communityQuestion.organizationId
})
.from(communityQuestion)
.innerJoin(course, eq(course.id, communityQuestion.courseId))
.leftJoin(profile, eq(profile.id, communityQuestion.authorProfileId))
.where(eq(communityQuestion.slug, slug))
.limit(1);
if (questionRows.length === 0) return null;
const q = questionRows[0];
const commentsRows = await db
.select({
id: communityAnswer.id,
body: communityAnswer.body,
votes: communityAnswer.votes,
createdAt: communityAnswer.createdAt,
authorId: profile.id,
authorName: profile.fullname,
authorAvatar: profile.avatarUrl
})
.from(communityAnswer)
.leftJoin(profile, eq(profile.id, communityAnswer.authorProfileId))
.where(eq(communityAnswer.questionId, q.id))
.orderBy(communityAnswer.createdAt);
return {
id: q.id,
title: q.title,
body: q.body,
votes: q.votes,
createdAt: q.createdAt,
courseId: q.courseId,
slug: q.slug,
organizationId: q.organizationId,
author: {
id: q.authorId,
fullname: q.authorName,
avatarUrl: q.authorAvatar
},
course: {
title: q.courseTitle
},
comments: commentsRows.map((c) => ({
id: c.id,
body: c.body,
votes: c.votes,
createdAt: c.createdAt,
author: {
id: c.authorId,
fullname: c.authorName,
avatarUrl: c.authorAvatar
}
}))
};
}
export async function submitComment({
body,
questionId,
authorProfileId,
votes
}: {
body: string;
questionId: number;
authorProfileId: string;
votes: number;
}) {
const response = await db
.insert(communityAnswer)
.values({
body,
questionId,
authorProfileId,
votes
})
.returning();
return response[0];
}
export async function upvoteQuestion({ id }: Partial<TCommunityQuestion>) {
if (!id) throw new Error('Question ID is required for upvoting');
const result = await db
.update(communityQuestion)
.set({ votes: sql`${communityQuestion.votes} + 1` })
.where(eq(communityQuestion.id, id))
.returning({ votes: communityQuestion.votes });
return result[0];
}
export async function upvoteAnswer({ id }: Partial<TCommunityAnswer>) {
if (!id) throw new Error('Answer ID is required for upvoting');
const result = await db
.update(communityAnswer)
.set({ votes: sql`${communityAnswer.votes} + 1` })
.where(eq(communityAnswer.id, id))
.returning({ votes: communityAnswer.votes });
return result[0];
}
export async function editCommunityQuestion({ id, title, body, courseId }: TNewCommunityQuestion) {
if (!id) throw new Error('Question ID is required for editing');
await db.update(communityQuestion).set({ title, body, courseId }).where(eq(communityQuestion.id, id));
}
export async function deleteCommentById(id: string) {
await db.delete(communityAnswer).where(eq(communityAnswer.id, id));
}
export async function deleteCommentByQuestionId(questionId: number) {
await db.delete(communityAnswer).where(eq(communityAnswer.questionId, questionId));
}
export async function deleteQuestionByQuestionId(questionId: number) {
await db.delete(communityQuestion).where(eq(communityQuestion.id, questionId));
}
export async function createCommunityQuestion({
title,
body,
organizationId,
authorProfileId,
slug,
courseId
}: TNewCommunityQuestion) {
const result = await db
.insert(communityQuestion)
.values({
title,
body,
organizationId,
authorProfileId,
votes: 0,
slug,
courseId
})
.returning();
return result[0];
}
/**
* Gets question author and course information for authorization checks
* @param questionId Question ID
* @returns Question with author ID and course ID, or null if not found
*/
export async function getQuestionAuthorAndCourse(questionId: number | string) {
const result = await db
.select({
id: communityQuestion.id,
authorId: communityQuestion.authorProfileId,
courseId: communityQuestion.courseId,
organizationId: communityQuestion.organizationId
})
.from(communityQuestion)
.where(eq(communityQuestion.id, Number(questionId)))
.limit(1);
return result.length > 0 ? result[0] : null;
}
/**
* Gets comment author and course information for authorization checks
* @param commentId Comment ID
* @returns Comment with author ID, question ID, and course ID, or null if not found
*/
export async function getCommentAuthorAndCourse(commentId: string) {
const result = await db
.select({
id: communityAnswer.id,
authorId: communityAnswer.authorProfileId,
questionId: communityAnswer.questionId,
courseId: communityQuestion.courseId,
organizationId: communityQuestion.organizationId
})
.from(communityAnswer)
.innerJoin(communityQuestion, eq(communityAnswer.questionId, communityQuestion.id))
.where(eq(communityAnswer.id, commentId))
.limit(1);
return result.length > 0 ? result[0] : null;
}
@@ -0,0 +1 @@
export * from './community';
+49 -2
View File
@@ -2,7 +2,7 @@ import * as schema from '@db/schema';
import { and, eq, sql } from 'drizzle-orm';
import { TNewCourse } from '@db/types';
import { TCourse, TNewCourse } from '@db/types';
import { db } from '@db/drizzle';
/**
@@ -10,7 +10,7 @@ import { db } from '@db/drizzle';
* @param siteName Organization site name
* @returns Array of courses with lesson counts and organization info
*/
export const getCoursesBySiteName = async (siteName: string) => {
export const getCoursesBySiteName = async (siteName: string): Promise<TCourse[]> => {
try {
const result = await db
.select({
@@ -56,6 +56,53 @@ export const getCoursesBySiteName = async (siteName: string) => {
}
};
/**
* Gets courses by organization orgId
* @param orgId Organization orgId
* @returns Array of courses with lesson counts and organization info
*/
export const getCoursesById = async (orgId: string): Promise<TCourse[]> => {
try {
const result = await db
.select({
course: schema.course,
organization: {
id: schema.organization.id,
name: schema.organization.name,
siteName: schema.organization.siteName,
avatarUrl: schema.organization.avatarUrl
},
lessonCount: sql<number>`COUNT(${schema.lesson.id})`.as('lesson_count')
})
.from(schema.course)
.innerJoin(schema.group, eq(schema.course.groupId, schema.group.id))
.innerJoin(schema.organization, eq(schema.group.organizationId, schema.organization.id))
.leftJoin(schema.lesson, eq(schema.course.id, schema.lesson.courseId))
.where(
and(eq(schema.organization.id, orgId), eq(schema.course.status, 'ACTIVE'), eq(schema.course.isPublished, true))
)
.groupBy(
schema.course.id,
schema.organization.id,
schema.organization.name,
schema.organization.siteName,
schema.organization.avatarUrl
);
return result.map((row) => ({
...row.course,
lessons: [{ count: Number(row.lessonCount) }],
group: {
organization: row.organization
}
}));
} catch (error) {
throw new Error(
`Failed to get courses by org ID "${orgId}": ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
};
/**
* Gets lessons by organization siteName
* @param siteName Organization site name
+63 -2
View File
@@ -1,7 +1,11 @@
import { db } from '@db/drizzle';
import { TNewGroup, TNewGroupmember } from '@db/types';
import * as schema from '@db/schema';
import { TNewGroup, TNewGroupmember } from '@db/types';
import { and, eq, or } from 'drizzle-orm';
import { ROLE } from '@cio/utils/constants';
import { db } from '@db/drizzle';
export async function createGroup(values: TNewGroup) {
try {
return db.insert(schema.group).values(values).returning();
@@ -17,3 +21,60 @@ export async function addGroupMember(values: TNewGroupmember) {
throw new Error(`Failed to add group member: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Checks if a user is a member of a course's group (any role)
* @param courseId Course ID
* @param profileId Profile ID to check
* @returns True if user is a member of the course's group, false otherwise
*/
export const isUserCourseMember = async (courseId: string, profileId: string): Promise<boolean> => {
const result = await db
.select({ roleId: schema.groupmember.roleId })
.from(schema.groupmember)
.innerJoin(schema.course, eq(schema.course.groupId, schema.groupmember.groupId))
.where(and(eq(schema.course.id, courseId), eq(schema.groupmember.profileId, profileId)))
.limit(1);
return result.length > 0;
};
/**
* Gets a user's role in a course's group
* @param courseId Course ID
* @param profileId Profile ID to check
* @returns Role ID if user is a member, null otherwise
*/
export const getUserCourseRole = async (courseId: string, profileId: string): Promise<number | null> => {
const result = await db
.select({ roleId: schema.groupmember.roleId })
.from(schema.groupmember)
.innerJoin(schema.course, eq(schema.course.groupId, schema.groupmember.groupId))
.where(and(eq(schema.course.id, courseId), eq(schema.groupmember.profileId, profileId)))
.limit(1);
return result.length > 0 ? Number(result[0].roleId) : null;
};
/**
* Checks if a user is a team member (ADMIN or TUTOR) in a course's group
* @param courseId Course ID
* @param profileId Profile ID to check
* @returns True if user is ADMIN or TUTOR in the course's group, false otherwise
*/
export const isUserCourseTeamMember = async (courseId: string, profileId: string): Promise<boolean> => {
const result = await db
.select({ roleId: schema.groupmember.roleId })
.from(schema.groupmember)
.innerJoin(schema.course, eq(schema.course.groupId, schema.groupmember.groupId))
.where(
and(
eq(schema.course.id, courseId),
eq(schema.groupmember.profileId, profileId),
or(eq(schema.groupmember.roleId, ROLE.ADMIN), eq(schema.groupmember.roleId, ROLE.TUTOR))
)
)
.limit(1);
return result.length > 0;
};
@@ -243,6 +243,44 @@ export const isUserOrgAdmin = async (orgId: string, profileId: string): Promise<
return result.length > 0;
};
/**
* Checks if a user is a member of an organization (any role)
* @param orgId Organization ID
* @param profileId Profile ID to check
* @returns True if user is a member, false otherwise
*/
export const isUserOrgMember = async (orgId: string, profileId: string): Promise<boolean> => {
const result = await db
.select({ roleId: schema.organizationmember.roleId })
.from(schema.organizationmember)
.where(and(eq(schema.organizationmember.organizationId, orgId), eq(schema.organizationmember.profileId, profileId)))
.limit(1);
return result.length > 0;
};
/**
* Checks if a user is a team member (ADMIN or TUTOR) of an organization
* @param orgId Organization ID
* @param profileId Profile ID to check
* @returns True if user is ADMIN or TUTOR, false otherwise
*/
export const isUserOrgTeamMember = async (orgId: string, profileId: string): Promise<boolean> => {
const result = await db
.select({ roleId: schema.organizationmember.roleId })
.from(schema.organizationmember)
.where(
and(
eq(schema.organizationmember.organizationId, orgId),
eq(schema.organizationmember.profileId, profileId),
or(eq(schema.organizationmember.roleId, ROLE.ADMIN), eq(schema.organizationmember.roleId, ROLE.TUTOR))
)
)
.limit(1);
return result.length > 0;
};
/**
* Gets organization team members (non-students)
* @param orgId Organization ID
@@ -11,5 +11,5 @@
<span class="ui:text-foreground ui:text-md">ClassroomIO</span>
</a>
<p class="ui:text-muted-foreground ui:text-sm">The Coure Platform That’s Actually <i>Easy To Use</i></p>
<p class="ui:text-muted-foreground ui:text-sm">The Course Platform That’s Actually <i>Easy To Use</i></p>
</div>
@@ -0,0 +1,69 @@
import * as z from 'zod';
export const ZCommunityQuestions = z.object({
orgId: z.string().min(1, 'orgId is required')
});
export const ZCommunityQuestion = z.object({
slug: z.string().min(1, 'slug is required')
});
export const ZNewCommunityQuestion = z.object({
slug: z.string().min(1, 'slug is required'),
body: z.string().min(1, 'body is required'),
title: z.string().min(1, 'title is required'),
courseId: z.string().min(1, 'courseId is required'),
organizationId: z.string().min(1, 'organizationId is required'),
authorProfileId: z.string().min(1, 'authorProfileId is required'),
votes: z.number().optional()
});
export const ZCreateCommunityQuestion = z.object({
body: z.string().min(1),
title: z.string().min(1),
courseId: z.string().optional()
});
export const ZGetCommunity = z.object({
id: z.coerce.number()
});
export const ZCommunityQuestionUpdate = z.object({
title: z.string().min(1, 'title is required'),
body: z.string().min(1, 'body is required'),
courseId: z.string().min(1, 'courseId is required')
});
// --- comment
export const ZCommunityCommentDelete = z.object({
id: z.string().min(1, 'id is required')
});
export const ZGetCommunityCommentQuestionId = z.object({
questionId: z.coerce.number()
});
export const ZCommunityComment = z.object({
body: z.string().min(1, 'body is required'),
authorProfileId: z.string().min(1, 'authorProfileId is required'),
votes: z.number().optional()
});
export const ZUpvotePost = z.object({
isQuestion: z.boolean()
});
export const ZUpvotePostParam = z.object({
id: z.union([z.string().min(1, 'id is required'), z.number().min(1, 'id is required')])
});
export type TNewCommunityQuestion = z.infer<typeof ZNewCommunityQuestion>;
export type TCreateCommunityQuestion = z.infer<typeof ZCreateCommunityQuestion>;
export type TCommunityQuestions = z.infer<typeof ZCommunityQuestions>;
export type TCommunityQuestion = z.infer<typeof ZCommunityQuestion>;
export type TCommunityComment = z.infer<typeof ZCommunityComment>;
export type TUpvotePost = z.infer<typeof ZUpvotePost>;
export type TCommunityCommentDelete = z.infer<typeof ZCommunityCommentDelete>;
export type TGetCommunity = z.infer<typeof ZGetCommunity>;
@@ -0,0 +1 @@
export * from './community';