Allow members to connect and manage their Facebook pages
This commit is contained in:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user