hotrush / laravel-signer
Package to create and validate signatures for laravel models.
1.1.0
2023-03-01 10:57 UTC
Requires
- php: ^8.1
- illuminate/contracts: ^9.0|^10.0
- spatie/laravel-package-tools: ^1.13.0
Requires (Dev)
- laravel/pint: ^1.0
- nunomaduro/collision: ^6.0
- nunomaduro/larastan: ^2.0.1
- orchestra/testbench: ^7.0
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
- phpunit/phpunit: ^9.5|^10.0
This package is auto-updated.
Last update: 2024-11-29 14:46:45 UTC
README
Laravel Signer
Package to create and validate signatures for laravel models.
Installation
composer require hotrush/laravel-signer
Usage
-
Add
Signable
contract to your modeluse Hotrush\Signer\Contracts\Signable; class Post extends Model implements Signable { }
-
Implement contract methods. To simplify this process
CanBeSigned
trait can be used.use Hotrush\Signer\Contracts\Signable; use Hotrush\Signer\Contracts\Traits\CanBeSigned; class Post extends Model implements Signable { use CanBeSigned; /** * Return null if never expires. * * @return Carbon|null */ public function getSignExpiration(): ?Carbon { return null; } /** * Payload used for making signature hash. * * @return array */ public function getSignPayload(): array { return [ $this->getKeyName() => $this->getKey(), 'field' => $this->field, ]; } /** * Payload put into encoded code. Will be publicly accessible. * * @return array */ public function getPublicSignPayload(): array { return [ $this->getKeyName() => $this->getKey(), ]; } /** * Define where clause for getting signable model instance by signature. * Only values from public payload can be used. */ public static function signableClauses(Signature $signature): \Closure { return function (Builder $query) use ($signature) { $query->where('id', '=', $signature->payload['id']); }; } }
-
Use facade to generate signature
use Hotrush\Signer\Facades\Signer; $signable = Post::find(1); $signature = Signer::generate($signable); echo (string) $signature;
Signature can be converted into a string and send a confirmation code for example.
-
To verify code facade can be used as well. But first need to decode signature.
use Hotrush\Signer\Facades\Signer; use Hotrush\Signer\Signature; // decode signature $signature = Signature::decode('signature-string-value'); // get signable $signable = Post::findSignable($signature); // verify $valid = Signer::validate($signable, $signature);
Testing
composer test