import bcrypt from 'bcryptjs'; import { query } from './db'; export interface Beo { id: number; name: string; vorname: string | null; kürzel: string | null; pw: string | null; MustChangePassword: number; role: string | null; } export async function getBeoByKuerzel(kuerzel: string): Promise { const rows = await query( 'SELECT id, name, vorname, `kürzel`, pw, MustChangePassword, role FROM beos WHERE `kürzel` = ?', [kuerzel] ) as Beo[]; return rows[0] ?? null; } export async function getBeoByLogin(login: string): Promise { // First try exact Kürzel match, then case-insensitive Nachname match const byKuerzel = await getBeoByKuerzel(login); if (byKuerzel) return byKuerzel; const rows = await query( 'SELECT id, name, vorname, `kürzel`, pw, MustChangePassword, role FROM beos WHERE LOWER(name) = LOWER(?)', [login] ) as Beo[]; return rows[0] ?? null; } export async function verifyCredentials( login: string, password: string ): Promise<{ beo: Beo; valid: boolean } | null> { const beo = await getBeoByLogin(login); if (!beo) return null; if (!beo.pw) { const defaultPw = process.env.DEFAULT_PASSWORD; if (!defaultPw) throw new Error('DEFAULT_PASSWORD Umgebungsvariable ist nicht gesetzt!'); const valid = password === defaultPw; return { beo, valid }; } const valid = await bcrypt.compare(password, beo.pw); return { beo, valid }; } export async function hashPassword(password: string): Promise { return bcrypt.hash(password, 12); } export function getBeoDisplayName(beo: Beo): string { return beo.vorname ? `${beo.vorname} ${beo.name}` : beo.name; }