oriamdev / encryption-user-db-auth
此包最新版本(dev-master)没有可用的许可证信息。
此包允许对数据库中所有关键字段进行双向加密。允许通过加密字段进行搜索。
dev-master
2022-05-29 12:18 UTC
This package is auto-updated.
Last update: 2024-09-29 05:57:08 UTC
README
此包允许对数据库中所有关键字段进行双向加密。
允许通过加密字段进行搜索。
安装
您可以通过composer安装此包
composer require oriamdev/encryption-db-fields
设置Eloquent模型
1 - 首先,您需要在需要加密字段时将特质EncryptAttributesTrait
添加到模型中。
use EncryptAttributesTrait;
2 - 定义要加密的字段数组
protected array $encrypts = ['name', 'email'];
3 - 如果您想通过加密字段进行搜索,您需要将数组$searchableEncrypts
添加到模型中。
protected array $searchableEncrypts = ['name', 'email'];
调整数据库表结构
注意
- 要加密的字段必须是文本类型。
- 对于每个可搜索的字段,您需要在迁移中添加一个字符串字段,名称为
field_signature
Schema::create('users', function (Blueprint $table) { $table->id(); $table->text('name'); $table->text('email'); $table->string('email_signature',10)->index(); $table->string('name_signature', 10)->index(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });
迁移数据库
php artisan migrate
CRUD操作
CRUD操作工作方式相同,加密和解密字段的过程由特质EncryptAttributesTrait
负责。
验证规则
laravel的验证规则unique and exists
不工作,但不用担心。该包有一个验证规则Oriamdev\EncryptionUserDbAuth\Rules\Encrypted
。构造函数需要模型的完全限定名称。User::class or Post::class
检查验证字段是否唯一
在创建Encrypted Rule的新实例后,您可以传递unique方法
$request->validate([ 'email' => [(new Encrypted(User::class))->unique()], ]);
如果验证失败,规则返回validation:unique
的默认值
检查验证字段是否存在
在创建Encrypted Rule的新实例后,您可以传递exists方法
$request->validate([ 'email' => [(new Encrypted(User::class))->unique()], ]);
如果验证失败,规则返回validation:unique
的默认值
$request->validate([ 'name' => [(new Encrypted(User::class))->exists()] ]);
通过加密字段进行搜索
$user = User::findByEncrypt('email', 'mario@oriamdev.com');
方法findByEncrypt
返回模型实例或不存在时返回null
。