haixunMaster/app/api/threads/oauth/authorize/route.ts

47 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2026-06-21 12:50:31 +00:00
import { NextResponse } from "next/server";
import { getOrCreateSettings } from "@/lib/user-settings";
import { getActiveAccountId } from "@/lib/account-context";
import { buildThreadsOAuthUrl, getAppBaseUrl, getThreadsAppId } from "@/lib/threads-api";
export async function GET(request: Request) {
let homeUrl: URL;
try {
homeUrl = new URL("/", new URL(request.url).origin);
} catch {
return NextResponse.json({ error: "invalid request url" }, { status: 400 });
}
try {
const settings = await getOrCreateSettings();
const appId = getThreadsAppId();
homeUrl = new URL("/", getAppBaseUrl(request, settings.appUrl));
if (!appId) {
homeUrl.searchParams.set(
"threads_error",
"系統尚未設定 Threads App請管理員在 .env 填入 THREADS_APP_ID"
);
return NextResponse.redirect(homeUrl);
}
const accountId = await getActiveAccountId();
if (!accountId) {
homeUrl.searchParams.set("threads_error", "no_active_account");
return NextResponse.redirect(homeUrl);
}
try {
const url = buildThreadsOAuthUrl(request, appId, accountId, settings.appUrl);
return NextResponse.redirect(url);
} catch (err) {
const message = err instanceof Error ? err.message : "invalid_app_id";
homeUrl.searchParams.set("threads_error", message);
return NextResponse.redirect(homeUrl);
}
} catch (err) {
const message = err instanceof Error ? err.message : "authorize_failed";
homeUrl.searchParams.set("threads_error", message);
return NextResponse.redirect(homeUrl);
}
}