80 lines
2.8 KiB
PHP
80 lines
2.8 KiB
PHP
<?php
|
|
namespace App\Models;
|
|
|
|
use App\Helpers\Security;
|
|
|
|
/**
|
|
* Class AuditLog
|
|
* Enterprise Audit Trail Logger (OWASP Non-repudiation Compliance)
|
|
*
|
|
* @package App\Models
|
|
*/
|
|
class AuditLog extends Model
|
|
{
|
|
protected string $table = 'audit_logs';
|
|
|
|
/**
|
|
* Record an audit trail log entry
|
|
*
|
|
* @param string $action e.g. 'LOGIN_SUCCESS', 'QUEUE_CREATE', 'SOAP_SIGN'
|
|
* @param string $entityType e.g. 'users', 'queues', 'soap_notes'
|
|
* @param int|null $entityId
|
|
* @param array|null $oldValues
|
|
* @param array|null $newValues
|
|
* @param int|null $userId
|
|
* @param int|null $branchId
|
|
*/
|
|
public static function record(
|
|
string $action,
|
|
string $entityType,
|
|
?int $entityId = null,
|
|
?array $oldValues = null,
|
|
?array $newValues = null,
|
|
?int $userId = null,
|
|
?int $branchId = null
|
|
): void {
|
|
try {
|
|
$log = new self();
|
|
$log->create([
|
|
'user_id' => $userId ?? ($_SESSION['user_id'] ?? null),
|
|
'branch_id' => $branchId ?? ($_SESSION['branch_id'] ?? 1),
|
|
'action' => $action,
|
|
'entity_type' => $entityType,
|
|
'entity_id' => $entityId,
|
|
'old_values' => $oldValues ? json_encode($oldValues, JSON_UNESCAPED_UNICODE) : null,
|
|
'new_values' => $newValues ? json_encode($newValues, JSON_UNESCAPED_UNICODE) : null,
|
|
'ip_address' => Security::getClientIp(),
|
|
'user_agent' => substr($_SERVER['HTTP_USER_AGENT'] ?? 'CLI/Unknown', 0, 255),
|
|
'created_at' => date('Y-m-d H:i:s'),
|
|
]);
|
|
} catch (\Throwable $e) {
|
|
// ห้ามให้การบันทึก Log ล้มเหลวไปกระทบการทำงานหลักของระบบ แต่บันทึกลง Error Log
|
|
error_log("AuditLog Record Failed: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get recent audit trails by branch or user
|
|
*/
|
|
public function getRecent(int $branchId = null, int $limit = 100): array
|
|
{
|
|
$sql = "SELECT a.*, CONCAT(u.first_name, ' ', u.last_name) AS user_name, u.role
|
|
FROM `{$this->table}` a
|
|
LEFT JOIN `users` u ON a.user_id = u.id ";
|
|
$params = [];
|
|
if ($branchId !== null) {
|
|
$sql .= " WHERE a.branch_id = :bid ";
|
|
$params['bid'] = $branchId;
|
|
}
|
|
$sql .= " ORDER BY a.id DESC LIMIT :lim";
|
|
|
|
$stmt = self::getDB()->prepare($sql);
|
|
if ($branchId !== null) {
|
|
$stmt->bindValue(':bid', $branchId, \PDO::PARAM_INT);
|
|
}
|
|
$stmt->bindValue(':lim', $limit, \PDO::PARAM_INT);
|
|
$stmt->execute();
|
|
return $stmt->fetchAll();
|
|
}
|
|
}
|