-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_handler.php
More file actions
66 lines (55 loc) · 2.49 KB
/
auth_handler.php
File metadata and controls
66 lines (55 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
session_start();
require_once 'includes/db.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
if ($action === 'signup') {
$name = trim($_POST['signupName']);
$email = trim($_POST['signupEmail']);
$password = $_POST['signupPassword'];
if (empty($name) || empty($email) || empty($password)) {
echo json_encode(['status' => 'error', 'message' => 'All fields are required.']);
exit;
}
try {
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$email]);
if ($stmt->fetch()) {
echo json_encode(['status' => 'error', 'message' => 'Email already registered.']);
exit;
}
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (full_name, email, password, role) VALUES (?, ?, ?, 'user')");
if ($stmt->execute([$name, $email, $hashed_password])) {
echo json_encode(['status' => 'success', 'message' => 'Account created successfully! Please log in.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Registration failed.']);
}
} catch (PDOException $e) {
echo json_encode(['status' => 'error', 'message' => 'Database error.']);
}
exit;
}
if ($action === 'login') {
$email = trim($_POST['loginEmail']);
$password = $_POST['loginPassword'];
try {
$stmt = $pdo->prepare("SELECT id, full_name, password, role FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['full_name'];
$_SESSION['user_role'] = $user['role'];
$redirect = ($user['role'] === 'admin') ? 'admin.php' : 'index.php';
echo json_encode(['status' => 'success', 'message' => 'Logged in successfully!', 'redirect' => $redirect]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Invalid email or password.']);
}
} catch (PDOException $e) {
echo json_encode(['status' => 'error', 'message' => 'Database error.']);
}
exit;
}
}