wearesho-team/yii2-tokens

在redis数据库中存储令牌(授权、注册)。

1.1.0 2022-11-30 14:18 UTC

This package is auto-updated.

Last update: 2024-09-29 05:21:30 UTC


README

PHP Composer Latest Stable Version Total Downloads codecov

在redis数据库中存储令牌(授权、注册)。

安装

composer require wearesho-team/yii2-tokens:^1.0.0

用法

仓库

为了存储令牌,您应该使用 Repository,该仓库将接收 令牌实体 并生成 UUIDv4 哈希。然后,您可以使用生成的哈希接收令牌。

<?php

use Wearesho\Yii2\Token;

$repository = new Token\Repository([
    'redis' => 'redis', // your yii2-redis connection
]);

$token = new Token\Entity(
    $type = 'registration',
    $tokenOwner = 'foo@bar.com',
    $value = 'random-token',
    (new \DateTime())->add('PT30M') // expire after 30 minutes
);

$hash = $repository->put($token);

// If you want to receive token

$token = $repository->get($hash); // entity or null

验证行为

为了验证包含哈希、所有者和值的模型属性,您应该使用 验证行为,而不是验证器,因为这三个属性必须一次性验证。{attribute} 无效。 消息将被添加到属性错误中,并且验证将失败(beforeValidate 事件)。

<?php

use yii\base;
use Wearesho\Yii2\Token;

class Model extends base\Model {
    /** @var string */
    public $hash;
    
    /** @var string */
    public $tokenOwner; // or `phone`, `email` etc.
    
    /** @var string */
    public $token;
    
    public function behaviors(): array
    {
        return [
            'validateToken' => [
                'class' => Token\ValidationBehavior::class,
                'type' => 'registration',
            ],    
        ];
    }
    
    public function rules(): array
    {
        return [
            [['hash', 'tokenOwner', 'token',], 'safe',], // to load using $model->load    
        ];
    }
}

$repository = new Token\Repository;

$model = new Model;
$model->hash = 'some-invalid-hash';
$model->owner = 'foo@bar.com';
$model->token = 'some-random-token';

$model->validate(); // false

$hash = $repository->put(new Token\Entity(
    'registration',
    $model->tokenWwner,
    $model->token,
    (new \DateTime)->add(new \DateInterval('PT1M'))
));

$model->hash = $hash;

$model->validate(); // true

待办事项

  • 修复测试,以便依赖方法调用的顺序(升级PHPUnit到10)

贡献者

许可证

MIT