定制 mchev/banhammer 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mchev/banhammer

Composer 安装命令:

composer require mchev/banhammer

包简介

Banhammer for Laravel allows you to ban any Model by key and by IP.

README 文档

README

A simple and powerful ban package for Laravel - ban models, IPs, and countries with ease.

Latest Version on Packagist GitHub Tests Action Status Total Downloads Package for laravel

Banhammer allows you to ban any Eloquent model, IP addresses, and even entire countries. Bans can be permanent or temporary with automatic expiration.

📋 Table of Contents

🚀 Quick Start

composer require mchev/banhammer
php artisan vendor:publish --provider="Mchev\Banhammer\BanhammerServiceProvider" --tag="migrations"
php artisan migrate

Add the trait to your model:

use Mchev\Banhammer\Traits\Bannable;

class User extends Model
{
    use Bannable;
}

Ban a user:

$user->ban();

✨ Features

  • ✅ Ban any Eloquent model (User, Team, etc.)
  • ✅ Ban IP addresses (single or multiple)
  • ✅ Block entire countries
  • ✅ Temporary or permanent bans
  • ✅ Automatic expiration handling
  • ✅ Middleware protection
  • ✅ Event system
  • ✅ Metadata support

📦 Installation

Requirements

  • PHP 8.0+

Laravel compatibility

Laravel Supported since Banhammer
9.x v1.0.0
10.x v1.0.0
11.x v2.2.0
12.x v2.4.0
13.x v2.5.0

Setup

  1. Install the package:

    composer require mchev/banhammer
  2. Publish and run migrations:

    php artisan vendor:publish --provider="Mchev\Banhammer\BanhammerServiceProvider" --tag="migrations"
    php artisan migrate
  3. Publish config (optional):

    php artisan vendor:publish --provider="Mchev\Banhammer\BanhammerServiceProvider" --tag="config"

    💡 The config file allows you to customize table name, model, fallback URLs, and more.

📖 Usage Guide

Banning Models

Make a Model Bannable

Add the Bannable trait to any model:

use Mchev\Banhammer\Traits\Bannable;

class User extends Model
{
    use Bannable;
}

💡 You can add the trait to multiple models (User, Team, Group, etc.)

Basic Operations

Action Code
Ban a user $user->ban()
Ban with expiration $user->banUntil('2 days')
Check if banned $user->isBanned()
Check if not banned $user->isNotBanned()
Unban $user->unban()

Advanced Ban Options

$user->ban([
    'comment' => "You've been evil",
    'ip' => "8.8.8.8",
    'expired_at' => Carbon::now()->addDays(7),
    'created_by_type' => 'App\Models\Admin',
    'created_by_id' => auth()->id(),
    'metas' => [
        'route' => request()->route()->getName(),
        'user_agent' => request()->header('user-agent')
    ]
]);

⚠️ Without expired_at, the ban is permanent.

Query Scopes

// Get banned users
$bannedUsers = User::banned()->get();

// Get non-banned users
$activeUsers = User::notBanned()->get();

// Alternative syntax
$activeUsers = User::banned(false)->get();

List Bans

// All bans for a model
$bans = $user->bans()->get();

// Only expired bans
$expired = $user->bans()->expired()->get();

// Active bans
$active = $user->bans()->notExpired()->get();

Banning IPs

Basic Operations

use Mchev\Banhammer\IP;

// Ban single IP
IP::ban("8.8.8.8");

// Ban multiple IPs
IP::ban(["8.8.8.8", "4.4.4.4", "1.1.1.1"]);

// Ban with expiration
IP::ban("8.8.8.8", [], now()->addMinutes(10));

// Ban with metadata
IP::ban("8.8.8.8", [
    'reason' => 'spam',
    'severity' => 'high'
]);

Unban IPs

// Unban single IP
IP::unban("8.8.8.8");

// Unban multiple IPs
IP::unban(["8.8.8.8", "4.4.4.4"]);

Check & List Banned IPs

// Check if IP is banned
IP::isBanned("8.8.8.8"); // bool

// Get all banned IPs
$ips = IP::banned()->get(); // Collection
$ips = IP::banned()->pluck('ip')->toArray(); // Array

Country Blocking

Block access from specific countries automatically.

Configuration

  1. Enable country blocking in config/ban.php:

    'block_by_country' => true,
  2. Specify blocked countries:

    'blocked_countries' => ['FR', 'ES', 'US'],

That's it! The middleware will automatically block requests from these countries.

⚠️ Rate Limit Notice: The free version of ip-api.com has a limit of 45 requests/minute. Exceeding this will result in 429 errors until the limit resets.

💡 Want to improve this? If you have suggestions for better geolocation services or want to contribute improvements, please open an issue or submit a pull request.

Middleware

Protect your routes with ban middleware:

Available Middleware

Middleware Description
auth.banned Blocks banned users
ip.banned Blocks banned IPs
logout.banned Logs out and blocks banned users/IPs

Usage

// Single route
Route::get('/dashboard', [DashboardController::class, 'index'])
    ->middleware('auth.banned');

