deegitalbe/laravel-trustup-io-audit

我们的包负责处理审计日志的创建。

v0.1.3 2023-11-06 11:19 UTC

README

安装

sail composer require deegitalbe/laravel-trustup-io-audit

.env(非必需)

TRUSTUP_IO_AUDIT_URL=

🙇 致谢

请将此列添加到您的迁移/模型中。它代表您的关联。

如果它与您的项目冲突,请随意更改其名称。

trustup_io_audit_log_uuids

🛠️ 默认使用

<?php

class TicketExample extends AbstractModel implements TrustupIoAuditRelatedModelContract
{
    use IsDefaultTrustupIoAuditRelatedModel;

    // The trait define already all necessary methods you will need to make your logs
    // By default it will take all attributes on your model like below 
        # public function getTrustupIoAuditPayload(): array
        # {
        #     return $this->getAttributes();
        # }
}

🛠️ 您也可以设置自定义属性

<?php

class TicketExample extends AbstractModel implements TrustupIoAuditRelatedModelContract

{
    use IsTrustupIoAuditRelatedModel;

    public function getTrustupIoAuditPayload(): array
    {
        // this will add your custom_attributes in your log payload for your current model.
        // It needs to return en array as the return type specify.
        return [
            $this->custom_attributes
            ];
    }
}

🛠️ 默认实现与关联

如果您需要更多有关关系如何工作的文档,请参阅 laravel-trustup-io-external-model-relation。在这里,您需要定义必要的检索日志的方法。

<?php

class TicketExample extends AbstractModel implements TrustupIoAuditRelatedModelWithRelationsContract
{
    use IsTrustupIoAuditRelatedModelWithRelations, IsExternalModelRelatedModel;

    // By default the relation name is set to trustupIoAuditLogs.

    public function getTrustupIoAuditPayload(): array
    {
        // here you can set all attributes that you want to log for your model
        // It needs to return en array as the return type specify.
        return $this->getAttributes();
    }
}

🛠️ 自定义实现与关联

如果您需要更多有关关系如何工作的文档,请参阅 laravel-trustup-io-external-model-relation

准备您的模型。

<?php

class TicketExample extends AbstractModel implements TrustupIoAuditRelatedModelContract
{
    use IsTrustupIoAuditRelatedModel, IsExternalModelRelatedModel;

    /**
     * Getting external relation names.
     *
     * @return array<int, string>
     */
    public function getExternalRelationNames(): array
    {
        return [
            'trustupIoAuditLogs'
        ];
    }

    public function getTrustupIoAuditLogColumn(): string
    {
        return 'trustup_io_audit_log_uuids';
    }

    public function trustupIoAuditLogs(): ExternalModelRelationContract
    {
        return $this->hasManyExternalModels(app()->make(TrustupIoLogLoadingCallback::class), $this->getTrustupIoAuditLogColumn());
    }

    /** @return Collection<int, ExternalModelContract> */
    public function getTrustupIoAuditLogs(): Collection
    {
        return $this->getExternalModels('trustupIoAuditLogs');
    }

    public function getTrustupIoAuditPayload(): array
    {
        // here you can set all attributes that you want to log for your model
        // It needs to return en array as the return type specify.
        return $this->getAttributes();
    }
}

🛠️ 通过创建资源公开您的模型

您可以使用包中的预定义资源来存储日志。

<?php

namespace App\Http\Resources;

use Deegitalbe\LaravelTrustupIoAudit\Resources\LogResource;
use Deegitalbe\LaravelTrustupIoExternalModelRelations\Traits\Resources\IsExternalModelRelatedResource;

class TicketExampleResource
{
    use IsExternalModelRelatedResource;


    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'text' => $this->text,
            'created_at' => $this->created_at,
            'logs' => LogResource::collection($this->whenExternalRelationLoaded('trustupIoAuditLogs')),
        ];
    }
}

🙇 🛠️ 适配器配置发布。

如有必要,请按以下方式覆盖它

sail artisan vendor:publish --provider="Deegitalbe\LaravelTrustupIoAudit\Providers\LaravelTrustupIoAuditServiceProvider" --tag="config"

🛠️ 默认适配器配置。

默认情况下,配置使用包适配器来设置一些属性。

如果您希望创建自己的适配器,您可以在配置中覆盖它,并且应该实现 LogServiceAdapterContract。

<?php

namespace Deegitalbe\LaravelTrustupIoAudit\Services\Logs\Adapters;

use Deegitalbe\LaravelTrustupIoAudit\Contracts\Services\Logs\Adapters\LogServiceAdapterContract;
use Deegitalbe\LaravelTrustupIoAudit\Facades\TrustupIoAudit;

class LogServiceAdapter implements LogServiceAdapterContract
{
    /** Application key */
    public function getAppKey(): string
    {
        return TrustupIoAudit::getConfig("app_key");
    }

    /** Responsible identifier */
    public function getResponsibleId(): string
    {
        return auth()->id();
    }

    /** type of the responsible */
    public function getResponsibleType(): string
    {
        return 'user';
    }

    /** account identifier */
    public function getAccountUuid(): ?string
    {
        return null;
    }
    /** Case the log was impersonated by */
    public function getImpersonatedBy(): ?string
    {
        return null;
    }
}

⚡ 预加载集合

即使您加载多个关联,也只会执行一个请求

use Illuminate\Routing\Controller;

class PostController extends Controller
{
    public function index()
    {
        return TicketExampleResource::collection(TicketExample::all()->loadExternalRelations('trustupIoAuditLogs'));
    }
}

⚡⚡ 迁移关系特性。

默认情况下,列设置为 trustup_io_audit_log_uuids,但您可以自由更改它。

<?php

namespace Deegitalbe\LaravelTrustupIoAudit\Tests\Unit\database\migrations;

use Deegitalbe\LaravelTrustupIoAudit\Services\Logs\Traits\TrustupioAuditRelatedMigrations;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    use TrustupioAuditRelatedMigrations;
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->nullable();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });
        $this->addAUditLogColumn('users', 'trustup_io_audit_log_uuids');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
        // $this->removeAuditLogColumn('users', 'trustup_io_audit_log_uuids');
    }
}

⚡⚡⚡ TrustupIoAudit 门面用于。

门面上的可用方法。

    public static function prefix(): string
    {
        return "laravel-trustup-io-audit";
    }

    /**
    * Mock laravel audit log.
    * Enabling logging during tests.
    */
    public function mock(): MockInterface
    {
        return $this->logStatus->mock();
    }

    /**
     * Disable Logging
     */
    public function disable(): void
    {
        $this->logStatus->disable();
    }

    /**
     * Enable Logging
     */
    public function enable(): void
    {
        $this->logStatus->enable();
    }

    /**
     * Store given attributes as log manually.
     */
    public function storeAttributes(string $eventName, array $attributes): ?string
    {
        return $this->logService->storeAttributes($eventName, $attributes);
    }

     /**
     * Store given requests as log manually.
     */
    public function storeRequest(StoreLogRequestContract $request): ?string
    {
        return $this->logService->storeRequest($request);
    }

⚡⚡⚡⚡ 注意默认情况下,包可以猜测它需要向哪个API发送请求。

因此,您不需要指定任何URL,只需指定您的环境即可。

<?php

namespace Deegitalbe\LaravelTrustupIoAudit;

...

    public function getUrl(): string
    {
        if ($environmentUrl = env("TRUSTUP_IO_AUDIT_URL")) return $environmentUrl;
        if (app()->environment("staging")) return "https://staging.audit.trustup.io";
        if (app()->environment("production")) return "https://audit.trustup.io";

        return "trustup-io-audit";
    }