49 lines
1.3 KiB
PHP
49 lines
1.3 KiB
PHP
<?php
|
|
session_start();
|
|
require_once __DIR__ . '/db/config.php';
|
|
|
|
function get_user() {
|
|
if (!isset($_SESSION['user_id'])) return null;
|
|
$stmt = db()->prepare("SELECT * FROM users WHERE id = ?");
|
|
$stmt->execute([$_SESSION['user_id']]);
|
|
return $stmt->fetch();
|
|
}
|
|
|
|
function require_login() {
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|
|
}
|
|
|
|
function require_role($roles) {
|
|
$user = get_user();
|
|
if (!$user || !in_array($user['role'], (array)$roles)) {
|
|
header('Location: index.php?error=Unauthorized');
|
|
exit;
|
|
}
|
|
}
|
|
|
|
function uuid() {
|
|
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
|
|
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
|
|
mt_rand(0, 0xffff),
|
|
mt_rand(0, 0x0fff) | 0x4000,
|
|
mt_rand(0, 0x3fff) | 0x8000,
|
|
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
|
|
);
|
|
}
|
|
|
|
function audit_log($action, $table = null, $record_id = null, $old = null, $new = null) {
|
|
$stmt = db()->prepare("INSERT INTO audit_logs (id, user_id, action, table_name, record_id, old_values, new_values) VALUES (?, ?, ?, ?, ?, ?, ?)");
|
|
$stmt->execute([
|
|
uuid(),
|
|
$_SESSION['user_id'] ?? null,
|
|
$action,
|
|
$table,
|
|
$record_id,
|
|
$old ? json_encode($old) : null,
|
|
$new ? json_encode($new) : null
|
|
]);
|
|
}
|