Repository navigation
Expand file tree
/
Copy pathconfig.php
More file actions
89 lines (77 loc) · 2.55 KB
/
Copy pathconfig.php
File metadata and controls
89 lines (77 loc) · 2.55 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
// ============================================
// AccesWaze v2.0 - Configuración
// ============================================
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', ''); // Cambia si tu MySQL tiene contraseña
define('DB_NAME', 'accesWaze');
define('DB_PORT', 3306);
define('DB_CHARSET', 'utf8mb4');
// ---- Sesión segura ----
if (session_status() === PHP_SESSION_NONE) {
ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);
session_start();
}
// ---- Headers CORS / JSON (solo para llamadas API) ----
function setApiHeaders(): void {
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
}
// ---- Conexión PDO (más robusta que mysqli) ----
function getConnection(): PDO {
static $pdo = null;
if ($pdo !== null) return $pdo;
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
DB_HOST, DB_PORT, DB_NAME, DB_CHARSET
);
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
} catch (PDOException $e) {
http_response_code(503);
echo json_encode([
'error' => 'No se pudo conectar a la base de datos.',
'detalle' => $e->getMessage() // Quita esta línea en producción
]);
exit;
}
return $pdo;
}
// ---- Respuesta JSON ----
function jsonResponse(array $data, int $status = 200): never {
http_response_code($status);
setApiHeaders();
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
// ---- Utilidades ----
function requireAuth(): array {
if (empty($_SESSION['usuario_id'])) {
jsonResponse(['error' => 'Sesión requerida. Por favor inicia sesión.'], 401);
}
return [
'id' => $_SESSION['usuario_id'],
'nombre' => $_SESSION['nombre'],
'email' => $_SESSION['email'],
'rol' => $_SESSION['rol'],
'perfil' => $_SESSION['perfil'] ?? 'general',
];
}
function requireAdmin(): array {
$user = requireAuth();
if ($user['rol'] !== 'admin') {
jsonResponse(['error' => 'Acceso denegado. Se requieren permisos de administrador.'], 403);
}
return $user;
}
function sanitize(string $str): string {
return htmlspecialchars(trim($str), ENT_QUOTES, 'UTF-8');
}