RedTera
RedTera

Reputation: 103

Account wide Rate Limiting

The official Yii docs talk about adding rate limiting to an api by implementing yii\filters\RateLimitInterface on a user identity class.

https://www.yiiframework.com/doc/guide/2.0/en/rest-rate-limiting

But is it possible to implement rate limiting on classes that aren't the user class?

For example in my api a User belongs to an Account. An Account has many Users.

Is it possible to implement rate limiting per Account, rather than per User? If so how?

Upvotes: 0

Views: 368

Answers (1)

Michal Hynčica
Michal Hynčica

Reputation: 6169

You have two options how to do that.

First option is to implement RateLimitInterface in same class that implements IdentityInterface but load/store allowance in your account model. If your User model implements IdentityInterface and has Account relation it can look like this:

class User extends ActiveRecord implements IdentityInterface, RateLimitInterface
{
    public function getRateLimit($request, $action)
    {
        return [$this->account->rateLimit, 1]; // $rateLimit requests per second
    }

    public function loadAllowance($request, $action)
    {
        return [$this->account->allowance, $this->account->allowance_updated_at];
    }

    public function saveAllowance($request, $action, $allowance, $timestamp)
    {
        $this->account->allowance = $allowance;
        $this->account->allowance_updated_at = $timestamp;
        $this->account->save();
    }
    
    // ... the rest of User class definitions ...
}

The second option is to have some other class implement RateLimitInterface and use closure in yii\filters\RateLimiter::$user to return instance of that class.

Upvotes: 0

Related Questions