Giter VIP home page Giter VIP logo

banhammer's Introduction

Banhammer, a Model, IP and Country ban package for Laravel

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

Banhammer for Laravel offers a very simple way to ban any Model by ID and by IP. It also allows to block requests by IP addresses.

Banned models can have an expiration date and will be automatically unbanned using the Scheduler.

Table of Contents

  1. Introduction
  2. Version Compatibility
  3. Installation
  4. Upgrading To 2.0 from 1.x
  5. Usage
  6. Testing
  7. Changelog
  8. Roadmap / Todo
  9. Contributing
  10. Security Vulnerabilities
  11. Credits
  12. License

Version Compatibility

Laravel Banhammer
^9.0 1.x, 2.x
^10.0 1.x, 2.x
^11.0 1.x, 2.x

Installation

You can install the package via composer:

composer require mchev/banhammer

Then run the migrations with:

php artisan migrate

You can publish the config file with:

php artisan vendor:publish --tag="banhammer-config"

It is possible to define the table name and the fallback_url in the config/ban.php file.

Upgrading To 2.0 from 1.x

To upgrade to Banhammer version 2.0, follow these simple steps:

  1. Update the package version in your application's composer.json file:
"require": {
    "mchev/banhammer": "^2.0"
}
  1. Run the following command in your terminal:
composer update mchev/banhammer
  1. Update the configuration

    1. Update the configuration
      • Backup your previous configuration file located at config/ban.php.
      • Force republish the new configuration using the command:
      php artisan vendor:publish --tag="banhammer-config" --force
      • Review the new configuration file and make any necessary edits.

Usage

To make a model bannable, add the Mchev\Banhammer\Traits\Bannable trait to the model:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Mchev\Banhammer\Traits\Bannable;

class User extends Authenticatable
{
    use Bannable;
}

You can add the Bannable trait on as many models as you want (Team, Group, User, etc.).

Ban / Unban

Simple ban

$user->ban();

Without the expired_at attribute specified, the user will be banned forever.

IP Ban

$user->ban([
	'ip' => $user->ip,
]);

Full

All attributes are optional

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

Shorthand

$user->banUntil('2 days');

Check if model is banned.

You can create custom middlewares using these methods.

$model->isBanned();
$model->isNotBanned();

List model bans

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

// Expired bans
$expired = $model->bans()->expired()->get();

// Not expired and permanent bans
$notExpired = $model->bans()->notExpired()->get();

Filters

$bannedTeams = Team::banned()->get(); 
$notBannedTeams = Team::notBanned()->get();

Unban

$user->unban();

IP

Ban IPs

use Mchev\Banhammer\IP;

IP::ban("8.8.8.8");
IP::ban(["8.8.8.8", "4.4.4.4"]);

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

// Full
IP::ban(
    "8.8.8.8", 
    [
        "MetaKey1" => "MetaValue1",
        "MetaKey2" => "MetaValue2",
    ], 
    now()->addMinutes(10)
);

Unban IPs

use Mchev\Banhammer\IP;

IP::unban("8.8.8.8");
IP::unban(["8.8.8.8", "4.4.4.4"]);

List all banned IPs

use Mchev\Banhammer\IP;

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

Metas

Ban IP with metas

use Mchev\Banhammer\IP;

IP::ban("8.8.8.8", [
	'route' => request()->route()->getName(),
	'user_agent' => request()->header('user-agent')
]);

Metas usage

$ban->setMeta('username', 'Jane');
$ban->getMeta('username'); // Jane
$ban->hasMeta('username'); // boolean
$ban->forgetMeta('username');

Filtering by Meta

IP::banned()->whereMeta('username', 'Jane')->get();
// OR
$users->bans()->whereMeta('username', 'Jane')->get();
// OR
$users->whereBansMeta('username', 'Jane')->get();

Blocking Access from Specific Countries

To enhance the security of your application, you can restrict access from specific countries by enabling the country-blocking feature in the configuration file. Follow these simple steps:

  1. Open your Banhammer configuration file (config/ban.php).

  2. Set the 'block_by_country' configuration option to true to enable country-based blocking.

'block_by_country' => true,
  1. Specify the list of countries you want to block by adding their country codes to the 'blocked_countries' array.
'blocked_countries' => ['FR', 'ES'],

By configuring these settings, you effectively block access to your application for users originating from the specified countries. This helps improve the security and integrity of your system by preventing unwanted traffic from regions you've identified as potential risks.

Important Notice: The Banhammer package utilizes the free version of ip-api.com for geolocation data. Keep in mind that their endpoints have a rate limit of 45 HTTP requests per minute from a single IP address. If you exceed this limit, your requests will be throttled, and you may receive a 429 HTTP status code until your rate limit window is reset.

