Allow members to connect and manage their Facebook pages

This commit is contained in:
Loma Bot Ops
2026-11-24 09:43:34 +07:00
parent 7f1a9face1
commit b14a9286cd
9 changed files with 90 additions and 40 deletions
+48 -6
View File
@@ -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 {