diff --git a/README.md b/README.md index 2a5ee49..397a422 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ npm run dev # http://localhost:3000 1. App Dashboard → Facebook Login → Settings → Valid OAuth Redirect URIs: `https:///api/facebook/oauth/callback` (โหมด Development: `http://localhost` ใช้ได้เลยไม่ต้องเพิ่ม; โหมด Live ต้องเป็น HTTPS) 2. โหมด Development: คนที่กด login ต้องมี role ในแอป (Admin/Developer/Tester). โหมด Live: permission ต้องผ่าน App Review (Advanced Access) -3. เข้าระบบด้วย SUPERADMIN → **เพจที่เชื่อม** → **เข้าสู่ระบบด้วย Facebook** → อนุญาต + เลือกเพจ → กลับมาเลือกเพจแล้วกดเชื่อม +3. ผู้ใช้ที่ล็อกอินแล้ว (รวม `MEMBER`) → **เพจที่เชื่อม** → **เข้าสู่ระบบด้วย Facebook** → อนุญาต + เลือกเพจ → กลับมาเลือกเพจแล้วกดเชื่อม; `MEMBER` จะเห็นเฉพาะบัญชี Facebook ของตนและได้สิทธิ์ `MANAGER` เมื่อ Facebook ยืนยันว่ามีงาน `MANAGE` หรือสิทธิ์จัดการเต็มรูปแบบ 4. Webhooks (รับ inbox/คอมเมนต์) ต้องเป็น HTTPS สาธารณะ: callback `https:///api/webhooks/meta` - Page: subscribe `messages`, `messaging_postbacks`, `feed` · Instagram: `messages`, `comments` - ระบบ subscribe แต่ละเพจให้เองตอนกดเชื่อม diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ebdf3fe..7660242 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -59,7 +59,7 @@ prisma/schema.prisma ขั้นตอน: -1. **List** — `GET /api/pages?available=1` เรียก `/me/accounts?fields=id,name,picture,access_token,instagram_business_account` จากทุกแหล่ง (แหล่งไหนพังรายงานเป็น `errors` ไม่ล้มทั้งหมด) +1. **List** — `GET /api/pages?available=1` เรียก `/me/accounts?fields=id,name,picture,access_token,instagram_business_account` เฉพาะ Facebook connection ของผู้ใช้; `SUPERADMIN` เห็นทุกแหล่งรวม system user (แหล่งไหนพังรายงานเป็น `errors` ไม่ล้มทั้งหมด) 2. **Connect** — upsert `Page` เก็บ page token แบบเข้ารหัส (`tokenBox`, AES-256-GCM, key `TOKEN_ENCRYPTION_KEY`) + `connectionId` ว่ามาจากบัญชีไหน 3. **Subscribe** — `POST /{page-id}/subscribed_apps` ด้วย page token 4. **Health** — `debug_token` ใช้ app token (`APP_ID|APP_SECRET`) เป็น inspector; cron รายวัน + ปุ่มในหน้าเพจ @@ -133,6 +133,7 @@ model PostInsightSnapshot { postId, date @db.Date, impressions, engaged, reactio - session จาก social login ไม่บังคับเปลี่ยนรหัสผ่านชั่วคราว (ไม่ได้ใช้รหัสนั้น); flag `mustChangePassword` ใน DB ยังอยู่สำหรับการเข้าด้วยรหัสผ่าน - Facebook ปุ่มนี้ขอแค่ `email,public_profile` คนละ flow กับ "เชื่อมเพจ" (`lib/facebook/oauth.ts`) — ไม่เก็บ token ของ provider +- `MEMBER` เชื่อม Facebook ของตนและเลือกเพจที่บัญชีนั้นมีงาน `MANAGE` หรือสิทธิ์จัดการเต็มรูปแบบ เมื่อเชื่อมจะได้ `PageMember: MANAGER` ของเพจนั้น; เพจที่เชื่อมอยู่แล้วเพิ่มสิทธิ์ให้ผู้เชื่อมโดยไม่เขียนทับ token เดิม - `SUPERADMIN` เข้าได้ทุกเพจ + เชื่อม/ถอดเพจ + จัดการผู้ใช้ - **Separation of duty**: คนที่แก้ล่าสุดอนุมัติโพสต์ตัวเองไม่ได้ (ยกเว้น SUPERADMIN และต้องบันทึกใน AuditLog ว่าอนุมัติงานตัวเอง) - แก้ caption/รูปหลังอนุมัติ → ลบ `PostApproval` ทั้งหมด กลับเป็น `PENDING_APPROVAL` diff --git a/src/app/(console)/pages/page.tsx b/src/app/(console)/pages/page.tsx index 26863fb..74bce18 100644 --- a/src/app/(console)/pages/page.tsx +++ b/src/app/(console)/pages/page.tsx @@ -23,12 +23,11 @@ export default async function PagesPage(props: PageProps<"/pages">) { }, orderBy: { name: "asc" }, }); - const connections = superadmin - ? await prisma.metaConnection.findMany({ - select: { id: true, name: true, scopes: true, expiresAt: true, _count: { select: { pages: true } } }, - orderBy: { createdAt: "asc" }, - }) - : []; + const connections = await prisma.metaConnection.findMany({ + where: superadmin ? undefined : { connectedById: ctx.user.id }, + select: { id: true, name: true, scopes: true, expiresAt: true, _count: { select: { pages: true } } }, + orderBy: { createdAt: "asc" }, + }); const roleOf = new Map(ctx.pages.map((p) => [p.id, p.role])); return ( diff --git a/src/app/api/facebook/connections/route.ts b/src/app/api/facebook/connections/route.ts index 958648b..b3d6491 100644 --- a/src/app/api/facebook/connections/route.ts +++ b/src/app/api/facebook/connections/route.ts @@ -1,17 +1,18 @@ import { NextResponse } from "next/server"; import { prisma } from "@/lib/db"; -import { actorLabel, requireSuperadmin } from "@/lib/auth/user"; +import { actorLabel, requireUser } from "@/lib/auth/user"; import { audit } from "@/lib/audit"; /** Facebook logins that can supply pages. Tokens never leave the server. */ export async function GET() { - const auth = await requireSuperadmin(); + const auth = await requireUser(); if (!auth.ok) return auth.response; const connections = await prisma.metaConnection.findMany({ + where: auth.user.globalRole === "SUPERADMIN" ? undefined : { connectedById: auth.user.id }, select: { id: true, name: true, scopes: true, expiresAt: true, updatedAt: true, _count: { select: { pages: true } } }, orderBy: { createdAt: "asc" }, }); - return NextResponse.json({ connections, systemUser: Boolean(process.env.META_SYSTEM_USER_TOKEN) }); + return NextResponse.json({ connections, systemUser: auth.user.globalRole === "SUPERADMIN" && Boolean(process.env.META_SYSTEM_USER_TOKEN) }); } /** @@ -19,11 +20,12 @@ export async function GET() { * and keep working; only re-listing pages from this login stops. */ export async function DELETE(req: Request) { - const auth = await requireSuperadmin(); + const auth = await requireUser(); if (!auth.ok) return auth.response; const id = new URL(req.url).searchParams.get("id") ?? ""; - const conn = await prisma.metaConnection.findUnique({ where: { id }, select: { name: true } }); + const conn = await prisma.metaConnection.findUnique({ where: { id }, select: { name: true, connectedById: true } }); if (!conn) return NextResponse.json({ error: "ไม่พบการเชื่อมนี้" }, { status: 404 }); + if (auth.user.globalRole !== "SUPERADMIN" && conn.connectedById !== auth.user.id) return NextResponse.json({ error: "ไม่พบการเชื่อมนี้" }, { status: 404 }); await prisma.metaConnection.delete({ where: { id } }); await audit({ action: "META_LOGIN_REMOVED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { name: conn.name } }); return NextResponse.json({ ok: true }); diff --git a/src/app/api/facebook/oauth/callback/route.ts b/src/app/api/facebook/oauth/callback/route.ts index 3a0dd41..d9a52ba 100644 --- a/src/app/api/facebook/oauth/callback/route.ts +++ b/src/app/api/facebook/oauth/callback/route.ts @@ -28,8 +28,8 @@ export async function GET(req: Request) { const userId = await verifyOAuthState(stateCookie, url.searchParams.get("state")); if (!userId) return hop(`/pages?fb_error=${encodeURIComponent("ลิงก์เชื่อมหมดอายุหรือไม่ถูกต้อง ลองกดเชื่อมใหม่")}`); - const user = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, name: true, email: true, isActive: true, globalRole: true } }); - if (!user?.isActive || user.globalRole !== "SUPERADMIN") return hop("/pages?fb_error=forbidden"); + const user = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, name: true, email: true, isActive: true } }); + if (!user?.isActive) return hop("/pages?fb_error=forbidden"); const fbError = url.searchParams.get("error_description") ?? url.searchParams.get("error"); if (fbError) return hop(`/pages?fb_error=${encodeURIComponent(`Facebook: ${fbError}`)}`); @@ -39,6 +39,10 @@ export async function GET(req: Request) { try { const r = await exchangeCode(url.origin, code); + const existing = await prisma.metaConnection.findUnique({ where: { fbUserId: r.fbUserId }, select: { connectedById: true } }); + if (existing && existing.connectedById !== user.id) { + return hop(`/pages?fb_error=${encodeURIComponent("บัญชี Facebook นี้เชื่อมกับผู้ใช้อื่นแล้ว ให้ผู้จัดการเพจเพิ่มสิทธิ์คุณแทน")}`); + } const conn = await prisma.metaConnection.upsert({ where: { fbUserId: r.fbUserId }, create: { fbUserId: r.fbUserId, name: r.name, tokenCipher: encryptToken(r.token), scopes: r.scopes, expiresAt: r.expiresAt, connectedById: user.id }, diff --git a/src/app/api/facebook/oauth/start/route.ts b/src/app/api/facebook/oauth/start/route.ts index f32a8d6..04af95a 100644 --- a/src/app/api/facebook/oauth/start/route.ts +++ b/src/app/api/facebook/oauth/start/route.ts @@ -1,16 +1,16 @@ import { BASE_PATH, appUrl } from "@/lib/base-path"; import { NextResponse } from "next/server"; -import { getCurrentUser, isSuperadmin } from "@/lib/auth/user"; +import { getCurrentUser } from "@/lib/auth/user"; import { authorizeUrl, createOAuthState, OAUTH_STATE_COOKIE } from "@/lib/facebook/oauth"; import { safeFacebookErrorMessage } from "@/lib/facebook/client"; import { externalRedirect } from "@/lib/http"; -/** SUPERADMIN only: redirects to the Facebook consent dialog. */ +/** Any signed-in user may connect their own Facebook account. */ export async function GET(req: Request) { const origin = new URL(req.url).origin; const root = appUrl(origin); const user = await getCurrentUser(); - if (!user || !isSuperadmin(user)) return NextResponse.redirect(`${root}/pages?fb_error=forbidden`); + if (!user) return NextResponse.redirect(`${root}/login`); try { const { nonce, cookie } = await createOAuthState(user.id); diff --git a/src/app/api/pages/route.ts b/src/app/api/pages/route.ts index d0aef1b..d5fa730 100644 --- a/src/app/api/pages/route.ts +++ b/src/app/api/pages/route.ts @@ -1,6 +1,6 @@ import { NextResponse } from "next/server"; import { prisma } from "@/lib/db"; -import { pageScope, requireSuperadmin, requireUser, actorLabel } from "@/lib/auth/user"; +import { pageScope, requireUser, actorLabel } from "@/lib/auth/user"; import { listAvailablePages, subscribePageWebhook } from "@/lib/facebook/pages"; import { encryptToken } from "@/lib/crypto/tokenBox"; import { forgetPageToken, getPageSources } from "@/lib/facebook/tokens"; @@ -20,7 +20,7 @@ const PAGE_SELECT = { tokenCheckedAt: true, } as const; -/** Pages the caller can see. `?available=1` (SUPERADMIN) also lists pages connectable from every token source. */ +/** Pages the caller can see. `?available=1` lists pages from their permitted token sources. */ export async function GET(req: Request) { const auth = await requireUser(); if (!auth.ok) return auth.response; @@ -31,12 +31,12 @@ export async function GET(req: Request) { orderBy: { name: "asc" }, }); - if (new URL(req.url).searchParams.get("available") !== "1" || auth.user.globalRole !== "SUPERADMIN") { + if (new URL(req.url).searchParams.get("available") !== "1") { return NextResponse.json({ pages }); } try { - const sources = await getPageSources(); + const sources = await getPageSources(auth.user); if (sources.length === 0) return NextResponse.json({ pages, available: [], errors: [], noSource: true }); const { pages: available, errors } = await listAvailablePages(sources); const connected = new Set(pages.map((p) => p.fbPageId)); @@ -49,6 +49,7 @@ export async function GET(req: Request) { pictureUrl: a.pictureUrl, igUsername: a.igUsername, connected: connected.has(a.fbPageId), + canManage: auth.user.globalRole === "SUPERADMIN" || a.tasks.some((task) => ["MANAGE", "PROFILE_PLUS_FULL_CONTROL", "PROFILE_PLUS_MANAGE"].includes(task)), via: sources.find((x) => x.connectionId === a.connectionId)?.label ?? null, })), }); @@ -62,7 +63,7 @@ export async function GET(req: Request) { * from /me/accounts — never accepted from the client. */ export async function POST(req: Request) { - const auth = await requireSuperadmin(); + const auth = await requireUser(); if (!auth.ok) return auth.response; const body = await readJson(req); @@ -70,7 +71,7 @@ export async function POST(req: Request) { if (ids.length === 0) return NextResponse.json({ error: "เลือกเพจอย่างน้อยหนึ่งเพจ" }, { status: 400 }); try { - const { pages: available } = await listAvailablePages(await getPageSources()); + const { pages: available } = await listAvailablePages(await getPageSources(auth.user)); const results: { fbPageId: string; name: string; ok: boolean; webhook: boolean; error?: string }[] = []; for (const fbPageId of ids) { @@ -79,6 +80,40 @@ export async function POST(req: Request) { results.push({ fbPageId, name: fbPageId, ok: false, webhook: false, error: "บัญชีที่เชื่อมไว้เข้าถึงเพจนี้ไม่ได้" }); continue; } + if (auth.user.globalRole !== "SUPERADMIN" && !a.tasks.some((task) => ["MANAGE", "PROFILE_PLUS_FULL_CONTROL", "PROFILE_PLUS_MANAGE"].includes(task))) { + results.push({ fbPageId, name: a.name, ok: false, webhook: false, error: "บัญชี Facebook นี้ไม่มีสิทธิ์จัดการเพจเต็มรูปแบบ ให้แอดมินเพจเพิ่มสิทธิ์ก่อน" }); + continue; + } + const prior = await prisma.page.findUnique({ where: { fbPageId }, select: { id: true, status: true, webhookSubscribedAt: true } }); + if (prior && auth.user.globalRole !== "SUPERADMIN") { + const refreshToken = prior.status !== "ACTIVE"; + if (refreshToken) { + await prisma.page.update({ + where: { id: prior.id }, + data: { name: a.name, pictureUrl: a.pictureUrl, igUserId: a.igUserId, igUsername: a.igUsername, tokenCipher: encryptToken(a.accessToken), connectionId: a.connectionId, status: "ACTIVE", statusDetail: null }, + }); + forgetPageToken(prior.id); + } + await prisma.pageMember.upsert({ + where: { userId_pageId: { userId: auth.user.id, pageId: prior.id } }, + create: { userId: auth.user.id, pageId: prior.id, role: "MANAGER" }, + update: { role: "MANAGER" }, + }); + await audit({ action: refreshToken ? "PAGE_CONNECTED" : "PAGE_MEMBER_SET", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId: prior.id, detail: { userId: auth.user.id, role: "MANAGER", source: "FACEBOOK_LOGIN" } }); + let webhook = Boolean(prior.webhookSubscribedAt); + if (refreshToken) { + try { + await subscribePageWebhook(fbPageId, a.accessToken); + await prisma.page.update({ where: { id: prior.id }, data: { webhookSubscribedAt: new Date() } }); + webhook = true; + } catch (e) { + console.error(`[pages:connect] webhook subscribe failed page=${fbPageId}`, e); + webhook = false; + } + } + results.push({ fbPageId, name: a.name, ok: true, webhook }); + continue; + } const page = await prisma.page.upsert({ where: { fbPageId }, create: { @@ -102,6 +137,13 @@ export async function POST(req: Request) { }, }); forgetPageToken(page.id); + if (auth.user.globalRole !== "SUPERADMIN") { + await prisma.pageMember.upsert({ + where: { userId_pageId: { userId: auth.user.id, pageId: page.id } }, + create: { userId: auth.user.id, pageId: page.id, role: "MANAGER" }, + update: { role: "MANAGER" }, + }); + } let webhook = false; try { diff --git a/src/components/PagesManager.tsx b/src/components/PagesManager.tsx index d46cd2d..5680c99 100644 --- a/src/components/PagesManager.tsx +++ b/src/components/PagesManager.tsx @@ -29,6 +29,7 @@ interface Available { pictureUrl: string | null; igUsername: string | null; connected: boolean; + canManage: boolean; via: string | null; } @@ -117,12 +118,12 @@ export function PagesManager({ } setAvailable(data.available); setSourceErrors(data.errors ?? []); - setPicked(data.available.filter((a) => !a.connected).map((a) => a.fbPageId)); + setPicked(data.available.filter((a) => !a.connected && a.canManage).map((a) => a.fbPageId)); } // Right after "Login with Facebook" returns, list the pages straight away. useEffect(() => { - if (!justConnected || !superadmin) return; + if (!justConnected) return; let alive = true; api<{ available: Available[]; errors: string[]; noSource?: boolean }>("/api/pages?available=1").then((r) => { if (!alive) return; @@ -132,7 +133,7 @@ export function PagesManager({ return () => { alive = false; }; - }, [justConnected, superadmin]); + }, [justConnected]); async function removeConnection(c: Connection) { if (!window.confirm(`เลิกใช้บัญชี Facebook "${c.name}"? เพจที่เชื่อมแล้วยังทำงานต่อได้ แต่จะดึงรายชื่อเพจจากบัญชีนี้ไม่ได้`)) return; @@ -206,8 +207,7 @@ export function PagesManager({ {error && {error}} {flash && {flash}} - {superadmin && ( -
+

