File size: 2,288 Bytes
c7fbc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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 });
    }
}