db = Database::getInstance(); } /** * Validate API key */ public function validateApiKey($clientId, $clientSecret) { $sql = "SELECT ak.*, au.username, au.nama_lengkap, au.email, au.timo_user FROM api_keys ak JOIN admin_users au ON au.id = ak.admin_user_id WHERE ak.client_id = :client_id AND ak.client_secret = :client_secret AND ak.is_active = 1 LIMIT 1"; $result = $this->db->fetchOne($sql, [ 'client_id' => $clientId, 'client_secret' => $clientSecret ]); if ($result) { // Update last_used_at $this->updateLastUsed($result->id); // Log successful validation $this->logApiUsage($result->id, 'validation', 'success'); return $result; } // Log failed validation $this->logApiUsage(null, 'validation', 'failed', ['client_id' => $clientId]); return false; } /** * Log API usage */ public function logApiUsage($apiKeyId, $endpoint, $status, $data = []) { $ipAddress = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'; $this->db->insert('api_logs', [ 'api_key_id' => $apiKeyId, 'endpoint' => $endpoint, 'status' => $status, 'request_data' => json_encode($data), 'ip_address' => $ipAddress, 'user_agent' => $userAgent, 'created_at' => date('Y-m-d H:i:s') ]); } /** * Get API key by ID */ public function getById($id) { $sql = "SELECT * FROM api_keys WHERE id = :id LIMIT 1"; return $this->db->fetchOne($sql, ['id' => $id]); } /** * Update last used timestamp */ public function updateLastUsed($id) { try { $this->db->update('api_keys', [ 'last_used_at' => date('Y-m-d H:i:s') ], 'id = :id', ['id' => $id]); } catch (\Exception $e) { // Ignore error jika column belum ada error_log("Warning: Could not update last_used_at: " . $e->getMessage()); } } }