geraete/lib/auth-options.ts
2025-11-17 15:26:43 +01:00

73 lines
1.7 KiB
TypeScript

// lib/auth-options.ts
import type { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { prisma } from './prisma';
import { compare } from 'bcryptjs';
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: 'Credentials',
credentials: {
email: {
label: 'Benutzername oder E-Mail',
type: 'text',
},
password: {
label: 'Passwort',
type: 'password',
},
},
async authorize(credentials) {
if (!credentials?.email || !credentials.password) {
return null;
}
const identifier = credentials.email.trim();
// User per E-Mail ODER Benutzername suchen
const user = await prisma.user.findFirst({
where: {
OR: [{ email: identifier }, { username: identifier }],
},
});
if (!user || !user.passwordHash) {
return null;
}
const isValid = await compare(credentials.password, user.passwordHash);
if (!isValid) {
return null;
}
return {
id: user.id,
name: user.name ?? user.username ?? user.email,
email: user.email,
};
},
}),
],
pages: {
signIn: '/login',
},
session: {
strategy: 'jwt',
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
}
return token;
},
async session({ session, token }) {
if (session.user && token.id) {
(session.user as any).id = token.id;
}
return session;
},
},
};