File size: 7,844 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import NextAuth, { NextAuthOptions } from "next-auth";
import FacebookProvider from "next-auth/providers/facebook";
import { PrismaClient } from "@prisma/client";

// Initialize Prisma Client (singleton pattern recommended for dev, keeping simplistic for now or importing from lib/prisma if I create it)
// For now, I'll assume global prisma or import it. I should create src/lib/prisma.ts first.
import { prisma } from "@/lib/prisma";
import { encrypt } from "@/lib/encryption";

export const authOptions: NextAuthOptions = {
    providers: [
        FacebookProvider({
            clientId: process.env.FACEBOOK_APP_ID!,
            clientSecret: process.env.FACEBOOK_APP_SECRET!,
            authorization: {
                params: {
                    scope: "public_profile,instagram_basic,instagram_content_publish,pages_show_list,pages_read_engagement,business_management",
                },
            },
        }),
    ],
    callbacks: {
        async signIn({ user, account, profile }) {
            if (account?.provider === "facebook" && account.access_token) {
                try {
                    console.log("Starting Facebook Sign In Process...");
                    // 1. Exchange for Long-Lived Token (LLT)
                    const graphUrl = process.env.INSTAGRAM_GRAPH_URL || "https://graph.facebook.com/v21.0";
                    const exchangeUrl = `${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.access_token}`;

                    console.log("Exchanging token...");
                    const exchangeRes = await fetch(exchangeUrl);
                    const exchangeData = await exchangeRes.json();

                    if (!exchangeRes.ok || !exchangeData.access_token) {
                        console.error("Failed to exchange token", exchangeData);
                        return false;
                    }
                    console.log("Token exchanged successfully.");

                    const longLivedToken = exchangeData.access_token;
                    // Calculate expiry (usually 60 days)
                    const expiresAt = new Date();
                    expiresAt.setDate(expiresAt.getDate() + 60);

                    // 2. Fetch accessible Pages and their connected Instagram Accounts
                    console.log("Fetching pages...");
                    const pagesUrl = `${graphUrl}/me/accounts?fields=id,name,access_token,instagram_business_account{id,username,profile_picture_url}&access_token=${longLivedToken}`;
                    const pagesRes = await fetch(pagesUrl);
                    const pagesData = await pagesRes.json();

                    if (!pagesRes.ok) {
                        console.error("Failed to fetch accounts", pagesData);
                        return false;
                    }

                    console.log("Pages fetched from FB:", pagesData.data?.length);
                    // Log details of each page
                    if (pagesData.data) {
                        pagesData.data.forEach((p: any) => {
                            console.log(`Page: ${p.name} (ID: ${p.id})`);
                            console.log(` - Has IG Object: ${!!p.instagram_business_account}`);
                        });
                    }

                    const connectedAccounts = (pagesData.data || []).filter((page: any) => page.instagram_business_account);

                    if (connectedAccounts.length === 0) {
                        console.warn("No Instagram Business accounts found. Raw pages data:", JSON.stringify(pagesData.data, null, 2));
                        // Allow login properly even if no accounts found, so user can see dashboard and realize they need to connect one.
                        // Previously we might have been implicitely failing if logic depended on it? No, logic flow continues.
                    }

                    // 3. Create or Update User
                    const email = user.email || `${user.id}@ripple.user`;
                    const userImage = user.image || null;

                    user.email = email;

                    console.log("Upserting User:", email);
                    const dbUser = await prisma.user.upsert({
                        where: { email },
                        update: { image: userImage },
                        create: { email, id: user.id || crypto.randomUUID(), image: userImage }, // Ensure ID is present
                    });
                    console.log("User upserted:", dbUser.id);

                    // 4. Save Instagram Accounts
                    if (connectedAccounts.length > 0) {
                        console.log(`Saving ${connectedAccounts.length} Instagram Accounts...`);
                        for (const page of connectedAccounts) {
                            const ig = page.instagram_business_account;
                            const encryptedToken = encrypt(longLivedToken);

                            await prisma.instagramAccount.upsert({
                                where: { instagramUserId: ig.id },
                                update: {
                                    username: ig.username,
                                    profilePictureUrl: ig.profile_picture_url,
                                    accessToken: encryptedToken,
                                    tokenExpiresAt: expiresAt,
                                    userId: dbUser.id,
                                },
                                create: {
                                    instagramUserId: ig.id,
                                    username: ig.username,
                                    profilePictureUrl: ig.profile_picture_url,
                                    accessToken: encryptedToken,
                                    tokenExpiresAt: expiresAt,
                                    userId: dbUser.id,
                                },
                            });
                        }
                        console.log("Instagram Accounts saved.");
                    } else {
                        console.log("Skipping IG Account save (None found).");
                    }

                    console.log("Sign In Logic Completed Successfully.");
                    return true;
                } catch (error) {
                    console.error("SignIn CRITICAL ERROR:", error);
                    return false;
                }
            }
            return true;
        },
        async jwt({ token, user, account }) {
            // Initial sign in
            if (account && user) {
                token.accessToken = account.access_token;
                token.id = user.id;

                // Ensure email is set in token
                if (user.email) {
                    token.email = user.email;
                } else if (user.id) {
                    token.email = `${user.id}@ripple.user`;
                }

                // Allow passing image if needed, but session typically reads from DB or user object
                if (user.image) token.picture = user.image;
            }
            return token;
        },
        async session({ session, token }) {
            session.accessToken = token.accessToken as string;
            if (session.user) {
                (session.user as any).id = token.id as string;
                if (token.email) {
                    session.user.email = token.email;
                }
                if (token.picture) {
                    session.user.image = token.picture;
                }
            }
            return session;
        },
    },
    pages: {
        signIn: '/auth/signin',
    },
    // @ts-ignore
    trustHost: true,
};