import NextAuth from 'next-auth'; import CredentialsProvider from 'next-auth/providers/credentials'; import db from '@/lib/db'; import type { User } from '@/lib/types'; export const { handlers: { GET, POST }, auth, signIn, signOut, } = NextAuth({ secret: process.env.AUTH_SECRET, providers: [ CredentialsProvider({ name: 'Credentials', credentials: { email: { label: 'Email', type: 'email' }, password: { label: 'Password', type: 'password' }, }, async authorize(credentials) { if (!credentials?.email || !credentials.password) { return null; } const email = credentials.email as string; const password = credentials.password as string; try { const stmt = db.prepare('SELECT * FROM users WHERE email = ?'); const user = stmt.get(email) as User | undefined; // In a real app, you would use a secure password hashing library like bcrypt if (user && user.password === password) { // Return a user object that NextAuth will use to create the session return { id: user.id.toString(), name: user.name, email: user.email, }; } else { // Invalid credentials return null; } } catch (error) { console.error('Database error during authorization:', error); return null; } }, }), ], callbacks: { jwt({ token, user }) { if (user) { token.id = user.id; } return token; }, session({ session, token }) { if (session.user) { session.user.id = token.id as string; } return session; }, }, pages: { signIn: '/login', }, });