Skip to content

Commit

Permalink
ITKDev: Added drush command to send line into audit log
Browse files Browse the repository at this point in the history
  • Loading branch information
cableman committed Apr 18, 2024
1 parent 7b0ca43 commit 9809589
Show file tree
Hide file tree
Showing 11 changed files with 179 additions and 62 deletions.
10 changes: 10 additions & 0 deletions modules/os2forms_audit/os2forms_audit.services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,13 @@ services:
plugin.manager.os2forms_audit_logger:
class: Drupal\os2forms_audit\Plugin\LoggerManager
parent: default_plugin_manager

os2forms_audit.logger:
class: Drupal\os2forms_audit\Service\Logger
arguments: ['@plugin.manager.os2forms_audit_logger', '@config.factory']

os2forms_audit.commands:
class: Drupal\os2forms_audit\Commands\Os2FormsAuditDrushCommands
arguments: ['@os2forms_audit.logger']
tags:
- { name: drush.command }
41 changes: 41 additions & 0 deletions modules/os2forms_audit/src/Commands/AuditLogDrushCommands.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace Drupal\os2forms_audit\Commands;

use Drupal\os2forms_audit\Service\Logger;
use Drush\Commands\DrushCommands;

/**
* Simple command to send log message into audit log.
*/
class AuditLogDrushCommands extends DrushCommands {

/**
* Os2FormsAuditDrushCommands constructor.
*
* @param \Drupal\os2forms_audit\Service\Logger $auditLogger
* Audit logger service.
*/
public function __construct(
protected readonly Logger $auditLogger
) {
parent::__construct();
}

/**
* Log a test message to the os2forms_audit logger.
*
* @param string $log_message
* Message to be logged.
*
* @command os2forms_audit:log
* @usage os2forms_audit:log 'This is a test message.'
* Logs 'This is a test message.' to the os2forms_audit logger.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
public function logMessage(string $log_message = ''): void {
$this->auditLogger->log(time(), $log_message, []);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
use Drupal\Core\Form\FormBuilderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Class to handle local taks tabs callbacks.
*/
class LocalTasksController extends ControllerBase {

/**
Expand Down Expand Up @@ -38,7 +41,7 @@ public static function create(ContainerInterface $container): LocalTasksControll
/**
* Get dynamic tasks.
*
* @param string|null $type (optional)
* @param string|null $type
* The type of form to retrieve. Defaults to NULL.
*
* @return array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,24 @@

namespace Drupal\os2forms_audit\Plugin\AuditLogger;

use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\Component\Plugin\PluginInspectionInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Plugin\PluginFormInterface;

/**
* Interface for AuditLogger plugins.
*/
interface AuditLoggerInterface extends PluginInspectionInterface {

/**
* Write the entity data.
* Logs a message with optional metadata.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be audited.
* @param int $timestamp
* The timestamp of the log entry.
* @param string $line
* The log message.
* @param array $metadata
* Additional metadata associated with the log entry. Defaults to an empty
* array.
*/
public function write(EntityInterface $entity);
public function log(int $timestamp, string $line, array $metadata = []): void;

}
45 changes: 35 additions & 10 deletions modules/os2forms_audit/src/Plugin/AuditLogger/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Drupal\os2forms_audit\Plugin\AuditLogger;

use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Plugin\PluginFormInterface;
Expand All @@ -17,7 +16,7 @@
* description = @Translation("Writes entities to a file.")
* )
*/
class File extends PluginBase implements AuditLoggerInterface, PluginFormInterface, ConfigurableInterface{
class File extends PluginBase implements AuditLoggerInterface, PluginFormInterface, ConfigurableInterface {

public function __construct(array $configuration, $plugin_id, $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
Expand All @@ -27,49 +26,75 @@ public function __construct(array $configuration, $plugin_id, $plugin_definition
/**
* {@inheritdoc}
*/
public function write(EntityInterface $entity): void {
public function log(int $timestamp, string $line, array $metadata = []): void {
// Code to write the entity to a file.
// This is just a placeholder and won't write the data.
file_put_contents('path_to_your_file.txt', serialize($entity));
file_put_contents(
$this->configuration['file'],
json_encode([
'epoc' => $timestamp,
'line' => $line,
'metadata' => $metadata,
]) . PHP_EOL,
FILE_APPEND | LOCK_EX);
}

/**
* {@inheritdoc}
*/
public function getConfiguration(): array {
return $this->configuration;
}

/**
* {@inheritdoc}
*/
public function setConfiguration(array $configuration): static {
$this->configuration = $configuration + $this->defaultConfiguration();
return $this;
}

/**
* {@inheritdoc}
*/
public function defaultConfiguration(): array {
return [
'path' => '/tmp/os2forms_audit.log',
'file' => '/tmp/os2forms_audit.log',
];
}

/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {

$form['path'] = [
$form['file'] = [
'#type' => 'textfield',
'#title' => $this->t('Full path to the audit log file to store entries in'),
'#default_value' => $this->configuration['path'],
'#title' => $this->t('The complete path and name of the file where log entries are stored.'),
'#default_value' => $this->configuration['file'],
];

return $form;
}

/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
// @todo Implement validateConfigurationForm() method.
}

public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
if (!$form_state->getErrors()) {
$values = $form_state->getValues();
$configuration = [
'path' => $values['path'],
'file' => $values['file'],
];
$this->setConfiguration($configuration);
}
}

}
31 changes: 23 additions & 8 deletions modules/os2forms_audit/src/Plugin/AuditLogger/Loki.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Drupal\os2forms_audit\Plugin\AuditLogger;

use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Plugin\PluginFormInterface;
Expand All @@ -27,27 +26,37 @@ public function __construct(array $configuration, $plugin_id, $plugin_definition
/**
* {@inheritdoc}
*/
public function write(EntityInterface $entity): void {

// Then log the action like this:
\Drupal::logger('os2forms_audit')->notice('Entity with ID @id is written.', ['@id' => $entity->id()]);
public function log(int $timestamp, string $line, array $metadata = []): void {
// @todo use loki client to send message to loki
}

/**
* {@inheritdoc}
*/
public function getConfiguration(): array {
return $this->configuration;
}

/**
* {@inheritdoc}
*/
public function setConfiguration(array $configuration): static {
$this->configuration = $configuration + $this->defaultConfiguration();
return $this;
}

/**
* {@inheritdoc}
*/
public function defaultConfiguration(): array {
return [
'entrypoint' => 'http://loki:3100'
'entrypoint' => 'http://loki:3100',
];
}

/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
$form['entrypoint'] = [
'#type' => 'url',
Expand Down Expand Up @@ -81,6 +90,9 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta
return $form;
}

/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state): void {
$values = $form_state->getValues();

Expand All @@ -101,7 +113,7 @@ public function validateConfigurationForm(array &$form, FormStateInterface $form

$curlOptions = array_filter(explode(',', $values['curl_options']));
foreach ($curlOptions as $option) {
[$key,] = explode(' =>', $option);
[$key] = explode(' =>', $option);
$key = trim($key);
if (!defined($key)) {
$form_state->setErrorByName('curl_options', $this->t('%option is not a valid cURL option.', ['%option' => $key]));
Expand All @@ -110,14 +122,17 @@ public function validateConfigurationForm(array &$form, FormStateInterface $form
}
}

/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
if (!$form_state->getErrors()) {
$values = $form_state->getValues();
$configuration = [
'entrypoint' => $values['entrypoint'],
'auth' => [
'username' => $values['auth']['username'],
'password' => $values['auth']['password']
'password' => $values['auth']['password'],
],
'curl_options' => $values['curl_options'],
];
Expand Down
13 changes: 7 additions & 6 deletions modules/os2forms_audit/src/Plugin/AuditLogger/Watchdog.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace Drupal\os2forms_audit\Plugin\AuditLogger;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginBase;

/**
Expand All @@ -20,10 +18,13 @@ class Watchdog extends PluginBase implements AuditLoggerInterface {
/**
* {@inheritdoc}
*/
public function write(EntityInterface $entity): void {
// Code to write the $entity data to a file as an audit entry.
public function log(int $timestamp, string $line, array $metadata = []): void {
$data = '';
array_walk($metadata, function ($val, $key) use (&$data) {
$data .= " $key=\"$val\"";
});

// Then log the action like this:
\Drupal::logger('os2forms_audit')->info('Entity with ID @id is written.', ['@id' => $entity->id()]);
\Drupal::logger('os2forms_audit')->info($line . ' (%data)', ['data' => $data]);
}

}
5 changes: 3 additions & 2 deletions modules/os2forms_audit/src/Plugin/Derivative/LocalTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

namespace Drupal\os2forms_audit\Plugin\Derivative;

use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\os2forms_audit\Plugin\LoggerManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
Expand All @@ -19,6 +17,9 @@ public function __construct(
) {
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id): LocalTask|static {
return new static(
$container->get('plugin.manager.os2forms_audit_logger')
Expand Down
8 changes: 3 additions & 5 deletions modules/os2forms_audit/src/Plugin/LoggerManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

namespace Drupal\os2forms_audit\Plugin;

use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;

/**
* Provides the Fruit plugin manager.
* Provides the Logger plugin manager.
*
* @see \Drupal\os2forms_audit\Annotation\AuditLoggerProvider
* @see \Drupal\os2forms_audit\Plugin\AuditLogger\AuditLoggerInterface
Expand All @@ -16,10 +16,9 @@
class LoggerManager extends DefaultPluginManager {

/**
* Constructor for FruitManager objects.
* Constructor for LoggerManager objects.
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {

parent::__construct(
'Plugin/AuditLogger',
$namespaces,
Expand All @@ -28,7 +27,6 @@ public function __construct(\Traversable $namespaces, CacheBackendInterface $cac
'Drupal\os2forms_audit\Annotation\AuditLoggerProvider',
);


$this->alterInfo('os2forms_audit_logger_info');
$this->setCacheBackend($cache_backend, 'os2forms_audit_logger_plugins');
}
Expand Down
Loading

0 comments on commit 9809589

Please sign in to comment.