Allow members to connect and manage their Facebook pages
This commit is contained in:
@@ -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 (
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 && <Notice tone="red">{error}</Notice>}
|
||||
{flash && <Notice tone="blue">{flash}</Notice>}
|
||||
|
||||
{superadmin && (
|
||||
<section className="card">
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>บัญชี Facebook</h2>
|
||||
{appConfigured ? (
|
||||
@@ -258,20 +258,17 @@ export function PagesManager({
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>เพจ ({pages.length})</h2>
|
||||
{superadmin && (
|
||||
<button type="button" className="btn btn-primary btn-sm ml-auto" disabled={busy === "available"} onClick={loadAvailable}>
|
||||
<Icon name="plus" size={14} /> {busy === "available" ? "กำลังดึงรายชื่อเพจ…" : "เชื่อมเพจ"}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-primary btn-sm ml-auto" disabled={busy === "available"} onClick={loadAvailable}>
|
||||
<Icon name="plus" size={14} /> {busy === "available" ? "กำลังดึงรายชื่อเพจ…" : "เชื่อมเพจ"}
|
||||
</button>
|
||||
</div>
|
||||
{pages.length === 0 ? (
|
||||
<EmptyState icon="pages" title="ยังไม่มีเพจ" hint={superadmin ? "เข้าสู่ระบบด้วย Facebook แล้วเลือกเพจที่จะจัดการ" : "ขอให้ผู้ดูแลระบบเพิ่มคุณเป็นสมาชิกเพจ"} />
|
||||
<EmptyState icon="pages" title="ยังไม่มีเพจ" hint="เชื่อมบัญชี Facebook ของคุณแล้วเลือกเพจ หรือให้ผู้จัดการเพจเพิ่มสิทธิ์คุณ" />
|
||||
) : (
|
||||
<ul>
|
||||
{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">
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={!a.canManage}
|
||||
checked={picked.includes(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}</>}
|
||||
</span>
|
||||
</span>
|
||||
{!a.canManage && <span className="text-[12px] text-ink-3">ต้องมีสิทธิ์จัดการเพจบน Facebook</span>}
|
||||
{a.connected && <span className="pill pill-blue">เชื่อมแล้ว (กดเพื่อรีเฟรช token)</span>}
|
||||
</label>
|
||||
</li>
|
||||
|
||||
@@ -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<PageSource[]> {
|
||||
export async function getPageSources(user: { id: string; globalRole: string }): Promise<PageSource[]> {
|
||||
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) });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user