Developer Note: While Banhammer currently relies on the free version of ip-api.com for geolocation data, I'm open to exploring better alternatives. If you have suggestions for a more robust or efficient solution, or if you'd like to contribute improvements, please feel free to open an issue or submit a pull request.

Middleware

To prevent banned users from accessing certain parts of your application, simply add the auth.banned middleware on the concerned routes.

Route::middleware(['auth.banned'])->group(function () {
    // ...
});

To prevent banned ips from accessing certain parts of your application, simply add the ip.banned middleware on the concerned routes.

Route::middleware(['ip.banned'])->group(function () {
    // ...
});

To block and logout banned Users or IP, add the logout.banned middleware:

Route::middleware(['logout.banned'])->group(function () {
    // ...
});

If you use the logout.banned middleware, it is not necessary to cumulate the other middlewares.

If you want to block IPs on every HTTP request of your application, list Mchev\Banhammer\Middleware\IPBanned in the $middleware property of your app/Http/Kernel.php class.

Scheduler

โš  IMPORTANT

In order to be able to automatically delete expired bans, you must have a cron job set up on your server to run the Laravel Scheduled Jobs

Running the scheduler

Configure Scheduler on Forge

Events

If entity is banned Mchev\Banhammer\Events\ModelWasBanned event is fired.

Is entity is unbanned Mchev\Banhammer\Events\ModelWasUnbanned event is fired.

MISC

To manually unban expired bans :

use Mchev\Banhammer\Banhammer;

Banhammer::unbanExpired();

Or you can use the command:

php artisan banhammer:unban

To permanently delete all the expired bans :

use Mchev\Banhammer\Banhammer;

Banhammer::clear();

Or you can use the command:

php artisan banhammer:clear

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Roadmap / Todo

  • Laravel pulse card (ips banned, block by country enabled, etc.).
  • Block by country feature

Contributing

To encourage active collaboration, Banhammer strongly encourages pull requests, not just bug reports. Pull requests will only be reviewed when marked as "ready for review" (not in the "draft" state) and all tests for new features are passing. Lingering, non-active pull requests left in the "draft" state will be closed after a few days.

However, if you file a bug report, your issue should contain a title and a clear description of the issue. You should also include as much relevant information as possible and a code sample that demonstrates the issue. The goal of a bug report is to make it easy for yourself - and others - to replicate the bug and develop a fix.

Remember, bug reports are created in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the bug report will automatically see any activity or that others will jump to fix it.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

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

banhammer's People

Contributors

mchev avatar mepsd avatar yazeedalsaif avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

banhammer's Issues

Banning models forever

What happened?

There is a method for banning users until specific date: $user->banUntil('2 days'); But, What if I need ban that user forever?
Sorry about creating this discussion as bug, link for "Request a feature" doesn't works.

How to reproduce the bug

Is not possible ban an user forever.

Package Version

1.1.5

PHP Version

8.1

Laravel Version

10

Which operating systems does with happen with?

Linux

Notes

No response

[feature request]: Expiration date for banned IPs

What happened?

Is it possible to add expiration date for banned IPs?

How to reproduce the bug

Is it possible to add expiration date for banned IPs?

Package Version

last

PHP Version

8.1

Laravel Version

10

Which operating systems does with happen with?

Linux

Notes

No response

$user->ban(); Not Working

What happened?

use the library then error

How to reproduce the bug

// My code
Route::get('/ban-user', function () {

$user = User::findOrFail(1);
$user->ban();

});

// Error

$user->ban();

Call to undefined method App\Models\User::ban()

Package Version

2.0

PHP Version

8.0.26

Laravel Version

9.19

Which operating systems does with happen with?

No response

Notes

No response

Add configurable Model

Some package usually allow to modify the Model that the package is use. This will allow user to add some functionality to package model, for example adding a cache layer.

[Feat]: What about having custom properties while banning user

What happened?

I was wondering if there was a way to set custom properties while banning a user; I know there is a comment field for that, but it would be great if we could save the activity, limit API requests, or prevent access to data that the user shouldn't be seeing; all of these things could be options where they could pass these custom properties and see whenever they review.

How to reproduce the bug

NA

Package Version

1.1

PHP Version

8.1

Laravel Version

10

Which operating systems does with happen with?

Linux

Notes

No response

Support UUIDs (or publish migrations)

Our system uses UUIDs, and the current migrations dont support it. We're left with the choice of running a second migration to fix the first one, or forking the package.

Having UUID support would be great, but if thats not possible then publishing the migrations instead of loading them would provide the necessary level of customisability.

[Bug]: N+1 Query when checking model is banned

What happened?

Checking model is banned while looping on list make N+1 Query even the relationship is eager loaded.

How to reproduce the bug

$users = User::with(['bans'])->get();
foreach ($users as $user) {
    $user->isBanned();
}

Package Version

1.2.0

PHP Version

8.2.6

Laravel Version

10.13.2

Which operating systems does with happen with?

macOS

Notes

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.