Files
Giveaway-app/src/app/api/auth/[...nextauth]/route.ts
T
Alexandru Eduard Farcas f8144fb5ac lint rules update
2025-05-18 10:15:18 +03:00

79 lines
2.5 KiB
TypeScript

import NextAuth, { SessionStrategy } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { db } from "@/lib/db";
import axios from "axios";
if (!db) {
throw new Error("Prisma client is not initialized. Check your database configuration.");
}
export const authOptions = {
adapter: PrismaAdapter(db),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
allowDangerousEmailAccountLinking: true,
authorization: {
params: {
scope: "openid email profile https://www.googleapis.com/auth/youtube.readonly",
},
},
}),
],
secret: process.env.NEXTAUTH_SECRET,
session: {
strategy: "database" as SessionStrategy,
},
callbacks: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async signIn({ user, account, profile }: { user: any; account: any; profile?: any }) {
if (!user || !account || !profile) {
console.error("Sign-in failed: Missing user, account, or profile data.");
return false;
}
if (account.provider === "google" && account.access_token) {
try {
console.log("Fetching YouTube handle for user:", user.email);
const { data } = await axios.get("https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true", {
params: {
part: "brandingSettings",
mine: "true",
},
headers: {
Authorization: `Bearer ${account.access_token}`,
},
});
console.log("YouTube API response:", JSON.stringify(data));
const customUrl = data.items?.[0]?.snippet?.customUrl;
const youtubeHandle = customUrl ;
console.log("Fetched YouTube handle:", youtubeHandle);
user.youtubeHandle = youtubeHandle;
} catch (error) {
console.error("Error fetching YouTube handle:", error);
}
}
return true;
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async session({ session, user }: { session: any; user: any }) {
session.user.id = user.id;
session.user.youtubeHandle = user.youtubeHandle; // Only attach YouTube handle
return session;
},
},
debug: true, // Enable debug mode for detailed error messages
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };