import { d as defineEventHandler, r as readBody, c as createError, s as setCookie } from '../../../nitro/nitro.mjs';
import { r as readUsers, v as verifyPassword, g as generateToken, c as createSession, w as writeUsers } from '../../../_/auth.mjs';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'node:fs';
import 'node:path';
import 'node:crypto';
import 'node:url';
import 'bcryptjs';
import 'jsonwebtoken';
import 'fs';
import 'path';
import '../../../_/encryption.mjs';
import 'crypto';

const login_post = defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const { email, password } = body;
    if (!email || !password) {
      throw createError({
        statusCode: 400,
        message: "E-Mail und Passwort sind erforderlich"
      });
    }
    const users = await readUsers();
    const user = users.find((u) => u.email.toLowerCase() === email.toLowerCase());
    if (!user) {
      throw createError({
        statusCode: 401,
        message: "Ung\xFCltige Anmeldedaten"
      });
    }
    if (user.active === false) {
      throw createError({
        statusCode: 403,
        message: "Ihr Konto wurde noch nicht freigeschaltet. Bitte warten Sie auf die Best\xE4tigung des Vorstands."
      });
    }
    const isValid = await verifyPassword(password, user.password);
    if (!isValid) {
      throw createError({
        statusCode: 401,
        message: "Ung\xFCltige Anmeldedaten"
      });
    }
    const token = generateToken(user);
    await createSession(user.id, token);
    user.lastLogin = (/* @__PURE__ */ new Date()).toISOString();
    const updatedUsers = users.map((u) => u.id === user.id ? user : u);
    await writeUsers(updatedUsers);
    setCookie(event, "auth_token", token, {
      httpOnly: true,
      secure: false,
      // Auch in Production false, da wir HTTPS über Apache terminieren
      sameSite: "lax",
      maxAge: 60 * 60 * 24 * 7
      // 7 days
    });
    return {
      success: true,
      token,
      // Token auch im Body für externe API-Clients
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        role: user.role
      }
    };
  } catch (error) {
    console.error("Login-Fehler:", error);
    throw error;
  }
});

export { login_post as default };
//# sourceMappingURL=login.post.mjs.map
