mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 09:36:08 +00:00
feat(billing): integrate Stripe for subscription management and billing access
- Added billing-related fields to the User model in the database. - Implemented functions for managing billing access, including trial periods and subscription statuses. - Created new billing utility functions for Stripe integration. - Updated onboarding page to include billing overview and workspace creation eligibility. - Enhanced route access checks to require billing access for certain actions. - Implemented cleanup scripts for expired billing workspaces and associated media. - Updated header component to conditionally show app navigation based on billing access. - Added new migrations for billing-related database changes.
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import {
|
||||
DEFAULT_TRIAL_PERIOD_DAYS,
|
||||
getOrCreateStripeCustomerId,
|
||||
getStripeCheckoutState,
|
||||
} from '@/lib/billing';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { getStripe, getStripePriceId, isStripeConfigured } from '@/lib/stripe';
|
||||
import { isTrustedSameOriginRequest } from '@/lib/request-origin';
|
||||
|
||||
function getAppOrigin(request: NextRequest) {
|
||||
if (isTrustedSameOriginRequest(request)) {
|
||||
const origin = request.headers.get('origin');
|
||||
if (origin) {
|
||||
return new URL(origin).origin;
|
||||
}
|
||||
}
|
||||
|
||||
return request.nextUrl.origin;
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
if (!isTrustedSameOriginRequest(request)) {
|
||||
return apiErrors.forbidden('Invalid request origin');
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
if (!isStripeConfigured()) {
|
||||
return apiErrors.internalError('Stripe billing is not configured');
|
||||
}
|
||||
|
||||
const checkoutState = await getStripeCheckoutState(session.user.id);
|
||||
if (checkoutState.hasActiveSubscription) {
|
||||
return apiErrors.badRequest('An active subscription already exists for this account');
|
||||
}
|
||||
|
||||
const stripe = getStripe();
|
||||
const priceId = getStripePriceId();
|
||||
const customerId = await getOrCreateStripeCustomerId(session.user.id);
|
||||
const appOrigin = getAppOrigin(request);
|
||||
|
||||
const checkoutSession = await stripe.checkout.sessions.create({
|
||||
mode: 'subscription',
|
||||
customer: customerId,
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
allow_promotion_codes: true,
|
||||
success_url: `${appOrigin}/settings?billing=success`,
|
||||
cancel_url: `${appOrigin}/settings?billing=canceled`,
|
||||
metadata: {
|
||||
userId: session.user.id,
|
||||
},
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
userId: session.user.id,
|
||||
},
|
||||
...(checkoutState.isTrialEligible ? { trial_period_days: DEFAULT_TRIAL_PERIOD_DAYS } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (!checkoutSession.url) {
|
||||
throw new Error('Stripe did not return a checkout URL');
|
||||
}
|
||||
|
||||
const response = successResponse({ url: checkoutSession.url });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error creating Stripe checkout session:', error);
|
||||
return apiErrors.internalError('Failed to start checkout');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { getBillingOverview } from '@/lib/billing';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { getStripe, isStripeConfigured } from '@/lib/stripe';
|
||||
import { isTrustedSameOriginRequest } from '@/lib/request-origin';
|
||||
|
||||
function getAppOrigin(request: NextRequest) {
|
||||
if (isTrustedSameOriginRequest(request)) {
|
||||
const origin = request.headers.get('origin');
|
||||
if (origin) {
|
||||
return new URL(origin).origin;
|
||||
}
|
||||
}
|
||||
|
||||
return request.nextUrl.origin;
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const limited = await rateLimit(request, 'mutate');
|
||||
if (limited) return limited;
|
||||
|
||||
if (!isTrustedSameOriginRequest(request)) {
|
||||
return apiErrors.forbidden('Invalid request origin');
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
if (!isStripeConfigured()) {
|
||||
return apiErrors.internalError('Stripe billing is not configured');
|
||||
}
|
||||
|
||||
const billing = await getBillingOverview(session.user.id);
|
||||
if (!billing.subscription.stripeCustomerId) {
|
||||
return apiErrors.badRequest('No Stripe customer exists for this account');
|
||||
}
|
||||
|
||||
const stripe = getStripe();
|
||||
const portalSession = await stripe.billingPortal.sessions.create({
|
||||
customer: billing.subscription.stripeCustomerId,
|
||||
return_url: `${getAppOrigin(request)}/settings`,
|
||||
});
|
||||
|
||||
const response = successResponse({ url: portalSession.url });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error creating Stripe portal session:', error);
|
||||
return apiErrors.internalError('Failed to open billing portal');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { auth } from '@/lib/auth';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { getBillingOverview } from '@/lib/billing';
|
||||
import { isStripeConfigured } from '@/lib/stripe';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const billing = await getBillingOverview(session.user.id);
|
||||
const response = successResponse({
|
||||
isConfigured: isStripeConfigured(),
|
||||
checkoutAvailable: isStripeConfigured() && !billing.subscription.hasActiveSubscription,
|
||||
portalAvailable: isStripeConfigured() && Boolean(billing.subscription.stripeCustomerId),
|
||||
subscription: {
|
||||
status: billing.subscription.status,
|
||||
label: billing.subscription.label,
|
||||
hasActiveSubscription: billing.subscription.hasActiveSubscription,
|
||||
hasActiveTrial: billing.subscription.hasActiveTrial,
|
||||
hasBillingAccess: billing.subscription.hasBillingAccess,
|
||||
priceId: billing.subscription.stripePriceId,
|
||||
currentPeriodEnd: billing.subscription.currentPeriodEnd?.toISOString() ?? null,
|
||||
cancelAtPeriodEnd: billing.subscription.cancelAtPeriodEnd ?? false,
|
||||
cancelAt: billing.subscription.cancelAt?.toISOString() ?? null,
|
||||
trialEndsAt: billing.subscription.trialEndsAt?.toISOString() ?? null,
|
||||
billingAccessEndedAt: billing.subscription.billingAccessEndedAt?.toISOString() ?? null,
|
||||
storageCleanupEligibleAt: billing.subscription.storageCleanupEligibleAt?.toISOString() ?? null,
|
||||
},
|
||||
workspaceCreation: billing.workspaceCreation,
|
||||
});
|
||||
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error fetching billing overview:', error);
|
||||
return apiErrors.internalError('Failed to fetch billing overview');
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkProjectAccess } from '@/lib/auth';
|
||||
import { ProjectMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
@@ -29,10 +29,11 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
@@ -44,15 +45,24 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.badRequest('Invalid role. Must be ADMIN or COMMENTATOR.');
|
||||
}
|
||||
|
||||
const member = await db.projectMember.update({
|
||||
where: { id: memberId },
|
||||
const member = await db.projectMember.findFirst({
|
||||
where: { id: memberId, projectId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!member) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const updatedMember = await db.projectMember.update({
|
||||
where: { id: member.id },
|
||||
data: { role: role as ProjectMemberRole },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(member);
|
||||
const response = successResponse(updatedMember);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error updating member role:', error);
|
||||
@@ -82,11 +92,13 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
const memberToRemove = await db.projectMember.findUnique({
|
||||
where: { id: memberId },
|
||||
const memberToRemove = await db.projectMember.findFirst({
|
||||
where: { id: memberId, projectId },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
|
||||
if (!memberToRemove) {
|
||||
@@ -95,11 +107,11 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
|
||||
const isSelf = memberToRemove.userId === session.user.id;
|
||||
|
||||
if (!isOwner && !isAdmin && !isSelf) {
|
||||
if ((!access.canEdit || (!isOwner && !isAdmin)) && !isSelf) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
await db.projectMember.delete({ where: { id: memberId } });
|
||||
await db.projectMember.delete({ where: { id: memberToRemove.id } });
|
||||
|
||||
const response = successResponse({ message: 'Member removed' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { InvitationStatus, ProjectMemberRole } from '@prisma/client';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkProjectAccess } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
@@ -29,10 +29,11 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only project owners and admins can cancel invitations');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkProjectAccess } from '@/lib/auth';
|
||||
import { InvitationRole, ProjectMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
|
||||
@@ -29,11 +29,12 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id);
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isMember = project.members.length > 0;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isMember) {
|
||||
if (!access.hasAccess || (!isOwner && !isMember)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
@@ -105,10 +106,11 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Project');
|
||||
}
|
||||
|
||||
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
|
||||
const isOwner = project.ownerId === session.user.id;
|
||||
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only project owners and admins can invite members');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkWorkspaceAccess } from '@/lib/auth';
|
||||
import { ProjectVisibility } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildBillingAccessWhereInput } from '@/lib/billing';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { DEFAULT_COMMENT_TAGS } from '@/lib/comment-tags';
|
||||
|
||||
@@ -48,10 +49,14 @@ export async function GET(request: NextRequest) {
|
||||
// Also include projects in workspaces where the user is a workspace member
|
||||
...(workspaceId ? [] : [{
|
||||
workspace: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
members: { some: { userId: session.user.id } },
|
||||
},
|
||||
}]),
|
||||
],
|
||||
workspace: {
|
||||
owner: buildBillingAccessWhereInput(),
|
||||
},
|
||||
};
|
||||
|
||||
// Filter by workspace if provided
|
||||
@@ -150,10 +155,12 @@ export async function POST(request: NextRequest) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const isWsOwner = workspace.ownerId === session.user.id;
|
||||
const isWsAdmin = workspace.members[0]?.role === 'ADMIN';
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
|
||||
if (!isWsOwner && !isWsAdmin) {
|
||||
if (!access.canEdit) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can create projects');
|
||||
}
|
||||
|
||||
@@ -164,7 +171,7 @@ export async function POST(request: NextRequest) {
|
||||
description: description?.trim() || null,
|
||||
slug,
|
||||
visibility: visibility || ProjectVisibility.PRIVATE,
|
||||
ownerId: session.user.id,
|
||||
ownerId: workspace.ownerId,
|
||||
workspaceId,
|
||||
},
|
||||
include: {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import type Stripe from 'stripe';
|
||||
import {
|
||||
markSubscriptionCanceledByCustomerId,
|
||||
syncStripeSubscriptionToUser,
|
||||
} from '@/lib/billing';
|
||||
import { getStripe, getStripeWebhookSecret } from '@/lib/stripe';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
async function handleSubscriptionDeleted(subscription: Stripe.Subscription) {
|
||||
const customerId =
|
||||
typeof subscription.customer === 'string'
|
||||
? subscription.customer
|
||||
: subscription.customer.id;
|
||||
|
||||
const currentPeriodEnd =
|
||||
'current_period_end' in subscription && typeof subscription.current_period_end === 'number'
|
||||
? new Date(subscription.current_period_end * 1000)
|
||||
: null;
|
||||
const endedAt =
|
||||
'ended_at' in subscription && typeof subscription.ended_at === 'number'
|
||||
? new Date(subscription.ended_at * 1000)
|
||||
: currentPeriodEnd;
|
||||
|
||||
await markSubscriptionCanceledByCustomerId(customerId, {
|
||||
currentPeriodEnd,
|
||||
endedAt,
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const signature = request.headers.get('stripe-signature');
|
||||
if (!signature) {
|
||||
return new Response('Missing Stripe signature', { status: 400 });
|
||||
}
|
||||
|
||||
let event: Stripe.Event;
|
||||
|
||||
try {
|
||||
const stripe = getStripe();
|
||||
const body = await request.text();
|
||||
event = stripe.webhooks.constructEvent(body, signature, getStripeWebhookSecret());
|
||||
} catch (error) {
|
||||
console.error('Failed to verify Stripe webhook:', error);
|
||||
return new Response('Invalid webhook signature', { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const stripe = getStripe();
|
||||
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed': {
|
||||
const session = event.data.object as Stripe.Checkout.Session;
|
||||
if (session.mode === 'subscription' && session.subscription) {
|
||||
const subscriptionId =
|
||||
typeof session.subscription === 'string'
|
||||
? session.subscription
|
||||
: session.subscription.id;
|
||||
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
||||
await syncStripeSubscriptionToUser(subscription);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'customer.subscription.created':
|
||||
case 'customer.subscription.updated': {
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
await syncStripeSubscriptionToUser(subscription);
|
||||
break;
|
||||
}
|
||||
case 'customer.subscription.deleted': {
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
await handleSubscriptionDeleted(subscription);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ received: true }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to process Stripe webhook:', error);
|
||||
return new Response('Webhook processing failed', { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkWorkspaceAccess } from '@/lib/auth';
|
||||
import { WorkspaceMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
@@ -30,10 +30,14 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
@@ -45,15 +49,24 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.badRequest('Invalid role. Must be ADMIN or COMMENTATOR.');
|
||||
}
|
||||
|
||||
const member = await db.workspaceMember.update({
|
||||
where: { id: memberId },
|
||||
const member = await db.workspaceMember.findFirst({
|
||||
where: { id: memberId, workspaceId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!member) {
|
||||
return apiErrors.notFound('Member');
|
||||
}
|
||||
|
||||
const updatedMember = await db.workspaceMember.update({
|
||||
where: { id: member.id },
|
||||
data: { role: role as WorkspaceMemberRole },
|
||||
include: {
|
||||
user: { select: { id: true, name: true, image: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const response = successResponse(member);
|
||||
const response = successResponse(updatedMember);
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
} catch (error) {
|
||||
console.error('Error updating member role:', error);
|
||||
@@ -83,12 +96,17 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
// Users can remove themselves, admins/owners can remove anyone
|
||||
const memberToRemove = await db.workspaceMember.findUnique({
|
||||
where: { id: memberId },
|
||||
const memberToRemove = await db.workspaceMember.findFirst({
|
||||
where: { id: memberId, workspaceId },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
|
||||
if (!memberToRemove) {
|
||||
@@ -97,11 +115,32 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
|
||||
const isSelf = memberToRemove.userId === session.user.id;
|
||||
|
||||
if (!isOwner && !isAdmin && !isSelf) {
|
||||
if ((!access.canEdit || (!isOwner && !isAdmin)) && !isSelf) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
await db.workspaceMember.delete({ where: { id: memberId } });
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.projectMember.deleteMany({
|
||||
where: {
|
||||
userId: memberToRemove.userId,
|
||||
project: {
|
||||
workspaceId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.project.updateMany({
|
||||
where: {
|
||||
workspaceId,
|
||||
ownerId: memberToRemove.userId,
|
||||
},
|
||||
data: {
|
||||
ownerId: workspace.ownerId,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workspaceMember.delete({ where: { id: memberToRemove.id } });
|
||||
});
|
||||
|
||||
const response = successResponse({ message: 'Member removed' });
|
||||
return withCacheControl(response, 'private, no-store');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { InvitationStatus, WorkspaceMemberRole } from '@prisma/client';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkWorkspaceAccess } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
@@ -29,10 +29,14 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can cancel invitations');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { auth, checkWorkspaceAccess } from '@/lib/auth';
|
||||
import { InvitationRole, WorkspaceMemberRole } from '@prisma/client';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
|
||||
@@ -53,11 +53,15 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isMember = workspace.members.length > 0;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isMember) {
|
||||
if (!access.hasAccess || (!isOwner && !isMember)) {
|
||||
return apiErrors.forbidden('Access denied');
|
||||
}
|
||||
|
||||
@@ -145,10 +149,14 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
return apiErrors.notFound('Workspace');
|
||||
}
|
||||
|
||||
const access = await checkWorkspaceAccess(
|
||||
{ id: workspace.id, ownerId: workspace.ownerId },
|
||||
session.user.id
|
||||
);
|
||||
const isOwner = workspace.ownerId === session.user.id;
|
||||
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
|
||||
|
||||
if (!isOwner && !isAdmin) {
|
||||
if (!access.canEdit || (!isOwner && !isAdmin)) {
|
||||
return apiErrors.forbidden('Only workspace owners and admins can invite members');
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { auth } from '@/lib/auth';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { buildBillingAccessWhereInput, getWorkspaceCreationEligibility } from '@/lib/billing';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
|
||||
// GET /api/workspaces - List all workspaces for the authenticated user
|
||||
@@ -39,8 +40,8 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const where = {
|
||||
OR: [
|
||||
{ ownerId: session.user.id },
|
||||
{ members: { some: { userId: session.user.id } } },
|
||||
{ ownerId: session.user.id, owner: buildBillingAccessWhereInput() },
|
||||
{ members: { some: { userId: session.user.id } }, owner: buildBillingAccessWhereInput() },
|
||||
],
|
||||
};
|
||||
|
||||
@@ -88,6 +89,13 @@ export async function POST(request: NextRequest) {
|
||||
return apiErrors.unauthorized();
|
||||
}
|
||||
|
||||
const billing = await getWorkspaceCreationEligibility(session.user.id);
|
||||
if (!billing.canCreateWorkspace) {
|
||||
return apiErrors.forbidden(
|
||||
billing.reason || 'Upgrade your account to create another workspace'
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, description } = body;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user