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
+1 -1
View File
@@ -55,7 +55,7 @@ npm run dev # http://localhost:3000
1. App Dashboard → Facebook Login → Settings → Valid OAuth Redirect URIs: `https://<domain>/api/facebook/oauth/callback` 1. App Dashboard → Facebook Login → Settings → Valid OAuth Redirect URIs: `https://<domain>/api/facebook/oauth/callback`
(โหมด Development: `http://localhost` ใช้ได้เลยไม่ต้องเพิ่ม; โหมด Live ต้องเป็น HTTPS) (โหมด Development: `http://localhost` ใช้ได้เลยไม่ต้องเพิ่ม; โหมด Live ต้องเป็น HTTPS)
2. โหมด Development: คนที่กด login ต้องมี role ในแอป (Admin/Developer/Tester). โหมด Live: permission ต้องผ่าน App Review (Advanced Access) 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://<domain>/api/webhooks/meta` 4. Webhooks (รับ inbox/คอมเมนต์) ต้องเป็น HTTPS สาธารณะ: callback `https://<domain>/api/webhooks/meta`
- Page: subscribe `messages`, `messaging_postbacks`, `feed` · Instagram: `messages`, `comments` - Page: subscribe `messages`, `messaging_postbacks`, `feed` · Instagram: `messages`, `comments`
- ระบบ subscribe แต่ละเพจให้เองตอนกดเชื่อม - ระบบ subscribe แต่ละเพจให้เองตอนกดเชื่อม
+2 -1
View File
@@ -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` ว่ามาจากบัญชีไหน 2. **Connect** — upsert `Page` เก็บ page token แบบเข้ารหัส (`tokenBox`, AES-256-GCM, key `TOKEN_ENCRYPTION_KEY`) + `connectionId` ว่ามาจากบัญชีไหน
3. **Subscribe** — `POST /{page-id}/subscribed_apps` ด้วย page token 3. **Subscribe** — `POST /{page-id}/subscribed_apps` ด้วย page token
4. **Health** — `debug_token` ใช้ app token (`APP_ID|APP_SECRET`) เป็น inspector; cron รายวัน + ปุ่มในหน้าเพจ 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 ยังอยู่สำหรับการเข้าด้วยรหัสผ่าน - session จาก social login ไม่บังคับเปลี่ยนรหัสผ่านชั่วคราว (ไม่ได้ใช้รหัสนั้น); flag `mustChangePassword` ใน DB ยังอยู่สำหรับการเข้าด้วยรหัสผ่าน
- Facebook ปุ่มนี้ขอแค่ `email,public_profile` คนละ flow กับ "เชื่อมเพจ" (`lib/facebook/oauth.ts`) — ไม่เก็บ token ของ provider - Facebook ปุ่มนี้ขอแค่ `email,public_profile` คนละ flow กับ "เชื่อมเพจ" (`lib/facebook/oauth.ts`) — ไม่เก็บ token ของ provider
- `MEMBER` เชื่อม Facebook ของตนและเลือกเพจที่บัญชีนั้นมีงาน `MANAGE` หรือสิทธิ์จัดการเต็มรูปแบบ เมื่อเชื่อมจะได้ `PageMember: MANAGER` ของเพจนั้น; เพจที่เชื่อมอยู่แล้วเพิ่มสิทธิ์ให้ผู้เชื่อมโดยไม่เขียนทับ token เดิม
- `SUPERADMIN` เข้าได้ทุกเพจ + เชื่อม/ถอดเพจ + จัดการผู้ใช้ - `SUPERADMIN` เข้าได้ทุกเพจ + เชื่อม/ถอดเพจ + จัดการผู้ใช้
- **Separation of duty**: คนที่แก้ล่าสุดอนุมัติโพสต์ตัวเองไม่ได้ (ยกเว้น SUPERADMIN และต้องบันทึกใน AuditLog ว่าอนุมัติงานตัวเอง) - **Separation of duty**: คนที่แก้ล่าสุดอนุมัติโพสต์ตัวเองไม่ได้ (ยกเว้น SUPERADMIN และต้องบันทึกใน AuditLog ว่าอนุมัติงานตัวเอง)
- แก้ caption/รูปหลังอนุมัติ → ลบ `PostApproval` ทั้งหมด กลับเป็น `PENDING_APPROVAL` - แก้ caption/รูปหลังอนุมัติ → ลบ `PostApproval` ทั้งหมด กลับเป็น `PENDING_APPROVAL`
+5 -6
View File
@@ -23,12 +23,11 @@ export default async function PagesPage(props: PageProps<"/pages">) {
}, },
orderBy: { name: "asc" }, orderBy: { name: "asc" },
}); });
const connections = superadmin const connections = await prisma.metaConnection.findMany({
? await prisma.metaConnection.findMany({ where: superadmin ? undefined : { connectedById: ctx.user.id },
select: { id: true, name: true, scopes: true, expiresAt: true, _count: { select: { pages: true } } }, select: { id: true, name: true, scopes: true, expiresAt: true, _count: { select: { pages: true } } },
orderBy: { createdAt: "asc" }, orderBy: { createdAt: "asc" },
}) });
: [];
const roleOf = new Map(ctx.pages.map((p) => [p.id, p.role])); const roleOf = new Map(ctx.pages.map((p) => [p.id, p.role]));
return ( return (
+7 -5
View File
@@ -1,17 +1,18 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { prisma } from "@/lib/db"; import { prisma } from "@/lib/db";
import { actorLabel, requireSuperadmin } from "@/lib/auth/user"; import { actorLabel, requireUser } from "@/lib/auth/user";
import { audit } from "@/lib/audit"; import { audit } from "@/lib/audit";
/** Facebook logins that can supply pages. Tokens never leave the server. */ /** Facebook logins that can supply pages. Tokens never leave the server. */
export async function GET() { export async function GET() {
const auth = await requireSuperadmin(); const auth = await requireUser();
if (!auth.ok) return auth.response; if (!auth.ok) return auth.response;
const connections = await prisma.metaConnection.findMany({ 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 } } }, select: { id: true, name: true, scopes: true, expiresAt: true, updatedAt: true, _count: { select: { pages: true } } },
orderBy: { createdAt: "asc" }, 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. * and keep working; only re-listing pages from this login stops.
*/ */
export async function DELETE(req: Request) { export async function DELETE(req: Request) {
const auth = await requireSuperadmin(); const auth = await requireUser();
if (!auth.ok) return auth.response; if (!auth.ok) return auth.response;
const id = new URL(req.url).searchParams.get("id") ?? ""; 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 (!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 prisma.metaConnection.delete({ where: { id } });
await audit({ action: "META_LOGIN_REMOVED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { name: conn.name } }); await audit({ action: "META_LOGIN_REMOVED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { name: conn.name } });
return NextResponse.json({ ok: true }); return NextResponse.json({ ok: true });
+6 -2
View File
@@ -28,8 +28,8 @@ export async function GET(req: Request) {
const userId = await verifyOAuthState(stateCookie, url.searchParams.get("state")); const userId = await verifyOAuthState(stateCookie, url.searchParams.get("state"));
if (!userId) return hop(`/pages?fb_error=${encodeURIComponent("ลิงก์เชื่อมหมดอายุหรือไม่ถูกต้อง ลองกดเชื่อมใหม่")}`); 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 } }); const user = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, name: true, email: true, isActive: true } });
if (!user?.isActive || user.globalRole !== "SUPERADMIN") return hop("/pages?fb_error=forbidden"); if (!user?.isActive) return hop("/pages?fb_error=forbidden");
const fbError = url.searchParams.get("error_description") ?? url.searchParams.get("error"); const fbError = url.searchParams.get("error_description") ?? url.searchParams.get("error");
if (fbError) return hop(`/pages?fb_error=${encodeURIComponent(`Facebook: ${fbError}`)}`); if (fbError) return hop(`/pages?fb_error=${encodeURIComponent(`Facebook: ${fbError}`)}`);
@@ -39,6 +39,10 @@ export async function GET(req: Request) {
try { try {
const r = await exchangeCode(url.origin, code); 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({ const conn = await prisma.metaConnection.upsert({
where: { fbUserId: r.fbUserId }, where: { fbUserId: r.fbUserId },
create: { fbUserId: r.fbUserId, name: r.name, tokenCipher: encryptToken(r.token), scopes: r.scopes, expiresAt: r.expiresAt, connectedById: user.id }, create: { fbUserId: r.fbUserId, name: r.name, tokenCipher: encryptToken(r.token), scopes: r.scopes, expiresAt: r.expiresAt, connectedById: user.id },
+3 -3
View File
@@ -1,16 +1,16 @@
import { BASE_PATH, appUrl } from "@/lib/base-path"; import { BASE_PATH, appUrl } from "@/lib/base-path";
import { NextResponse } from "next/server"; 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 { authorizeUrl, createOAuthState, OAUTH_STATE_COOKIE } from "@/lib/facebook/oauth";
import { safeFacebookErrorMessage } from "@/lib/facebook/client"; import { safeFacebookErrorMessage } from "@/lib/facebook/client";
import { externalRedirect } from "@/lib/http"; 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) { export async function GET(req: Request) {
const origin = new URL(req.url).origin; const origin = new URL(req.url).origin;
const root = appUrl(origin); const root = appUrl(origin);
const user = await getCurrentUser(); const user = await getCurrentUser();
if (!user || !isSuperadmin(user)) return NextResponse.redirect(`${root}/pages?fb_error=forbidden`); if (!user) return NextResponse.redirect(`${root}/login`);
try { try {
const { nonce, cookie } = await createOAuthState(user.id); const { nonce, cookie } = await createOAuthState(user.id);
+48 -6
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { prisma } from "@/lib/db"; 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 { listAvailablePages, subscribePageWebhook } from "@/lib/facebook/pages";
import { encryptToken } from "@/lib/crypto/tokenBox"; import { encryptToken } from "@/lib/crypto/tokenBox";
import { forgetPageToken, getPageSources } from "@/lib/facebook/tokens"; import { forgetPageToken, getPageSources } from "@/lib/facebook/tokens";
@@ -20,7 +20,7 @@ const PAGE_SELECT = {
tokenCheckedAt: true, tokenCheckedAt: true,
} as const; } 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) { export async function GET(req: Request) {
const auth = await requireUser(); const auth = await requireUser();
if (!auth.ok) return auth.response; if (!auth.ok) return auth.response;
@@ -31,12 +31,12 @@ export async function GET(req: Request) {
orderBy: { name: "asc" }, 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 }); return NextResponse.json({ pages });
} }
try { try {
const sources = await getPageSources(); const sources = await getPageSources(auth.user);
if (sources.length === 0) return NextResponse.json({ pages, available: [], errors: [], noSource: true }); if (sources.length === 0) return NextResponse.json({ pages, available: [], errors: [], noSource: true });
const { pages: available, errors } = await listAvailablePages(sources); const { pages: available, errors } = await listAvailablePages(sources);
const connected = new Set(pages.map((p) => p.fbPageId)); const connected = new Set(pages.map((p) => p.fbPageId));
@@ -49,6 +49,7 @@ export async function GET(req: Request) {
pictureUrl: a.pictureUrl, pictureUrl: a.pictureUrl,
igUsername: a.igUsername, igUsername: a.igUsername,
connected: connected.has(a.fbPageId), 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, 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. * from /me/accounts — never accepted from the client.
*/ */
export async function POST(req: Request) { export async function POST(req: Request) {
const auth = await requireSuperadmin(); const auth = await requireUser();
if (!auth.ok) return auth.response; if (!auth.ok) return auth.response;
const body = await readJson(req); 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 }); if (ids.length === 0) return NextResponse.json({ error: "เลือกเพจอย่างน้อยหนึ่งเพจ" }, { status: 400 });
try { 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 }[] = []; const results: { fbPageId: string; name: string; ok: boolean; webhook: boolean; error?: string }[] = [];
for (const fbPageId of ids) { 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: "บัญชีที่เชื่อมไว้เข้าถึงเพจนี้ไม่ได้" }); results.push({ fbPageId, name: fbPageId, ok: false, webhook: false, error: "บัญชีที่เชื่อมไว้เข้าถึงเพจนี้ไม่ได้" });
continue; 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({ const page = await prisma.page.upsert({
where: { fbPageId }, where: { fbPageId },
create: { create: {
@@ -102,6 +137,13 @@ export async function POST(req: Request) {
}, },
}); });
forgetPageToken(page.id); 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; let webhook = false;
try { try {
+12 -13
View File
@@ -29,6 +29,7 @@ interface Available {
pictureUrl: string | null; pictureUrl: string | null;
igUsername: string | null; igUsername: string | null;
connected: boolean; connected: boolean;
canManage: boolean;
via: string | null; via: string | null;
} }
@@ -117,12 +118,12 @@ export function PagesManager({
} }
setAvailable(data.available); setAvailable(data.available);
setSourceErrors(data.errors ?? []); 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. // Right after "Login with Facebook" returns, list the pages straight away.
useEffect(() => { useEffect(() => {
if (!justConnected || !superadmin) return; if (!justConnected) return;
let alive = true; let alive = true;
api<{ available: Available[]; errors: string[]; noSource?: boolean }>("/api/pages?available=1").then((r) => { api<{ available: Available[]; errors: string[]; noSource?: boolean }>("/api/pages?available=1").then((r) => {
if (!alive) return; if (!alive) return;
@@ -132,7 +133,7 @@ export function PagesManager({
return () => { return () => {
alive = false; alive = false;
}; };
}, [justConnected, superadmin]); }, [justConnected]);
async function removeConnection(c: Connection) { async function removeConnection(c: Connection) {
if (!window.confirm(`เลิกใช้บัญชี Facebook "${c.name}"? เพจที่เชื่อมแล้วยังทำงานต่อได้ แต่จะดึงรายชื่อเพจจากบัญชีนี้ไม่ได้`)) return; if (!window.confirm(`เลิกใช้บัญชี Facebook "${c.name}"? เพจที่เชื่อมแล้วยังทำงานต่อได้ แต่จะดึงรายชื่อเพจจากบัญชีนี้ไม่ได้`)) return;
@@ -206,8 +207,7 @@ export function PagesManager({
{error && <Notice tone="red">{error}</Notice>} {error && <Notice tone="red">{error}</Notice>}
{flash && <Notice tone="blue">{flash}</Notice>} {flash && <Notice tone="blue">{flash}</Notice>}
{superadmin && ( <section className="card">
<section className="card">
<div className="card-head"> <div className="card-head">
<h2>บัญชี Facebook</h2> <h2>บัญชี Facebook</h2>
{appConfigured ? ( {appConfigured ? (
@@ -258,20 +258,17 @@ export function PagesManager({
)} )}
</ul> </ul>
)} )}
</section> </section>
)}
<section className="card"> <section className="card">
<div className="card-head"> <div className="card-head">
<h2>เพจ ({pages.length})</h2> <h2>เพจ ({pages.length})</h2>
{superadmin && ( <button type="button" className="btn btn-primary btn-sm ml-auto" disabled={busy === "available"} onClick={loadAvailable}>
<button type="button" className="btn btn-primary btn-sm ml-auto" disabled={busy === "available"} onClick={loadAvailable}> <Icon name="plus" size={14} /> {busy === "available" ? "กำลังดึงรายชื่อเพจ…" : "เชื่อมเพจ"}
<Icon name="plus" size={14} /> {busy === "available" ? "กำลังดึงรายชื่อเพจ…" : "เชื่อมเพจ"} </button>
</button>
)}
</div> </div>
{pages.length === 0 ? ( {pages.length === 0 ? (
<EmptyState icon="pages" title="ยังไม่มีเพจ" hint={superadmin ? "เข้าสู่ระบบด้วย Facebook แล้วเลือกเพจที่จะจัดการ" : "ขอให้ผู้ดูแลระบบเพิ่มคุณเป็นสมาชิกเพจ"} /> <EmptyState icon="pages" title="ยังไม่มีเพจ" hint="เชื่อมบัญชี Facebook ของคุณแล้วเลือกเพจ หรือให้ผู้จัดการเพจเพิ่มสิทธิ์คุณ" />
) : ( ) : (
<ul> <ul>
{pages.map((p) => ( {pages.map((p) => (
@@ -330,6 +327,7 @@ export function PagesManager({
<label className="flex items-center gap-3 px-[18px] py-3 border-b border-line-2 cursor-pointer hover:bg-board"> <label className="flex items-center gap-3 px-[18px] py-3 border-b border-line-2 cursor-pointer hover:bg-board">
<input <input
type="checkbox" type="checkbox"
disabled={!a.canManage}
checked={picked.includes(a.fbPageId)} checked={picked.includes(a.fbPageId)}
onChange={(e) => setPicked((cur) => (e.target.checked ? [...cur, a.fbPageId] : cur.filter((x) => x !== a.fbPageId)))} onChange={(e) => setPicked((cur) => (e.target.checked ? [...cur, a.fbPageId] : cur.filter((x) => x !== a.fbPageId)))}
/> />
@@ -341,6 +339,7 @@ export function PagesManager({
{a.via && <> · ผ่าน {a.via}</>} {a.via && <> · ผ่าน {a.via}</>}
</span> </span>
</span> </span>
{!a.canManage && <span className="text-[12px] text-ink-3">ต้องมีสิทธิ์จัดการเพจบน Facebook</span>}
{a.connected && <span className="pill pill-blue">เชื่อมแล้ว (กดเพื่อรีเฟรช token)</span>} {a.connected && <span className="pill pill-blue">เชื่อมแล้ว (กดเพื่อรีเฟรช token)</span>}
</label> </label>
</li> </li>
+6 -3
View File
@@ -49,11 +49,14 @@ export function forgetPageToken(pageId: string) {
} }
/** Every token source for listing pages: system user (env, optional) + each Facebook login connection. */ /** Every token source for listing pages: system user (env, optional) + each Facebook login connection. */
export async function getPageSources(): Promise<PageSource[]> { export async function getPageSources(user: { id: string; globalRole: string }): Promise<PageSource[]> {
const sources: PageSource[] = []; const sources: PageSource[] = [];
const sys = systemUserSource(); const sys = user.globalRole === "SUPERADMIN" ? systemUserSource() : null;
if (sys) sources.push(sys); 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) { for (const c of connections) {
sources.push({ connectionId: c.id, label: c.name, token: decryptToken(c.tokenCipher) }); sources.push({ connectionId: c.id, label: c.name, token: decryptToken(c.tokenCipher) });
} }