58 lines
1.7 KiB
PHP
58 lines
1.7 KiB
PHP
<?php
|
|
session_start();
|
|
require_once __DIR__ . '/db/config.php';
|
|
|
|
$action = $_GET['action'] ?? '';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$pdo = db();
|
|
if ($action === 'register') {
|
|
$username = trim($_POST['username']);
|
|
$password = $_POST['password'];
|
|
$confirm_password = $_POST['confirm_password'];
|
|
|
|
if ($password !== $confirm_password) {
|
|
die("Passwords do not match.");
|
|
}
|
|
|
|
$hash = password_hash($password, PASSWORD_DEFAULT);
|
|
|
|
// Check if this is the first user
|
|
$stmt = $pdo->query("SELECT COUNT(*) FROM users");
|
|
$count = $stmt->fetchColumn();
|
|
$role = ($count == 0) ? 'admin' : 'user';
|
|
|
|
try {
|
|
$stmt = $pdo->prepare("INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)");
|
|
$stmt->execute([$username, $hash, $role]);
|
|
header('Location: index.php?registered=1');
|
|
exit;
|
|
} catch (PDOException $e) {
|
|
die("Registration failed: " . $e->getMessage());
|
|
}
|
|
} elseif ($action === 'login') {
|
|
$username = trim($_POST['username']);
|
|
$password = $_POST['password'];
|
|
|
|
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
|
|
$stmt->execute([$username]);
|
|
$user = $stmt->fetch();
|
|
|
|
if ($user && password_verify($password, $user['password_hash'])) {
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['username'] = $user['username'];
|
|
$_SESSION['role'] = $user['role'];
|
|
header('Location: dashboard.php');
|
|
exit;
|
|
} else {
|
|
die("Invalid credentials.");
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($action === 'logout') {
|
|
session_destroy();
|
|
header('Location: index.php');
|
|
exit;
|
|
}
|