Audit fixes: VIP self-grant, draft leak, onboarding flag, hero personalization, gated downloads
Deploy GitHub Pages / deploy (push) Canceled after 0s
Deploy GitHub Pages / deploy (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import configPromise from '@payload-config'
|
||||
import type { Media } from '@payload-types'
|
||||
import { resolveCoverImage } from '@/lib/agent-media'
|
||||
import { resolveAttachments, deleteFileDocs } from '@/lib/agent-files'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/** Agent update endpoint: PUT /api/agent/posts/:slug */
|
||||
export async function PUT(req: NextRequest, ctx: { params: Promise<{ slug: string }> }) {
|
||||
const key = process.env.AGENT_API_KEY
|
||||
if (!key || req.headers.get('x-agent-key') !== key) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { slug } = await ctx.params
|
||||
const body = (await req.json().catch(() => null)) as Record<string, unknown> | null
|
||||
if (!body) return NextResponse.json({ error: 'invalid JSON body' }, { status: 400 })
|
||||
|
||||
const existing = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { slug: { equals: slug } },
|
||||
limit: 1,
|
||||
})
|
||||
const post = existing.docs[0]
|
||||
if (!post) return NextResponse.json({ error: 'not found' }, { status: 404 })
|
||||
|
||||
// Only writable fields; status is admin-only (except the explicit publish flag)
|
||||
const allowed = ['title', 'slug', 'dek', 'teaser', 'content', 'category', 'access', 'readingMinutes', 'cover'] as const
|
||||
const data: Record<string, unknown> = {}
|
||||
for (const field of allowed) {
|
||||
if (field in body) data[field] = body[field]
|
||||
}
|
||||
|
||||
// Explicit image payload (inline base64 or remote URL) → stored as a media document.
|
||||
let coverUrl: string | null = null
|
||||
if ('coverImage' in body && body.coverImage != null) {
|
||||
try {
|
||||
const cover = await resolveCoverImage(payload, body.coverImage)
|
||||
data.cover = cover.id
|
||||
coverUrl = cover.url
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
// Per-post work files (inline base64) → stored as gated `files` documents.
|
||||
// Like coverImage, `attachments` is an input transform, not a raw field.
|
||||
// Sending it REPLACES the post's file set; omit it to keep existing files.
|
||||
let attachments: Awaited<ReturnType<typeof resolveAttachments>> = []
|
||||
if ('attachments' in body && body.attachments != null) {
|
||||
try {
|
||||
attachments = await resolveAttachments(payload, body.attachments)
|
||||
data.attachments = attachments.map(a => a.id)
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
// `publish` is an explicit opt-in flag; unpublishing stays admin-only.
|
||||
if (body.publish === true) {
|
||||
data.status = 'published'
|
||||
if (!post.publishedAt) data.publishedAt = new Date().toISOString()
|
||||
}
|
||||
|
||||
let doc
|
||||
try {
|
||||
doc = await payload.update({ collection: 'posts', id: post.id, data, depth: 0 })
|
||||
} catch (err) {
|
||||
// The post write failed — don't orphan the file docs created above
|
||||
// (the post keeps its previous attachments, which are untouched).
|
||||
if (attachments.length) await deleteFileDocs(payload, attachments.map(a => a.id))
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!coverUrl && typeof data.cover === 'number') {
|
||||
const coverDoc: Media = await payload.findByID({ collection: 'media', id: data.cover })
|
||||
coverUrl = coverDoc.url ?? null
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
id: doc.id, title: doc.title, slug: doc.slug,
|
||||
status: doc.status, access: doc.access, category: doc.category,
|
||||
cover: { id: data.cover ?? post.cover, url: coverUrl },
|
||||
attachments: attachments.map(a => ({ id: a.id, filename: a.filename, access: a.access, url: `/api/files/${a.id}` })),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import type { Payload } from 'payload'
|
||||
import type { Media } from '@payload-types'
|
||||
import configPromise from '@payload-config'
|
||||
import { resolveCoverImage } from '@/lib/agent-media'
|
||||
import { resolveAttachments, deleteFileDocs } from '@/lib/agent-files'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
type Body = Record<string, unknown>
|
||||
|
||||
function unauthorized() {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
function validKey(req: NextRequest) {
|
||||
const key = process.env.AGENT_API_KEY
|
||||
if (!key) return false
|
||||
return req.headers.get('x-agent-key') === key
|
||||
}
|
||||
|
||||
/** Fields the agent is allowed to write; status is NEVER included. */
|
||||
function pickFields(body: Body): Body {
|
||||
const allowed = ['title', 'slug', 'dek', 'teaser', 'content', 'category', 'access', 'readingMinutes', 'cover'] as const
|
||||
const out: Body = {}
|
||||
for (const field of allowed) {
|
||||
if (field in body) out[field] = body[field]
|
||||
}
|
||||
// cover omitted → per-category default assigned below (seeded covers)
|
||||
return out
|
||||
}
|
||||
|
||||
const CATEGORY_COVER_SLUGS: Record<string, string> = {
|
||||
'وكلاء': 'cover-agents',
|
||||
'نماذج': 'cover-models',
|
||||
'استرجاع': 'cover-retrieval',
|
||||
'سلامة': 'cover-safety',
|
||||
'أدوات': 'cover-tools',
|
||||
'أعمال': 'cover-business',
|
||||
}
|
||||
|
||||
async function defaultCoverId(payload: Payload, category: unknown) {
|
||||
const filename = CATEGORY_COVER_SLUGS[String(category)] || 'cover-default'
|
||||
const res = await payload.find({
|
||||
collection: 'media',
|
||||
where: { filename: { equals: `${filename}.jpg` } },
|
||||
limit: 1,
|
||||
})
|
||||
return res.docs[0]?.id
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!validKey(req)) return unauthorized()
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const body = (await req.json().catch(() => null)) as Body | null
|
||||
if (!body || typeof body.slug !== 'string' || !body.slug) {
|
||||
return NextResponse.json({ error: 'slug is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Slug conflict → 409
|
||||
const existing = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { slug: { equals: body.slug } },
|
||||
limit: 1,
|
||||
})
|
||||
if (existing.docs.length > 0) {
|
||||
return NextResponse.json({ error: 'slug already exists' }, { status: 409 })
|
||||
}
|
||||
|
||||
const data = pickFields(body)
|
||||
|
||||
// Per-post work files (inline base64) → stored as gated `files` documents.
|
||||
// Like coverImage, `attachments` is an input transform, not a raw field.
|
||||
let attachments: Awaited<ReturnType<typeof resolveAttachments>> = []
|
||||
if ('attachments' in body && body.attachments != null) {
|
||||
try {
|
||||
attachments = await resolveAttachments(payload, body.attachments)
|
||||
data.attachments = attachments.map(a => a.id)
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit image payload (inline base64 or remote URL) → stored as a media document.
|
||||
let coverUrl: string | null = null
|
||||
if ('coverImage' in body && body.coverImage != null) {
|
||||
try {
|
||||
const cover = await resolveCoverImage(payload, body.coverImage)
|
||||
data.cover = cover.id
|
||||
coverUrl = cover.url
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
}
|
||||
if (!data.cover) data.cover = await defaultCoverId(payload, data.category)
|
||||
|
||||
// `publish` is an explicit opt-in flag — the agent still cannot pass `status`
|
||||
// directly (unpublished content requires a deliberate admin action otherwise).
|
||||
const publish = body.publish === true
|
||||
if (publish && !data.publishedAt) data.publishedAt = new Date().toISOString()
|
||||
if (!data.content || typeof data.content !== 'object') {
|
||||
// minimal valid Lexical doc (empty root is rejected by validation); agent PUTs full content later
|
||||
data.content = {
|
||||
root: {
|
||||
type: 'root', format: '', indent: 0, version: 1, direction: 'rtl',
|
||||
children: [{ type: 'paragraph', version: 1, children: [{ type: 'text', version: 1, text: '…' }] }],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let doc
|
||||
try {
|
||||
doc = await payload.create({
|
||||
collection: 'posts',
|
||||
data: { ...data, status: publish ? 'published' : 'draft' },
|
||||
draft: true,
|
||||
depth: 0,
|
||||
})
|
||||
} catch (err) {
|
||||
// The post write failed — don't orphan the file docs created above.
|
||||
if (attachments.length) await deleteFileDocs(payload, attachments.map(a => a.id))
|
||||
return NextResponse.json({ error: (err as Error).message }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!coverUrl && data.cover) {
|
||||
const coverDoc: Media = await payload.findByID({ collection: 'media', id: data.cover as number })
|
||||
coverUrl = coverDoc.url ?? null
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
id: doc.id,
|
||||
title: doc.title,
|
||||
slug: doc.slug,
|
||||
status: doc.status,
|
||||
access: doc.access,
|
||||
category: doc.category,
|
||||
cover: { id: data.cover, url: coverUrl },
|
||||
attachments: attachments.map(a => ({ id: a.id, filename: a.filename, access: a.access, url: `/api/files/${a.id}` })),
|
||||
}, { status: 201 })
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest) {
|
||||
if (!validKey(req)) return unauthorized()
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const slug = req.nextUrl.pathname.split('/').filter(Boolean).pop() as string
|
||||
const body = (await req.json().catch(() => null)) as Body | null
|
||||
if (!body) return NextResponse.json({ error: 'invalid JSON body' }, { status: 400 })
|
||||
|
||||
const existing = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { slug: { equals: slug } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
const post = existing.docs[0]
|
||||
if (!post) return NextResponse.json({ error: 'not found' }, { status: 404 })
|
||||
|
||||
const data = pickFields(body)
|
||||
delete (data as Body).status // agent can never publish/unpublish
|
||||
|
||||
const doc = await payload.update({
|
||||
collection: 'posts',
|
||||
id: post.id,
|
||||
data,
|
||||
depth: 0,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
id: doc.id,
|
||||
title: doc.title,
|
||||
slug: doc.slug,
|
||||
status: doc.status,
|
||||
access: doc.access,
|
||||
category: doc.category,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import { headers } from 'next/headers'
|
||||
import { randomBytes } from 'crypto'
|
||||
import configPromise from '@payload-config'
|
||||
import { sendVerificationEmail } from '@/lib/mail'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* POST /api/auth/resend-verification — logged-in user asks for a fresh
|
||||
verification email. Regenerates the token so old links die. */
|
||||
export async function POST() {
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { user } = await payload.auth({ headers: await headers() })
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
if (user.emailVerified) return NextResponse.json({ already: true })
|
||||
|
||||
const token = randomBytes(32).toString('hex')
|
||||
await payload.update({
|
||||
collection: 'users',
|
||||
id: user.id,
|
||||
data: { verificationToken: token },
|
||||
overrideAccess: true,
|
||||
context: { systemActivation: true },
|
||||
})
|
||||
|
||||
const { sent } = await sendVerificationEmail(user.email, token)
|
||||
if (!sent) {
|
||||
return NextResponse.json(
|
||||
{ error: 'خدمة البريد غير مربوطة بعد — ستعمل تلقائياً بعد ضبط SMTP على الاستضافة.' },
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
return NextResponse.json({ sent: true })
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import { redirect } from 'next/navigation'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* GET /api/auth/verify-email?token=... — the link sent by email.
|
||||
Marks the account verified and lands the user on onboarding. */
|
||||
export async function GET(request: Request) {
|
||||
const token = new URL(request.url).searchParams.get('token')
|
||||
if (!token) redirect('/verify-email?invalid=1')
|
||||
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { docs } = await payload.find({
|
||||
collection: 'users',
|
||||
where: { verificationToken: { equals: token } },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
const user = docs[0]
|
||||
if (!user) redirect('/verify-email?invalid=1')
|
||||
|
||||
await payload.update({
|
||||
collection: 'users',
|
||||
id: user.id,
|
||||
data: { emailVerified: true, verificationToken: null },
|
||||
overrideAccess: true,
|
||||
context: { systemActivation: true },
|
||||
})
|
||||
|
||||
redirect('/onboarding')
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { getPayload } from 'payload'
|
||||
import configPromise from '@payload-config'
|
||||
import { FILES_DIR } from '@/collections/Files'
|
||||
import { getViewer } from '@/lib/viewer'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
type FileDoc = { id: number; access: 'free' | 'vip'; filename: string; mimeType: string }
|
||||
|
||||
/* GET /api/files/[id] — per-post work files, gated per file.
|
||||
`free` streams to anyone; `vip` requires a signed-in vip/admin (same style
|
||||
as the comments route). The Files collection read rule is defense in depth;
|
||||
this route is the enforcement point for the bytes. */
|
||||
export async function GET(_req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await ctx.params
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
|
||||
let doc: FileDoc | null = null
|
||||
try {
|
||||
doc = (await payload.findByID({ collection: 'files', id, depth: 0, overrideAccess: true })) as unknown as FileDoc
|
||||
} catch {
|
||||
doc = null // unknown id / DB error → not found
|
||||
}
|
||||
if (!doc?.filename) return NextResponse.json({ error: 'الملف غير موجود.' }, { status: 404 })
|
||||
|
||||
if (doc.access === 'vip') {
|
||||
const viewer = await getViewer()
|
||||
if (!viewer) return NextResponse.json({ error: 'سجّل الدخول لتنزيل الملفات.' }, { status: 401 })
|
||||
if (viewer.role !== 'vip' && viewer.role !== 'admin') {
|
||||
return NextResponse.json({ error: 'التنزيل متاح لأعضاء العضوية.' }, { status: 403 })
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const buf = await readFile(path.join(FILES_DIR, doc.filename))
|
||||
return new NextResponse(new Uint8Array(buf), {
|
||||
headers: {
|
||||
'Content-Type': doc.mimeType,
|
||||
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(doc.filename)}`,
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
// Row exists but the file is missing on disk — do not leak a fake download.
|
||||
return NextResponse.json({ error: 'الملف غير موجود.' }, { status: 404 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import { headers } from 'next/headers'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* POST /api/posts/[slug]/comments — create a moderated comment.
|
||||
Signed-in only (401); VIP post requires entitlement (403); 1 comment / 60 s
|
||||
per user, counting pending (429); body 8–2000 chars (400).
|
||||
NOTE: deliberately NOT /api/comments — Payload mounts its admin REST there
|
||||
(see docs/adr/0001-comments-route-not-at-api-comments.md). */
|
||||
export async function POST(_request: Request, ctx: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await ctx.params
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { user } = await payload.auth({ headers: await headers() })
|
||||
if (!user) return NextResponse.json({ error: 'سجّل الدخول للتعليق.' }, { status: 401 })
|
||||
|
||||
// Verified-email gate (pentest #7 remediation): admins exempt.
|
||||
const { role, emailVerified } = user as { role?: string; emailVerified?: boolean }
|
||||
if (!emailVerified && role !== 'admin') {
|
||||
return NextResponse.json(
|
||||
{ error: 'أكّد بريدك الإلكتروني قبل التعليق — راجع بريدك الوارد.' },
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = await _request.json().catch(() => null)
|
||||
const text = typeof parsed?.body === 'string' ? parsed.body.trim() : ''
|
||||
if (text.length < 8) return NextResponse.json({ error: 'اكتب تعليقاً من ٨ أحرف على الأقل.' }, { status: 400 })
|
||||
if (text.length > 2000) return NextResponse.json({ error: 'التعليق طويل جداً — ٢٠٠٠ حرف كحد أقصى.' }, { status: 400 })
|
||||
|
||||
const { docs } = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { and: [{ slug: { equals: slug } }, { status: { equals: 'published' } }] },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
})
|
||||
const post = docs[0] as unknown as { id: number; access: string } | undefined
|
||||
if (!post) return NextResponse.json({ error: 'المقال غير موجود.' }, { status: 404 })
|
||||
|
||||
// Mirror the UI paywall: commenting on a VIP post requires entitlement.
|
||||
if (post.access === 'vip' && role !== 'vip' && role !== 'admin') {
|
||||
return NextResponse.json({ error: 'التعليق على هذا الدليل متاح لأعضاء العضوية.' }, { status: 403 })
|
||||
}
|
||||
|
||||
// Naive per-user rate limit: 1 comment / 60 s, any post, counts pending.
|
||||
const recent = await payload.find({
|
||||
collection: 'comments',
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
where: {
|
||||
and: [
|
||||
{ author: { equals: user.id } },
|
||||
{ createdAt: { greater_than: new Date(Date.now() - 60_000) } },
|
||||
],
|
||||
},
|
||||
})
|
||||
if (recent.docs.length) return NextResponse.json({ error: 'تمهّل قليلاً قبل تعليق جديد.' }, { status: 429 })
|
||||
|
||||
const fullName = (user as { fullName?: string }).fullName
|
||||
await payload.create({
|
||||
collection: 'comments',
|
||||
data: { post: post.id, author: user.id, authorName: fullName || 'عضو', body: text, status: 'pending' },
|
||||
overrideAccess: true,
|
||||
})
|
||||
return NextResponse.json({ ok: true, pending: true }, { status: 201 })
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import { headers } from 'next/headers'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* POST /api/posts/[slug]/like — toggle. Login required (401 otherwise);
|
||||
one like per user per post (PostLikes uniqueness); likes counter on post. */
|
||||
export async function POST(_request: Request, ctx: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await ctx.params
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { user } = await payload.auth({ headers: await headers() })
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const { docs } = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { slug: { equals: slug } },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
select: { likes: true },
|
||||
overrideAccess: true,
|
||||
})
|
||||
const post = docs[0]
|
||||
if (!post) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
|
||||
const existing = await payload.find({
|
||||
collection: 'post-likes',
|
||||
where: { and: [{ user: { equals: user.id } }, { post: { equals: post.id } }] },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
|
||||
let liked: boolean
|
||||
if (existing.docs.length > 0) {
|
||||
await payload.delete({ collection: 'post-likes', id: existing.docs[0].id, overrideAccess: true })
|
||||
liked = false
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: 'post-likes',
|
||||
data: { user: user.id, post: post.id },
|
||||
overrideAccess: true,
|
||||
})
|
||||
liked = true
|
||||
}
|
||||
|
||||
const likes = Math.max(0, (typeof post.likes === 'number' ? post.likes : 0) + (liked ? 1 : -1))
|
||||
await payload.update({ collection: 'posts', id: post.id, data: { likes }, overrideAccess: true })
|
||||
return NextResponse.json({ liked, likes })
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import configPromise from '@payload-config'
|
||||
import { REST_DELETE, REST_GET, REST_PATCH, REST_PUT } from '@payloadcms/next/routes'
|
||||
import { getViewer } from '@/lib/viewer'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
type Ctx = { params: Promise<{ slug: string }> }
|
||||
|
||||
const restGet = REST_GET(configPromise)
|
||||
const restPatch = REST_PATCH(configPromise)
|
||||
const restPut = REST_PUT(configPromise)
|
||||
const restDelete = REST_DELETE(configPromise)
|
||||
|
||||
/* Shadows the Payload REST catch-all for /api/posts/:id-or-slug.
|
||||
- Numeric ids: plain REST passthrough — the /admin edit view depends on them.
|
||||
- String slugs: by-slug lookup with the VIP gate, instead of the catch-all
|
||||
casting the slug as an id (postgres error → 500, QA-01).
|
||||
Mutations pass through to REST for numeric ids (the /admin SPA saves via
|
||||
REST PATCH/PUT/DELETE on /api/posts/:id); the collection's own access
|
||||
control still applies. No string-slug mutations exist. */
|
||||
export async function GET(req: NextRequest, ctx: Ctx) {
|
||||
const { slug } = await ctx.params
|
||||
if (/^\d+$/.test(slug)) {
|
||||
return restGet(req, { params: Promise.resolve({ slug: ['posts', slug] }) })
|
||||
}
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
// Published only — drafts must not leak by slug (numeric-id passthrough
|
||||
// stays for the /admin SPA; its read access already constrains it).
|
||||
const { docs } = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { and: [{ slug: { equals: slug } }, { status: { equals: 'published' } }] },
|
||||
depth: 0, limit: 1, overrideAccess: true,
|
||||
})
|
||||
const post = docs[0]
|
||||
if (!post) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
if (post.access === 'vip') {
|
||||
const viewer = await getViewer()
|
||||
if (!viewer) return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
|
||||
if (viewer.role !== 'vip' && viewer.role !== 'admin') {
|
||||
return NextResponse.json({ error: 'VIP membership required' }, { status: 403 })
|
||||
}
|
||||
}
|
||||
return NextResponse.json(post)
|
||||
}
|
||||
|
||||
export async function PATCH(req: NextRequest, ctx: Ctx) {
|
||||
const { slug } = await ctx.params
|
||||
return restPatch(req, { params: Promise.resolve({ slug: ['posts', slug] }) })
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest, ctx: Ctx) {
|
||||
const { slug } = await ctx.params
|
||||
return restPut(req, { params: Promise.resolve({ slug: ['posts', slug] }) })
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest, ctx: Ctx) {
|
||||
const { slug } = await ctx.params
|
||||
return restDelete(req, { params: Promise.resolve({ slug: ['posts', slug] }) })
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* POST /api/posts/[slug]/view — global view counter (client fires this once
|
||||
per browser session per post, from the post page). */
|
||||
export async function POST(_request: Request, ctx: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await ctx.params
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { docs } = await payload.find({
|
||||
collection: 'posts',
|
||||
where: { slug: { equals: slug } },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
select: { views: true },
|
||||
overrideAccess: true,
|
||||
})
|
||||
const post = docs[0]
|
||||
if (!post) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
|
||||
const views = (typeof post.views === 'number' ? post.views : 0) + 1
|
||||
await payload.update({ collection: 'posts', id: post.id, data: { views }, overrideAccess: true })
|
||||
return NextResponse.json({ views })
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server'
|
||||
import configPromise from '@payload-config'
|
||||
import { REST_GET, REST_POST } from '@payloadcms/next/routes'
|
||||
import { getViewer } from '@/lib/viewer'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/* Shadows the Payload REST catch-all for /api/posts: the REST list returned
|
||||
full bodies of all published posts (incl. VIP) to anonymous — a paid-content
|
||||
leak. List reads are now admin-only. Create (POST) stays Payload REST —
|
||||
access.create: isAdmin already rejects non-admins. The app frontend and
|
||||
agent API use the local API / custom routes, never the REST list. */
|
||||
export async function GET(req: NextRequest) {
|
||||
const viewer = await getViewer()
|
||||
if (!viewer) return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
|
||||
if (viewer.role !== 'admin') return NextResponse.json({ error: 'Admin only' }, { status: 403 })
|
||||
return REST_GET(configPromise)(req, { params: Promise.resolve({ slug: ['posts'] }) })
|
||||
}
|
||||
|
||||
export const POST = REST_POST(configPromise)
|
||||
@@ -0,0 +1,64 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import Stripe from 'stripe'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const secret = process.env.STRIPE_SECRET_KEY
|
||||
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET
|
||||
if (!secret || !webhookSecret) {
|
||||
return NextResponse.json({ error: 'Stripe not configured' }, { status: 503 })
|
||||
}
|
||||
|
||||
const stripe = new Stripe(secret)
|
||||
const signature = req.headers.get('stripe-signature')
|
||||
if (!signature) return NextResponse.json({ error: 'Missing signature' }, { status: 400 })
|
||||
|
||||
const rawBody = await req.text()
|
||||
let event: Stripe.Event
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(rawBody, signature, webhookSecret)
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 })
|
||||
}
|
||||
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
|
||||
if (event.type === 'checkout.session.completed') {
|
||||
const session = event.data.object
|
||||
const userId = session.client_reference_id || session.metadata?.payloadUserId
|
||||
if (userId) {
|
||||
await payload.update({
|
||||
collection: 'users',
|
||||
id: userId,
|
||||
data: { role: 'vip' },
|
||||
overrideAccess: true,
|
||||
context: { systemActivation: true },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === 'customer.subscription.deleted') {
|
||||
const subscription = event.data.object
|
||||
const customerId = typeof subscription.customer === 'string' ? subscription.customer : subscription.customer.id
|
||||
const { docs } = await payload.find({
|
||||
collection: 'users',
|
||||
where: { stripeCustomerId: { equals: customerId } },
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
for (const u of docs) {
|
||||
await payload.update({
|
||||
collection: 'users',
|
||||
id: u.id,
|
||||
data: { role: 'free' },
|
||||
overrideAccess: true,
|
||||
context: { systemActivation: true },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ received: true })
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getPayload } from 'payload'
|
||||
import type { Payload } from 'payload'
|
||||
import { headers } from 'next/headers'
|
||||
import Stripe from 'stripe'
|
||||
import configPromise from '@payload-config'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST() {
|
||||
const secret = process.env.STRIPE_SECRET_KEY
|
||||
const priceId = process.env.STRIPE_PRICE_ID
|
||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'
|
||||
|
||||
// Stripe pending mode: no keys yet → subscription is «قريباً» (coming soon).
|
||||
// No VIP is granted without a Stripe-verified session; adding
|
||||
// STRIPE_SECRET_KEY + STRIPE_PRICE_ID switches to real Checkout with the
|
||||
// same success/cancel pages.
|
||||
if (!secret || !priceId) {
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { user } = await payload.auth({ headers: await headers() })
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
return NextResponse.json({ comingSoon: true })
|
||||
}
|
||||
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const { user } = await payload.auth({ headers: await headers() })
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const stripe = new Stripe(secret)
|
||||
let customerId = user.stripeCustomerId as string | undefined
|
||||
if (!customerId) {
|
||||
const customer = await stripe.customers.create({
|
||||
email: user.email,
|
||||
metadata: { payloadUserId: String(user.id) },
|
||||
})
|
||||
customerId = customer.id
|
||||
await payload.update({
|
||||
collection: 'users',
|
||||
id: user.id,
|
||||
data: { stripeCustomerId: customerId },
|
||||
context: { systemActivation: true },
|
||||
})
|
||||
}
|
||||
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
mode: 'subscription',
|
||||
customer: customerId,
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
client_reference_id: String(user.id),
|
||||
success_url: `${siteUrl}/payment-success?session_id={CHECKOUT_SESSION_ID}`,
|
||||
cancel_url: `${siteUrl}/payment-cancelled`,
|
||||
})
|
||||
|
||||
return NextResponse.json({ url: session.url })
|
||||
}
|
||||
Reference in New Issue
Block a user