บัญชี Facebook

{appConfigured ? ( @@ -258,20 +258,17 @@ export function PagesManager({ )} )} -
- )} +

เพจ ({pages.length})

- {superadmin && ( - - )} +
{pages.length === 0 ? ( - + ) : (
    {pages.map((p) => ( @@ -330,6 +327,7 @@ export function PagesManager({ diff --git a/src/lib/facebook/tokens.ts b/src/lib/facebook/tokens.ts index b7837c8..494e721 100644 --- a/src/lib/facebook/tokens.ts +++ b/src/lib/facebook/tokens.ts @@ -49,11 +49,14 @@ export function forgetPageToken(pageId: string) { } /** Every token source for listing pages: system user (env, optional) + each Facebook login connection. */ -export async function getPageSources(): Promise { +export async function getPageSources(user: { id: string; globalRole: string }): Promise { const sources: PageSource[] = []; - const sys = systemUserSource(); + const sys = user.globalRole === "SUPERADMIN" ? systemUserSource() : null; if (sys) sources.push(sys); - const connections = await prisma.metaConnection.findMany({ orderBy: { createdAt: "asc" } }); + const connections = await prisma.metaConnection.findMany({ + where: user.globalRole === "MEMBER" ? { connectedById: user.id } : undefined, + orderBy: { createdAt: "asc" }, + }); for (const c of connections) { sources.push({ connectionId: c.id, label: c.name, token: decryptToken(c.tokenCipher) }); }