philippurbschat.de/plants/auth_api.php

87 lines
3 KiB
PHP

<?php
$current_project = 'plants';
require_once __DIR__ . '/../auth.php';
require_once 'db.php'; // Stellt die $pdo-Verbindung her
// Eine sichere Methode, um eine Session zu starten
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
$action = $data['action'] ?? $_GET['action'] ?? null;
// ============================
// === BEARBEITUNG DER ANFRAGEN ===
// ============================
try {
if ($action === 'register') {
// --- Registrierung ---
$username = $data['username'] ?? '';
$email = $data['email'] ?? '';
$password = $data['password'] ?? '';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Bitte gib eine gültige E-Mail-Adresse ein.');
}
if (strlen($password) < 8) {
throw new Exception('Das Passwort muss mindestens 8 Zeichen lang sein.');
}
if (empty($username)) {
throw new Exception('Bitte gib einen Namen ein.');
}
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$email]);
if ($stmt->fetch()) {
throw new Exception('Diese E-Mail-Adresse ist bereits registriert.');
}
$password_hash = password_hash($password, PASSWORD_ARGON2ID);
$stmt = $pdo->prepare("INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)");
$stmt->execute([$username, $email, $password_hash]);
echo json_encode(['success' => true, 'message' => 'Konto erfolgreich erstellt! Du kannst dich jetzt einloggen.']);
} elseif ($action === 'login') {
// --- Login ---
$email = $data['email'] ?? '';
$password = $data['password'] ?? '';
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($password)) {
throw new Exception('Bitte gib E-Mail und Passwort ein.');
}
$stmt = $pdo->prepare("SELECT id, username, password_hash FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password_hash'])) {
// Passwort ist korrekt, starte die Session
session_regenerate_id(true); // Wichtig für die Sicherheit
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
echo json_encode(['success' => true, 'message' => 'Login erfolgreich!']);
} else {
throw new Exception('E-Mail oder Passwort ist falsch.');
}
} elseif ($action === 'logout') {
// --- Logout ---
session_destroy();
echo json_encode(['success' => true, 'message' => 'Du wurdest ausgeloggt.']);
} else {
throw new Exception('Ungültige Aktion.');
}
} catch (Exception $e) {
http_response_code(400); // Bad Request
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>