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

93 lines
2 KiB
TypeScript
Raw Normal View History

import { compare } from 'bcrypt-ts';
import NextAuth, { type DefaultSession } from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { createGuestUser, getUser } from '@/lib/db/queries';
import { authConfig } from './auth.config';
import { DUMMY_PASSWORD } from '@/lib/constants';
import type { DefaultJWT } from 'next-auth/jwt';
2025-04-25 23:40:15 -07:00
export type UserType = 'guest' | 'regular';
2025-04-25 23:40:15 -07:00
declare module 'next-auth' {
2025-04-25 23:40:15 -07:00
interface Session extends DefaultSession {
user: {
id: string;
type: UserType;
} & DefaultSession['user'];
2025-04-25 23:40:15 -07:00
}
interface User {
id?: string;
email?: string | null;
type: UserType;
}
}
2024-10-11 18:00:22 +05:30
declare module 'next-auth/jwt' {
2025-04-25 23:40:15 -07:00
interface JWT extends DefaultJWT {
id: string;
type: UserType;
}
2024-10-11 18:00:22 +05:30
}
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);
if (!passwordsMatch) return null;
return { ...user, type: 'regular' };
2025-04-25 23:40:15 -07:00
},
}),
Credentials({
id: 'guest',
2025-04-25 23:40:15 -07:00
credentials: {},
async authorize() {
const [guestUser] = await createGuestUser();
return { ...guestUser, type: 'guest' };
2024-10-11 18:00:22 +05:30
},
}),
],
callbacks: {
async jwt({ token, user }) {
2024-10-11 18:00:22 +05:30
if (user) {
2025-04-25 23:40:15 -07:00
token.id = user.id as string;
token.type = user.type;
2024-10-11 18:00:22 +05:30
}
return token;
},
async session({ session, token }) {
2024-10-11 18:00:22 +05:30
if (session.user) {
2025-04-25 23:40:15 -07:00
session.user.id = token.id;
session.user.type = token.type;
2024-10-11 18:00:22 +05:30
}
return session;
},
},
});