54 lines
1.5 KiB
PHP
54 lines
1.5 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../db/config.php';
|
|
|
|
session_start();
|
|
header('Content-Type: application/json');
|
|
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$data || !isset($data['email']) || !isset($data['password'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['status' => 'error', 'message' => 'Invalid input.']);
|
|
exit;
|
|
}
|
|
|
|
$email = trim($data['email']);
|
|
$password = $data['password'];
|
|
|
|
if (empty($email) || empty($password)) {
|
|
http_response_code(400);
|
|
echo json_encode(['status' => 'error', 'message' => 'Please fill all fields.']);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
|
|
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
|
|
$stmt->execute([$email]);
|
|
$user = $stmt->fetch();
|
|
|
|
if ($user && password_verify($password, $user['password'])) {
|
|
// Password is correct, start session
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['username'] = $user['username'];
|
|
$_SESSION['role'] = $user['role'];
|
|
|
|
echo json_encode([
|
|
'status' => 'success',
|
|
'message' => 'Login successful.',
|
|
'user' => [
|
|
'username' => $user['username'],
|
|
'role' => $user['role']
|
|
]
|
|
]);
|
|
} else {
|
|
http_response_code(401);
|
|
echo json_encode(['status' => 'error', 'message' => 'Invalid email or password.']);
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
http_response_code(500);
|
|
echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
|
|
}
|