chatbot-template/app/(auth)/auth.ts

70 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-11-14 12:16:05 -05:00
import { compare } from 'bcrypt-ts';
2024-11-15 12:18:17 -05:00
import NextAuth, { type User, type Session } from 'next-auth';
2024-11-14 12:16:05 -05:00
import Credentials from 'next-auth/providers/credentials';
2024-10-11 18:00:22 +05:30
2024-11-15 10:13:21 -05:00
import { getUser } from '@/lib/db/queries';
2024-10-11 18:00:22 +05:30
2024-11-14 12:16:05 -05:00
import { authConfig } from './auth.config';
import { DUMMY_PASSWORD } from '@/lib/constants';
2024-10-11 18:00:22 +05:30
interface ExtendedSession extends Session {
user: User;
}
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
...authConfig,
providers: [
Credentials({
credentials: {},
async authorize({ email, password }: any) {
2024-11-15 12:18:17 -05:00
const users = await getUser(email);
if (users.length === 0) {
await compare(password, DUMMY_PASSWORD);
return null;
}
const [user] = users;
if (!user.password) {
await compare(password, DUMMY_PASSWORD);
return null;
}
const passwordsMatch = await compare(password, user.password);
2024-11-15 13:00:15 -05:00
if (!passwordsMatch) return null;
return user as any;
2024-10-11 18:00:22 +05:30
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
}
return token;
},
async session({
session,
token,
}: {
session: ExtendedSession;
token: any;
}) {
if (session.user) {
session.user.id = token.id as string;
}
return session;
},
},
});