Added authentication functionality and simple role based model
This commit is contained in:
42
register.php
Normal file
42
register.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
require 'db.php';
|
||||
require 'auth.php';
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
$data = json_decode(file_get_contents('php://input'), true);
|
||||
$email = strtolower(trim($data['email'] ?? ''));
|
||||
$password = strval($data['password'] ?? '');
|
||||
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'Invalid email']);
|
||||
exit;
|
||||
}
|
||||
if (strlen($password) < 8) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'Password must be at least 8 characters']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$hash = password_hash($password, PASSWORD_DEFAULT);
|
||||
|
||||
// Standard role id from roles table
|
||||
$stmt = $pdo->prepare("SELECT id FROM roles WHERE name = 'standard' LIMIT 1");
|
||||
$stmt->execute();
|
||||
$role_id = intval($stmt->fetchColumn());
|
||||
|
||||
if ($role_id <= 0) {
|
||||
http_response_code(500);
|
||||
echo json_encode(['success' => false, 'error' => "Role 'standard' not found"]);
|
||||
exit;
|
||||
}
|
||||
|
||||
try {
|
||||
$stmt = $pdo->prepare("INSERT INTO users (email, password_hash, role_id) VALUES (?, ?, ?)");
|
||||
$stmt->execute([$email, $hash, $role_id]);
|
||||
echo json_encode(['success' => true]);
|
||||
} catch (Throwable $e) {
|
||||
http_response_code(409);
|
||||
echo json_encode(['success' => false, 'error' => 'Account already exists']);
|
||||
}
|
||||
Reference in New Issue
Block a user