Spaces:
Runtime error
Runtime error
Download src/app/api/auth/refresh/route.ts from damndeepesh-dev/RippleWorkers: direct link, hf CLI and curl.
- Browser
- Download file 2.29 kB
-
https://huggingface.co/spaces/damndeepesh-dev/RippleWorkers/resolve/main/src/app/api/auth/refresh/route.ts
- Command line
-
hf download hf://spaces/damndeepesh-dev/RippleWorkers/src/app/api/auth/refresh/route.ts
-
curl -L -o route.ts https://huggingface.co/spaces/damndeepesh-dev/RippleWorkers/resolve/main/src/app/api/auth/refresh/route.ts
2.29 kB
| import { prisma } from "@/lib/prisma"; | |
| import { getServerSession } from "next-auth"; | |
| import { authOptions } from "@/lib/auth"; | |
| import { NextRequest, NextResponse } from "next/server"; | |
| export async function POST(req: NextRequest) { | |
| const session = await getServerSession(authOptions); | |
| if (!session?.user?.email) { | |
| return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); | |
| } | |
| try { | |
| const user = await prisma.user.findUnique({ | |
| where: { email: session.user.email }, | |
| include: { instagramAccounts: true }, | |
| }); | |
| if (!user || user.instagramAccounts.length === 0) { | |
| return NextResponse.json({ error: "No accounts found" }, { status: 404 }); | |
| } | |
| const graphUrl = process.env.INSTAGRAM_GRAPH_URL || "https://graph.facebook.com/v21.0"; | |
| let refreshedCount = 0; | |
| for (const account of user.instagramAccounts) { | |
| // Exchange current token for a fresh long-lived token | |
| // https://developers.facebook.com/docs/instagram-basic-display-api/guides/long-lived-access-tokens | |
| const refreshUrl = `${graphUrl}/oauth/access_token?grant_type=fb_exchange_token&client_id=${process.env.FACEBOOK_APP_ID}&client_secret=${process.env.FACEBOOK_APP_SECRET}&fb_exchange_token=${account.accessToken}`; | |
| const res = await fetch(refreshUrl); | |
| const data = await res.json(); | |
| if (data.access_token) { | |
| const expiresAt = new Date(); | |
| expiresAt.setDate(expiresAt.getDate() + 60); // Approx 60 days | |
| await prisma.instagramAccount.update({ | |
| where: { id: account.id }, | |
| data: { | |
| accessToken: data.access_token, | |
| tokenExpiresAt: expiresAt, | |
| } | |
| }); | |
| refreshedCount++; | |
| } else { | |
| console.error(`Failed to refresh token for account ${account.username}`, data); | |
| } | |
| } | |
| return NextResponse.json({ success: true, count: refreshedCount }); | |
| } catch (error) { | |
| console.error("Refresh Token Error", error); | |
| return NextResponse.json({ error: "Internal Server Error" }, { status: 500 }); | |
| } | |
| } | |