73 lines
2.0 KiB
PHP
73 lines
2.0 KiB
PHP
<?php
|
|
require_once 'includes/auth.php';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
header('Location: index.php');
|
|
exit();
|
|
}
|
|
|
|
$action = $_POST['action'] ?? '';
|
|
|
|
if ($action === 'register') {
|
|
$name = $_POST['name'] ?? '';
|
|
$email = $_POST['email'] ?? '';
|
|
$password = $_POST['password'] ?? '';
|
|
|
|
if (empty($name) || empty($email) || empty($password)) {
|
|
header('Location: register.php?error=missing_fields');
|
|
exit();
|
|
}
|
|
|
|
$db = db();
|
|
$stmt = $db->prepare('SELECT id FROM users WHERE email = ?');
|
|
$stmt->execute([$email]);
|
|
if ($stmt->fetch()) {
|
|
header('Location: register.php?error=email_taken');
|
|
exit();
|
|
}
|
|
|
|
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
|
|
|
|
// Default new registrations to the 'Client' role
|
|
$stmt = $db->prepare("SELECT id FROM roles WHERE name = 'Client'");
|
|
$stmt->execute();
|
|
$client_role = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
$stmt = $db->prepare('INSERT INTO users (name, email, password, role_id) VALUES (?, ?, ?, ?)');
|
|
if ($stmt->execute([$name, $email, $hashed_password, $client_role['id'] ?? null])) {
|
|
$user_id = $db->lastInsertId();
|
|
$_SESSION['user_id'] = $user_id;
|
|
header('Location: portal/');
|
|
exit();
|
|
} else {
|
|
header('Location: register.php?error=registration_failed');
|
|
exit();
|
|
}
|
|
|
|
} elseif ($action === 'login') {
|
|
$email = $_POST['email'] ?? '';
|
|
$password = $_POST['password'] ?? '';
|
|
|
|
if (empty($email) || empty($password)) {
|
|
header('Location: login.php?error=missing_fields');
|
|
exit();
|
|
}
|
|
|
|
$db = db();
|
|
$stmt = $db->prepare('SELECT * FROM users WHERE email = ?');
|
|
$stmt->execute([$email]);
|
|
$user = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if ($user && password_verify($password, $user['password'])) {
|
|
$_SESSION['user_id'] = $user['id'];
|
|
header('Location: portal/');
|
|
exit();
|
|
} else {
|
|
header('Location: login.php?error=invalid_credentials');
|
|
exit();
|
|
}
|
|
} else {
|
|
header('Location: index.php');
|
|
exit();
|
|
}
|