mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 09:36:08 +00:00
feat: add approvals workflow and unified member invitation management across projects, workspaces, and videos
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { InvitationStatus, WorkspaceMemberRole } from '@prisma/client';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
|
||||
type RouteParams = { params: Promise<{ workspaceId: string; invitationId: string }> };
|
||||
|
||||
// DELETE /api/workspaces/[workspaceId]/members/invitations/[invitationId] - Cancel a pending invitation
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'manage-member');
|
||||
if (limited) return limited;
|
||||
|
||||
const session = await auth();
|
||||
const { workspaceId, invitationId } = await params;
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const workspace = await db.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
include: { members: { where: { userId: session.user.id } } },
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can cancel invitations');
|
||||
}
|
||||
|
||||
const invitation = await db.invitation.findFirst({
|
||||
where: {
|
||||
id: invitationId,
|
||||
workspaceId,
|
||||
scope: 'WORKSPACE',
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!invitation) {
|
||||
return apiErrors.notFound('Invitation');
|
||||
}
|
||||
|
||||
if (invitation.status !== InvitationStatus.PENDING) {
|
||||
return apiErrors.conflict('Only pending invitations can be canceled');
|
||||
}
|
||||
|
||||
await db.invitation.update({
|
||||
where: { id: invitation.id },
|
||||
data: { status: InvitationStatus.CANCELED },
|
||||
});
|
||||
|
||||
const response = successResponse({ message: 'Invitation canceled' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error canceling workspace invitation:', error);
|
||||
return apiErrors.internalError('Failed to cancel invitation');
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { WorkspaceMemberRole } from '@prisma/client';
|
||||
import { InvitationRole, WorkspaceMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
|
||||
type RouteParams = { params: Promise<{ workspaceId: string }> };
|
||||
@@ -54,12 +55,15 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isMember = workspace.members.length > 0;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isMember) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
const [members, total] = await Promise.all([
|
||||
const now = new Date();
|
||||
const canViewPendingInvitations = isOwner || isAdmin;
|
||||
const [members, total, pendingInvitations] = await Promise.all([
|
||||
db.workspaceMember.findMany({
|
||||
where: { workspaceId },
|
||||
include: {
|
||||
@@ -72,6 +76,27 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
db.workspaceMember.count({
|
||||
where: { workspaceId },
|
||||
}),
|
||||
canViewPendingInvitations
|
||||
? db.invitation.findMany({
|
||||
where: {
|
||||
workspaceId,
|
||||
scope: 'WORKSPACE',
|
||||
status: 'PENDING',
|
||||
expiresAt: { gt: now },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
expiresAt: true,
|
||||
invitedBy: {
|
||||
select: { id: true, name: true, email: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
|
||||
// Include the owner as well
|
||||
@@ -81,7 +106,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
});
|
||||
|
||||
const response = successResponse(
|
||||
{ members, owner },
|
||||
{ members, owner, pendingInvitations },
|
||||
200,
|
||||
{
|
||||
page,
|
||||
@@ -90,7 +115,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
totalPages: Math.ceil(total / limit),
|
||||
}
|
||||
);
|
||||
return withCacheControl(response, 'private, max-age=60, stale-while-revalidate=120');
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error fetching workspace members:', error);
|
||||
return apiErrors.internalError('Failed to fetch members');
|
||||
@@ -134,45 +159,55 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.badRequest('Email is required');
|
||||
}
|
||||
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.validationError('Invalid email format');
|
||||
}
|
||||
|
||||
// Validate role
|
||||
const validRoles = ['ADMIN', 'COMMENTATOR'];
|
||||
const memberRole = validRoles.includes(role) ? role : 'COMMENTATOR';
|
||||
|
||||
// Find user by email
|
||||
// If this email belongs to an existing user, validate owner/member conflicts.
|
||||
const userToInvite = await db.user.findUnique({
|
||||
where: { email: email.toLowerCase().trim() },
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!userToInvite) {
|
||||
const response = successResponse({ message: 'If the user exists, an invitation has been sent.' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
}
|
||||
|
||||
if (userToInvite.id === workspace.ownerId) {
|
||||
if (userToInvite?.id === workspace.ownerId) {
|
||||
return apiErrors.badRequest('Cannot invite the workspace owner as a member');
|
||||
}
|
||||
|
||||
// Check if already a member
|
||||
const existingMember = await db.workspaceMember.findUnique({
|
||||
where: { workspaceId_userId: { workspaceId, userId: userToInvite.id } },
|
||||
});
|
||||
if (userToInvite) {
|
||||
const existingMember = await db.workspaceMember.findUnique({
|
||||
where: { workspaceId_userId: { workspaceId, userId: userToInvite.id } },
|
||||
});
|
||||
|
||||
if (existingMember) {
|
||||
return apiErrors.conflict('User is already a member of this workspace');
|
||||
if (existingMember) {
|
||||
return apiErrors.conflict('User is already a member of this workspace');
|
||||
}
|
||||
}
|
||||
|
||||
const member = await db.workspaceMember.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
userId: userToInvite.id,
|
||||
role: memberRole as WorkspaceMemberRole,
|
||||
},
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true, image: true } },
|
||||
},
|
||||
const invitation = await createOrRefreshInvitation({
|
||||
email: normalizedEmail,
|
||||
scope: 'WORKSPACE',
|
||||
role: memberRole as InvitationRole,
|
||||
invitedById: session.user.id,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
const response = successResponse(member, 201);
|
||||
const invitationUrl = buildInvitationUrl(invitation.token, normalizedEmail);
|
||||
void sendInvitationEmail({
|
||||
to: normalizedEmail,
|
||||
inviterName: session.user.name || 'A team member',
|
||||
role: invitation.role,
|
||||
scope: invitation.scope,
|
||||
targetName: workspace.name,
|
||||
invitationUrl,
|
||||
});
|
||||
|
||||
const response = successResponse({ message: 'Invitation email sent.' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error inviting workspace member:', error);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { cleanupWorkspaceMediaFiles } from '@/lib/r2-cleanup';
|
||||
import { cleanupBunnyStreamVideos } from '@/lib/bunny-stream-cleanup';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
|
||||
type RouteParams = { params: Promise<{ workspaceId: string }> };
|
||||
@@ -164,6 +165,22 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.forbidden('Only the workspace owner can delete it');
|
||||
}
|
||||
|
||||
// Delete Bunny provider videos first to avoid orphaned external assets.
|
||||
const workspaceVersionRefs = await db.videoVersion.findMany({
|
||||
where: {
|
||||
video: {
|
||||
project: {
|
||||
workspaceId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
providerId: true,
|
||||
videoId: true,
|
||||
},
|
||||
});
|
||||
await cleanupBunnyStreamVideos(workspaceVersionRefs);
|
||||
|
||||
// Clean up voice files from R2 before cascade delete removes comment rows
|
||||
await cleanupWorkspaceMediaFiles(workspaceId);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user