// Route group
Route::middleware(['auth.banned'])->group(function () {
    Route::get('/profile', [ProfileController::class, 'index']);
    Route::get('/settings', [SettingsController::class, 'index']);
});

// Block IPs on all routes
// Add to app/Http/Kernel.php:
protected $middleware = [
    // ...
    \Mchev\Banhammer\Middleware\IPBanned::class,
];

💡 Tip: logout.banned includes the functionality of both auth.banned and ip.banned, so you don't need to use them together.

Scheduler

Banhammer automatically deletes expired bans using Laravel's scheduler.

Setup

⚠️ Important: You must have a cron job running Laravel's scheduler:

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

See: Laravel Scheduler Docs

Configuration

By default, the banhammer:unban command runs every minute. You can customize this:

Disable automatic scheduler:

// config/ban.php
'scheduler_enabled' => false,

Or via environment:

BANHAMMER_SCHEDULER_ENABLED=false

Change frequency:

// config/ban.php
'scheduler_periodicity' => 'everyFiveMinutes', // or 'hourly', 'daily', etc.

Or via environment:

BANHAMMER_SCHEDULER_PERIODICITY=everyFiveMinutes

Available frequencies: everyMinute, everyFiveMinutes, everyTenMinutes, everyFifteenMinutes, everyThirtyMinutes, hourly, daily, twiceDaily, etc.

Events

Listen to ban/unban events:

use Mchev\Banhammer\Events\ModelWasBanned;
use Mchev\Banhammer\Events\ModelWasUnbanned;

Event::listen(ModelWasBanned::class, function ($event) {
    // User was banned
    Log::info("User {$event->ban->bannable->id} was banned");
});

Event::listen(ModelWasUnbanned::class, function ($event) {
    // User was unbanned
    Log::info("User {$event->ban->bannable->id} was unbanned");
});

🔧 Advanced Topics

Metas

Store additional data with bans:

// Set meta
$ban->setMeta('username', 'Jane');
$ban->setMeta('reason', 'spam');

// Get meta
$ban->getMeta('username'); // 'Jane'

// Check if meta exists
$ban->hasMeta('username'); // true

// Remove meta
$ban->forgetMeta('username');

Filter by Meta

// Find bans with specific meta
IP::banned()->whereMeta('username', 'Jane')->get();
$user->bans()->whereMeta('reason', 'spam')->get();
User::whereBansMeta('username', 'Jane')->get();

Ban with Metas

// When banning
$user->ban([
    'metas' => [
        'route' => request()->route()->getName(),
        'user_agent' => request()->header('user-agent')
    ]
]);

IP::ban("8.8.8.8", [
    'reason' => 'spam',
    'severity' => 'high'
]);

UUIDs

To use UUIDs instead of auto-incrementing IDs:

  1. Publish migrations:

    php artisan vendor:publish --provider="Mchev\Banhammer\BanhammerServiceProvider" --tag="migrations"
  2. Edit the migration:

    - $table->id();
    + $table->uuid('id');
  3. Create a custom Ban model:

    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Concerns\HasUuids;
    use Mchev\Banhammer\Models\Ban as BanhammerBan;
    
    class Ban extends BanhammerBan
    {
        use HasUuids;
    }
  4. Update config:

    // config/ban.php
    'model' => \App\Models\Ban::class,

Upgrading To 2.0 from 1.x

  1. Update composer.json:

    "require": {
        "mchev/banhammer": "^2.0"
    }
  2. Update the package:

    composer update mchev/banhammer
  3. Update configuration:

    # Backup your current config
    cp config/ban.php config/ban.php.backup
    
    # Republish config
    php artisan vendor:publish --provider="Mchev\Banhammer\BanhammerServiceProvider" --tag="config" --force
    
    # Review and merge any custom settings

🛠️ Development

Commands

# Manually delete expired bans
php artisan banhammer:unban

# Permanently delete all expired bans
php artisan banhammer:clear

Programmatic Usage

use Mchev\Banhammer\Banhammer;

// Delete expired bans
Banhammer::unbanExpired();

// Permanently delete expired bans
Banhammer::clear();

Testing

composer test

🤝 Contributing

We welcome contributions! Please:

  • Open issues for bug reports or feature requests
  • Submit pull requests (mark as "ready for review")
  • Ensure all tests pass
  • Follow Laravel coding standards

💡 Pull requests in "draft" state will be closed after a few days of inactivity.

🙏 Credits

Inspired by laravel-ban from cybercog.

📄 License

The MIT License (MIT). Please see License File for more information.

mchev/banhammer 适用场景与选型建议

mchev/banhammer 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 111.63k 次下载、GitHub Stars 达 372, 最近一次更新时间为 2023 年 02 月 11 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「IP」 「country」 「ban」 「bannable」 「mchev」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mchev/banhammer 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mchev/banhammer 我们能提供哪些服务?
定制开发 / 二次开发

基于 mchev/banhammer 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 111.63k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 372
  • 点击次数: 20
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 372
  • Watchers: 2
  • Forks: 28
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-02-11