feat(auth): include subscription tier in token and session payload
- Adds subscription tier info to access/refresh tokens. - Stores tier details in session Redis record. - Returns tier data in login/register response. - Uses default tier when user has none.
This commit is contained in:
1 parent
7f42def478
commit
d27526e026
20 files changed
+2133
-40
No files matched your search
@@ -0,0 +1,210 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAdminUser } from "@/lib/auth/middleware";
|
||||
import {
|
||||
getSubscriptionTierById,
|
||||
updateSubscriptionTier,
|
||||
deleteSubscriptionTier,
|
||||
countUsersInSubscriptionTier,
|
||||
} from "@/lib/prisma/queries/subscription-tiers";
|
||||
import { updateSubscriptionTierSchema } from "@/lib/validation-schemas";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAdminUser(request);
|
||||
if (auth instanceof NextResponse) {
|
||||
return auth;
|
||||
}
|
||||
|
||||
try {
|
||||
const { id } = await params;
|
||||
const tierId = Number.parseInt(id, 10);
|
||||
|
||||
if (Number.isNaN(tierId) || tierId <= 0) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "ID de tier inválido" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const tier = await getSubscriptionTierById(tierId, true);
|
||||
|
||||
if (!tier) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Plano não encontrado" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
tier,
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
secureLogger.error("❌ Erro ao consultar subscription tier", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Erro ao consultar plano de assinatura",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAdminUser(request);
|
||||
if (auth instanceof NextResponse) {
|
||||
return auth;
|
||||
}
|
||||
|
||||
try {
|
||||
const { id } = await params;
|
||||
const tierId = Number.parseInt(id, 10);
|
||||
|
||||
if (Number.isNaN(tierId) || tierId <= 0) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "ID de tier inválido" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const parsed = updateSubscriptionTierSchema.parse(body);
|
||||
|
||||
const updatedTier = await updateSubscriptionTier(tierId, {
|
||||
name: parsed.name,
|
||||
slug: parsed.slug,
|
||||
description: parsed.description ?? undefined,
|
||||
level: parsed.level,
|
||||
price_monthly: parsed.priceMonthly ?? undefined,
|
||||
price_yearly: parsed.priceYearly ?? undefined,
|
||||
is_active: parsed.isActive,
|
||||
features: parsed.features?.map((feature, index) => ({
|
||||
feature_key: feature.featureKey,
|
||||
label: feature.label,
|
||||
description: feature.description ?? null,
|
||||
sort_order: feature.sortOrder ?? index,
|
||||
_delete: feature._delete ?? false,
|
||||
})),
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
tier: updatedTier,
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && "issues" in error) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Dados inválidos",
|
||||
details: (error as any).issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
secureLogger.error("❌ Erro ao atualizar subscription tier", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Erro ao atualizar plano de assinatura",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const auth = await requireAdminUser(request);
|
||||
if (auth instanceof NextResponse) {
|
||||
return auth;
|
||||
}
|
||||
|
||||
try {
|
||||
const { id } = await params;
|
||||
const tierId = Number.parseInt(id, 10);
|
||||
|
||||
if (Number.isNaN(tierId) || tierId <= 0) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "ID de tier inválido" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const tier = await getSubscriptionTierById(tierId, false);
|
||||
|
||||
if (!tier) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Plano não encontrado" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
if (tier.slug === "free") {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "O plano padrão 'free' não pode ser removido.",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const userCount = await countUsersInSubscriptionTier(tierId);
|
||||
|
||||
if (userCount > 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Plano não pode ser removido enquanto houver usuários associados.",
|
||||
users: userCount,
|
||||
},
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
await deleteSubscriptionTier(tierId);
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
secureLogger.error("❌ Erro ao remover subscription tier", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Erro ao remover plano de assinatura",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAdminUser } from "@/lib/auth/middleware";
|
||||
import {
|
||||
assignUserToSubscriptionTier,
|
||||
getSubscriptionTierById,
|
||||
getSubscriptionTierBySlug,
|
||||
getDefaultSubscriptionTier,
|
||||
} from "@/lib/prisma/queries/subscription-tiers";
|
||||
import { assignSubscriptionTierSchema } from "@/lib/validation-schemas";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
import { getUserById } from "@/lib/prisma/queries/users";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const auth = await requireAdminUser(request);
|
||||
if (auth instanceof NextResponse) {
|
||||
return auth;
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = assignSubscriptionTierSchema.parse(body);
|
||||
|
||||
const user = await getUserById(parsed.userId);
|
||||
if (!user) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Usuário não encontrado.",
|
||||
},
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
let targetTierId: number | null = null;
|
||||
let targetTier:
|
||||
| {
|
||||
subscription_tier_id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
level: number;
|
||||
}
|
||||
| null = null;
|
||||
|
||||
if (parsed.tierId !== undefined) {
|
||||
if (parsed.tierId === null) {
|
||||
const defaultTier = await getDefaultSubscriptionTier();
|
||||
if (!defaultTier) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Plano padrão não encontrado.",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
targetTier = defaultTier;
|
||||
} else {
|
||||
const tierById = await getSubscriptionTierById(parsed.tierId, false);
|
||||
if (!tierById) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Plano informado não existe.",
|
||||
},
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
targetTier = tierById;
|
||||
}
|
||||
} else if (parsed.tierSlug) {
|
||||
const tierBySlug = await getSubscriptionTierBySlug(parsed.tierSlug, false);
|
||||
if (!tierBySlug) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Plano informado não existe.",
|
||||
},
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
targetTier = tierBySlug;
|
||||
}
|
||||
|
||||
if (!targetTier) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Plano de assinatura não identificado.",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
targetTierId = targetTier.subscription_tier_id;
|
||||
|
||||
await assignUserToSubscriptionTier(parsed.userId, targetTierId);
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
userId: parsed.userId,
|
||||
tier: {
|
||||
id: targetTier.subscription_tier_id,
|
||||
name: targetTier.name,
|
||||
slug: targetTier.slug,
|
||||
level: targetTier.level,
|
||||
},
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && "issues" in error) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Dados inválidos",
|
||||
details: (error as any).issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
secureLogger.error("❌ Erro ao atribuir subscription tier", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Erro ao atribuir plano de assinatura ao usuário",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAdminUser } from "@/lib/auth/middleware";
|
||||
import {
|
||||
getAllSubscriptionTiers,
|
||||
createSubscriptionTier,
|
||||
} from "@/lib/prisma/queries/subscription-tiers";
|
||||
import { createSubscriptionTierSchema } from "@/lib/validation-schemas";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const auth = await requireAdminUser(request);
|
||||
if (auth instanceof NextResponse) {
|
||||
return auth;
|
||||
}
|
||||
|
||||
try {
|
||||
const tiers = await getAllSubscriptionTiers(true);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
tiers,
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
secureLogger.error("❌ Erro ao listar subscription tiers", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Erro ao listar planos de assinatura",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const auth = await requireAdminUser(request);
|
||||
if (auth instanceof NextResponse) {
|
||||
return auth;
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = createSubscriptionTierSchema.parse(body);
|
||||
|
||||
const tier = await createSubscriptionTier({
|
||||
name: parsed.name,
|
||||
slug: parsed.slug,
|
||||
description: parsed.description ?? null,
|
||||
level: parsed.level ?? 0,
|
||||
price_monthly: parsed.priceMonthly ?? null,
|
||||
price_yearly: parsed.priceYearly ?? null,
|
||||
is_active: parsed.isActive ?? true,
|
||||
features: parsed.features?.map((feature, index) => ({
|
||||
feature_key: feature.featureKey,
|
||||
label: feature.label,
|
||||
description: feature.description ?? null,
|
||||
sort_order: feature.sortOrder ?? index,
|
||||
})),
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
tier,
|
||||
},
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof NextResponse) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (error instanceof Error && "issues" in error) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Dados inválidos",
|
||||
details: (error as any).issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
secureLogger.error("❌ Erro ao criar subscription tier", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Erro ao criar plano de assinatura",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user