feat: add authentication checks to checkout and customer portal actions

- Integrated authentication session validation in createCheckoutAction and createPortalAction to ensure only authorized users can create sessions.
- Enhanced unsubscribeNewsletterAction with similar authentication checks for improved security and user feedback.
This commit is contained in:
javayhu 2025-03-24 23:54:59 +08:00
parent bf4f296fe1
commit ef740e23db
3 changed files with 36 additions and 0 deletions

View File

@ -1,10 +1,12 @@
'use server';
import { auth } from "@/lib/auth";
import { getBaseUrlWithLocale } from "@/lib/urls/get-base-url";
import { createCheckout, getPlanById } from "@/payment";
import { CreateCheckoutParams } from "@/payment/types";
import { getLocale } from "next-intl/server";
import { createSafeActionClient } from 'next-safe-action';
import { headers } from "next/headers";
import { z } from 'zod';
// Create a safe action client
@ -24,6 +26,16 @@ const checkoutSchema = z.object({
export const createCheckoutAction = actionClient
.schema(checkoutSchema)
.action(async ({ parsedInput }) => {
const authSession = await auth.api.getSession({
headers: await headers(),
});
if (!authSession) {
return {
success: false,
error: 'Unauthorized',
};
}
try {
const { planId, priceId, email, metadata } = parsedInput;

View File

@ -1,10 +1,12 @@
'use server';
import { auth } from "@/lib/auth";
import { getBaseUrlWithLocale } from "@/lib/urls/get-base-url";
import { createCustomerPortal } from "@/payment";
import { CreatePortalParams } from "@/payment/types";
import { getLocale } from "next-intl/server";
import { createSafeActionClient } from 'next-safe-action';
import { headers } from "next/headers";
import { z } from 'zod';
// Create a safe action client
@ -22,6 +24,16 @@ const portalSchema = z.object({
export const createPortalAction = actionClient
.schema(portalSchema)
.action(async ({ parsedInput }) => {
const authSession = await auth.api.getSession({
headers: await headers(),
});
if (!authSession) {
return {
success: false,
error: 'Unauthorized',
};
}
try {
const { customerId, returnUrl } = parsedInput;

View File

@ -1,7 +1,9 @@
'use server';
import { auth } from '@/lib/auth';
import { unsubscribe } from '@/newsletter';
import { createSafeActionClient } from 'next-safe-action';
import { headers } from 'next/headers';
import { z } from 'zod';
// Create a safe action client
@ -16,6 +18,16 @@ const newsletterSchema = z.object({
export const unsubscribeNewsletterAction = actionClient
.schema(newsletterSchema)
.action(async ({ parsedInput: { email } }) => {
const authSession = await auth.api.getSession({
headers: await headers(),
});
if (!authSession) {
return {
success: false,
error: 'Unauthorized',
};
}
try {
const unsubscribed = await unsubscribe(email);