import { NextAuthOptions } from 'next-auth'; import GoogleProvider from 'next-auth/providers/google'; import GithubProvider from 'next-auth/providers/github'; import DiscordProvider from 'next-auth/providers/discord'; import CredentialsProvider from 'next-auth/providers/credentials'; import { connectDB } from '@/app/lib/mongodb'; import bcrypt from 'bcryptjs'; import User from '@/app/lib/models/Users'; export const options = { providers: [ GoogleProvider({ clientId: process.env.AUTH_GOOGLE_ID, clientSecret: process.env.AUTH_GOOGLE_SECRET }), GithubProvider({ clientId: process.env.AUTH_GITHUB_ID, clientSecret: process.env.AUTH_GITHUB_SECRET }), DiscordProvider({ clientId: process.env.AUTH_DISCORD_ID, clientSecret: process.env.AUTH_DISCORD_SECRET }), CredentialsProvider({ name: 'Credentials', id: 'credentials', credentials: { username: { label: 'Username', type: 'text', placeholder: 'your-username' }, password: { label: 'Password', type: 'password', placeholder: 'your-password' } }, async authorize(credentials, req) { await connectDB(); const user = await User.findOne({ email: credentials?.email }).select('+password'); if (!user) throw new Error('Wrong Email'); const PassWordMatch = await bcrypt.compare( credentials.password, user.password ); if (!PassWordMatch) throw new Error('Wrong Password'); return user; } }) ], session: { strategy: 'jwt' }, callbacks: { async signIn({ user, account, profile }) { await connectDB(); if (!user.email) { console.error("No email returned from OAuth provider"); return false; } const existingUser = await User.findOne({ email: user.email }); if (!existingUser) { const newUser = new User({ name: user.name || "Anonymous", email: user.email, password: "OAuth" }); await newUser.save(); } return true; }, async redirect({ url, baseUrl }) { if (url && url.startsWith(baseUrl)) { return url; } return baseUrl; }, async jwt({ token, user }) { if (user) { token.id = user._id; } return token; }, async session({ session, token }) { if (token) { session.id = token.id; } return session; } }, pages: { signIn: '/auth/signin', signup: '/auth/signup', signOut: '/auth/signout', error: '/auth/error', verifyRequest: '/auth/verify-request', newUser: null // Will disable the new account creation screen } };