返回介绍

API Throttling

发布于 2021-11-04 22:44:46 字数 2361 浏览 948 评论 0 收藏 0

Flarum comes with a builtin Flarum\Api\Middleware\ThrottleApi middleware for throttling requests to the API. This runs on every API route, and extensions can add their own custom logic to throttle requests.

Forum Routes

Some forum routes (login, register, forgot password, etc) work by calling an API route under the surface. The ThrottleApi middleware does not currently run for these requests, but that is planned for the future.

The format for a custom throttler is extremely simple: all you need is a closure or invokable class that takes the current request as an argument, and returns one of:

  • false: This explicitly bypasses throttling for this request, overriding all other throttlers
  • true: This marks the request as to be throttled.
  • null: This means that this throttler doesn't apply. Any other outputs will be ignored, with the same effect as null.

Throttlers will be run on EVERY request, and are responsible for figuring out whether or not they apply. For example, consider Flarum's post throttler:


use DateTime;
use Flarum\Post\Post;


function ($request) {
    if (! in_array($request->getAttribute('routeName'), ['discussions.create', 'posts.create'])) {
        return;
    }


    $actor = $request->getAttribute('actor');


    if ($actor->can('postWithoutThrottle')) {
        return false;
    }


    if (Post::where('user_id', $actor->id)->where('created_at', '>=', new DateTime('-10 seconds'))->exists()) {
        return true;
    }
};

Throttlers can be added or removed via the ThrottleApi middleware in extend.php. For example:


<?php


use Flarum\Extend;


return [
    // Other extenders
    (new Extend\ThrottleApi())
        ->set('throttleAll', function () {
          return false;
        })
        ->remove('bypassThrottlingAttribute'),
    // Other extenders
];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文