Files
tinyTask/register.php

57 lines
1.6 KiB
PHP

<?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 {
$pdo->beginTransaction();
// Create user
$stmt = $pdo->prepare("INSERT INTO users (email, password_hash, role_id) VALUES (?, ?, ?)");
$stmt->execute([$email, $hash, $role_id]);
$userId = (int)$pdo->lastInsertId();
// Create default profile for this user
$stmt = $pdo->prepare("INSERT INTO profiles (user_id, name, is_default) VALUES (?, 'Default', 1)");
$stmt->execute([$userId]);
$pdo->commit();
echo json_encode(['success' => true]);
} catch (Throwable $e) {
if ($pdo->inTransaction()) $pdo->rollBack();
http_response_code(409);
echo json_encode(['success' => false, 'error' => 'Account already exists']);
}