cdonut/laraflood

laravel 的洪水防护

v1.0 2020-08-11 19:17 UTC

This package is auto-updated.

Last update: 2024-09-11 21:20:17 UTC


README

此工具用于限制某些用户请求。

此工具基于: ircop/Laraflood,我添加/修改了一些对我当前项目有用的功能,并发布它,以防它对某人有用!

安装

1: 通过 composer 安装

composer require vincendev/laraflood

如果您使用的是 laravel 5.5:步骤 2 和 3 不必要。

2: 将服务提供者添加到 providers 数组中的 config/app.php

Vincendev\Laraflood\LarafloodServiceProvider::class,

3: 将外观别名添加到 aliases 数组中的 config/app.php

'Laraflood' => Vincendev\Laraflood\FacadeLaraflood::class,

使用方法

检查给定身份的记录是否存在并添加尝试。

$identity - 可以是 IP 地址、用户 ID、任何唯一标识符。默认是 IP 地址。

$action - 用户试图做什么?提交-post、登录、搜索等。默认是 'default'。

$maxAttempts - 您希望用户尝试多少次?默认是 5。

$seconds - 尝试结束后等待时间。默认是 5 分钟。


Laraflood::check( $identity = 'ip', $action = 'default', $maxAttempts = 5, $seconds = 300 );
Laraflood::check();
Laraflood::check( $user->id , 'submit-comment');
Laraflood::check( $user->id , 'report-comment', 1, 5);

/* Return bool */

仅检查不添加尝试。

Laraflood::checkOnly( $identity = 'ip', $action = 'default', $maxAttempts = 5, $seconds = 300 );
Laraflood::checkOnly();
Laraflood::checkOnly( $user->id , 'submit-comment');
Laraflood::checkOnly( $user->id , 'report-comment', 1, 5);

/* Return bool */

在给定的 $minutes 上给定的 $identity 进行 ·$action 尝试。默认 'ip' 是真实用户的 IP。

Laraflood::addAttempt( $identity = 'ip', $action = 'default', $seconds = 300 );
Laraflood::addAttempt();
Laraflood::addAttempt('ip', 'like-post');
Laraflood::addAttempt( $user->id ,'default', 5 );

/* Void */

获取给定身份 & 操作的剩余时间。


Laraflood::secondsLeft( $identity = 'ip', $action = 'default');
Laraflood::secondsLeft();
Laraflood::secondsLeft( 'ip', 'like-post');

/* Return string */
	# X hours
	# X minutes
	# X seconds



返回给定身份 & 操作的数组


Laraflood::get($identity = 'ip', $action = 'default')
Laraflood::get();
Laraflood::get( 'ip', 'like-post');

/*
array:3 [▼
  "action" => "default"
  "attempts" => 1
  "expiration" => "2019-09-18 19:51:01.175237"
]
*/

示例

限制给定 IP 地址的错误登录尝试

此示例限制从单个 IP 地址到每 20 分钟 5 次尝试的错误登录尝试

public function postLogin()
{
	
/**
* If thes user ip has >= 5 failed login attempts in last 5 minutes, redirect user
* back with error:
*/

	if( Laraflood::check( 'ip' , 'login', 5, 5 ) === FALSE )
		return redirect()->back()->withErrors(["AntiFlood Protection! Try again in ".Laraflood::secondsLeft('ip','login')." ."]);
	
	/**
	* Your code here..
	*/

}

增加帖子浏览量。

此代码展示了如何仅在 24 小时内增加帖子浏览量。

public function incrementPostViews()
{
		$action = "post-visit:" . $post->id; // Post unique ID
		$visitsPerUser = 1;
		$minutes = 1440; // 24Hours
        if(Laraflood::checkOnly('ip', $action, $visitsPerUser)){
			/**
			* Increment post views
			* Your code here..
			*/
			Laraflood::addAttempt('ip', $action, $minutes);
        }

}