homelab-dashboard/auth.ts
Bilal Teke c7fd939f41 v4.1
2026-04-20 20:35:43 +02:00

69 lines
1.8 KiB
TypeScript

import { compare } from 'bcryptjs';
import { getServerSession, type NextAuthOptions } from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { getUserByUsername, hasAnyUser } from '@/src/lib/db/user';
export const authOptions: NextAuthOptions = {
providers: [
Credentials({
credentials: {
username: { label: 'Benutzername', type: 'text' },
password: { label: 'Passwort', type: 'password' },
},
async authorize(credentials) {
if (!credentials?.username || !credentials?.password) {
return null;
}
const username = credentials.username.trim();
const password = credentials.password;
try {
const dbUser = getUserByUsername(username);
if (dbUser) {
const isPasswordValid = await compare(password, dbUser.password_hash);
if (!isPasswordValid) {
return null;
}
return {
id: String(dbUser.id),
name: username,
email: `${username}@homelab.local`,
username,
};
}
if (hasAnyUser()) {
return null;
}
} catch (error) {
console.error('Database authentication error:', error);
return null;
}
},
}),
],
pages: {
signIn: '/login',
},
callbacks: {
async jwt({ token, user }) {
if (user && user.username) {
token.username = user.username;
}
return token;
},
async session({ session, token }) {
if (session.user) {
session.user.username = token.username;
}
return session;
},
},
session: {
strategy: 'jwt',
maxAge: 24 * 60 * 60,
},
secret: process.env.NEXTAUTH_SECRET,
};
export function auth() {
return getServerSession(authOptions);
}