mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
refactor(auth): Centralize project access checks
- Move `checkProjectAccess` function to `lib/auth.ts` - Consolidate project access logic into a single utility - Simplify access checks in video API routes - Remove redundant project member inclusions from queries
This commit is contained in:
@@ -1,37 +1,10 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkProjectAccess } from '@/lib/auth';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
|
||||
type RouteParams = { params: Promise<{ videoId: string }> };
|
||||
|
||||
// Helper to check project access including workspace membership
|
||||
async function checkProjectAccess(project: { ownerId: string; workspaceId: string; visibility: string; members: { userId: string }[] }, userId: string | undefined) {
|
||||
const isOwner = userId === project.ownerId;
|
||||
const isMember = project.members.some(m => m.userId === userId);
|
||||
const isPublic = project.visibility === 'PUBLIC';
|
||||
|
||||
// Check workspace membership for access
|
||||
let isWorkspaceMember = false;
|
||||
if (!isOwner && !isMember && !isPublic && userId) {
|
||||
const wsMember = await db.workspaceMember.findUnique({
|
||||
where: {
|
||||
workspaceId_userId: {
|
||||
workspaceId: project.workspaceId,
|
||||
userId: userId,
|
||||
},
|
||||
},
|
||||
});
|
||||
const wsOwner = await db.workspace.findUnique({
|
||||
where: { id: project.workspaceId },
|
||||
select: { ownerId: true },
|
||||
});
|
||||
isWorkspaceMember = !!wsMember || wsOwner?.ownerId === userId;
|
||||
}
|
||||
|
||||
return { isOwner, isMember, isPublic, isWorkspaceMember, hasAccess: isOwner || isMember || isPublic || isWorkspaceMember };
|
||||
}
|
||||
|
||||
// GET /api/watch/[videoId] - Public watch endpoint (no projectId needed)
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
@@ -41,11 +14,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
const video = await db.video.findUnique({
|
||||
where: { id: videoId },
|
||||
include: {
|
||||
project: {
|
||||
include: {
|
||||
members: { where: { userId: session?.user?.id || '' } },
|
||||
},
|
||||
},
|
||||
project: true,
|
||||
versions: {
|
||||
orderBy: { versionNumber: 'desc' },
|
||||
include: {
|
||||
@@ -92,7 +61,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
visibility: project.visibility,
|
||||
},
|
||||
isAuthenticated: !!session?.user?.id,
|
||||
canComment: access.isOwner || access.isMember || access.isPublic || access.isWorkspaceMember,
|
||||
canComment: access.hasAccess,
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-cache');
|
||||
|
||||
Reference in New Issue
Block a user