uogsoe/hash-model-id

为模型添加 HashID ->id_hash 属性的非常基础的特质

1.0.0 2018-05-26 15:31 UTC

This package is auto-updated.

Last update: 2024-09-22 01:31:58 UTC


README

此包提供了一个非常基础的特质,可以为模型返回一个6个字符以上的hashid,用于模型中的$id_hash属性。它主要用于我们在错误报告时最小化泄露'真实'ID。例如,可能对向Rollbar等第三方服务报告时符合GDPR的规定。

该包设计为无配置和简单易用,它是为了覆盖我们简单地混淆ID用于报告的用例。如果您需要更可配置或更安全的解决方案,请不要使用它 :-)

安装

composer require uogsoe/hash-model-id

用法

在您的模型中(通常是您的App\User)添加CanHashUserIds特质

<?php

namespace App;

use UoGSoE\ModelHashIds\CanHashUserIds;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
    use CanHashUserIds;

    // ...
}

然后您可以通过调用$user->id_hash来获取该模型的唯一hashid。例如,如果您正在使用Rollbar,您可以将它设置为在错误报告中使用人属性中的hash,例如

// app/Exceptions/Handler.php

    public function report(Exception $exception)
    {
        if (Auth::check() && $this->shouldReport($exception)) {
            $user = Auth::user();
            \Log::error($exception->getMessage(), [
                'person' => ['id' => $user->id_hash]
            ]);
        }
        parent::report($exception);
    }

要将hash解码回模型ID,您需要执行类似以下操作(例如在tinker中)

(new UoGSoE\ModelHashIds\Hasher)->decode("the-hash");

故意没有提供简单的$model->decode('the-hash')方法,以减少泄露的风险。

内部机制

hashids基于您的.env APP_KEY字符串,因此如果您决定更改它,那么从->id_hash调用中获取的hash将不同。hash至少有六个字符长,因为基本上六个字符在复制粘贴时很容易用鼠标点击到 ;-)

该特质只是对原始hashids库的一个非常简单的包装,所有荣誉都归原始开发者。