59 lines
1.6 KiB
TypeScript
59 lines
1.6 KiB
TypeScript
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<Beo | null> {
|
|
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<Beo | null> {
|
|
// 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<string> {
|
|
return bcrypt.hash(password, 12);
|
|
}
|
|
|
|
export function getBeoDisplayName(beo: Beo): string {
|
|
return beo.vorname ? `${beo.vorname} ${beo.name}` : beo.name;
|
|
}
|