GithubHelp home page GithubHelp logo

cybercog / laravel-ban Goto Github PK

View Code? Open in Web Editor NEW
1.0K 15.0 64.0 154 KB

Laravel Ban simplify blocking and banning Eloquent models.

Home Page: https://komarev.com/sources/laravel-ban

License: MIT License

PHP 97.33% Dockerfile 2.67%
laravel eloquent cog trait ban jail block access security package justice restrict forbid arrest user prison sanction php

laravel-ban's Introduction

Laravel Ban

cog-laravel-ban

Discord Releases Build StyleCI Code Quality License

Introduction

Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes!

Use case is not limited to User model, any Eloquent model could be banned: Organizations, Teams, Groups and others.

Contents

Features

  • Model can have many bans.
  • Removed bans kept in history as soft deleted records.
  • Most parts of the logic is handled by the BanService.
  • Has middleware to prevent banned user route access.
  • Use case is not limited to User model, any Eloquent model could be banned.
  • Events firing on models ban and unban.
  • Designed to work with Laravel Eloquent models.
  • Has Laravel Nova support.
  • Using contracts to keep high customization capabilities.
  • Using traits to get functionality out of the box.
  • Following PHP Standard Recommendations:
  • Covered with unit tests.

Installation

First, pull in the package through Composer:

composer require cybercog/laravel-ban

Registering package

The package will automatically register itself. This step required for Laravel 5.4 or earlier releases only.

Include the service provider within app/config/app.php:

'providers' => [
    Cog\Laravel\Ban\Providers\BanServiceProvider::class,
],

Apply database migrations

At last, you need to publish and run database migrations:

php artisan vendor:publish --provider="Cog\Laravel\Ban\Providers\BanServiceProvider" --tag="migrations"
php artisan migrate

Usage

Prepare bannable model

use Cog\Contracts\Ban\Bannable as BannableInterface;
use Cog\Laravel\Ban\Traits\Bannable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements BannableInterface
{
    use Bannable;
}

Prepare bannable model database table

Bannable model must have nullable timestamp column named banned_at. This value used as flag and simplify checks if user was banned. If you are trying to make default Laravel User model to be bannable you can use example below.

Create a new migration file

php artisan make:migration add_banned_at_column_to_users_table

Then insert the following code into migration file:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->timestamp('banned_at')->nullable();
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('banned_at');
        });
    }
};

Available methods

Apply ban for the entity

$user->ban();

Apply ban for the entity with reason comment

$user->ban([
    'comment' => 'Enjoy your ban!',
]);

Apply ban for the entity which will be deleted over time

$user->ban([
    'expired_at' => '2086-03-28 00:00:00',
]);

expired_at attribute could be \Carbon\Carbon instance or any string which could be parsed by \Carbon\Carbon::parse($string) method:

$user->ban([
    'expired_at' => '+1 month',
]);

Remove ban from entity

$user->unban();

On unban all related ban models are soft deletes.

Check if entity is banned

$user->isBanned();

Check if entity is not banned

$user->isNotBanned();

Delete expired bans manually

app(\Cog\Contracts\Ban\BanService::class)->deleteExpiredBans();

Determine if ban is permanent

$ban = $user->ban();

$ban->isPermanent(); // true

Or pass null value.

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

$ban->isPermanent(); // true

Determine if ban is temporary

$ban = $user->ban([
   'expired_at' => '2086-03-28 00:00:00',
]);

$ban->isTemporary(); // true

Scopes

Get all models which are not banned

$users = User::withoutBanned()->get();

Get banned and not banned models

$users = User::withBanned()->get();

Get only banned models

$users = User::onlyBanned()->get();

Scope auto-apply

To apply query scopes all the time you can define shouldApplyBannedAtScope method in bannable model. If method returns true all banned models will be hidden by default.

use Cog\Contracts\Ban\Bannable as BannableInterface;
use Cog\Laravel\Ban\Traits\Bannable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements BannableInterface
{
    use Bannable;
    
    /**
     * Determine if BannedAtScope should be applied by default.
     *
     * @return bool
     */
    public function shouldApplyBannedAtScope()
    {
        return true;
    }
}

Events

If entity is banned \Cog\Laravel\Ban\Events\ModelWasBanned event is fired.

Is entity is unbanned \Cog\Laravel\Ban\Events\ModelWasUnbanned event is fired.

Middleware

This package has route middleware designed to prevent banned users to go to protected routes.

To use it define new middleware in $routeMiddleware array of app/Http/Kernel.php file:

protected $routeMiddleware = [
    'forbid-banned-user' => \Cog\Laravel\Ban\Http\Middleware\ForbidBannedUser::class,
]

Then use it in any routes and route groups you need to protect:

Route::get('/', [
    'uses' => 'UsersController@profile',
    'middleware' => 'forbid-banned-user',
]);

If you want force logout banned user on protected routes access, use LogsOutBannedUser middleware instead:

protected $routeMiddleware = [
    'logs-out-banned-user' => \Cog\Laravel\Ban\Http\Middleware\LogsOutBannedUser::class,
]

Scheduling

After you have performed the basic installation you can start using the ban:delete-expired command. In most cases you'll want to schedule these command so you don't have to manually run it everytime you need to delete expired bans and unban models.

The command can be scheduled in Laravel's console kernel, just like any other command.

// app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->command('ban:delete-expired')->everyMinute();
}

Of course, the time used in the code above is just example. Adjust it to suit your own preferences.

Integrations

Changelog

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

Upgrading

Please see UPGRADING for detailed upgrade instructions.

Contributing

Please see CONTRIBUTING for details.

Testing

Run the tests with:

vendor/bin/phpunit

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Contributors

@antonkomarev
Anton Komarev
@badrshs
badr aldeen shek salim
@rickmacgillis
Rick Mac Gillis
@AnsellC
AnsellC
@joearcher
Joe Archer
@Im-Fran
Francisco Solis
@jadamec
Jakub Adamec
@ilzrv
Ilia Lazarev
@ZeoKnight
ZeoKnight

Laravel Ban contributors list

Alternatives

License

🌟 Stargazers over time

Stargazers over time

About CyberCog

CyberCog is a Social Unity of enthusiasts. Research the best solutions in product & software development is our passion.

CyberCog

laravel-ban's People

Contributors

ansellc avatar antonkomarev avatar badrshs avatar bobbypiper avatar eberharterm avatar ilzrv avatar im-fran avatar imanghafoori1 avatar jadamec avatar jeffersonsimaogoncalves avatar joearcher avatar laravel-shift avatar leonelngande avatar lex111 avatar rickmacgillis 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-ban's Issues

Laravel 7 compatibility

4.2 is not compatible with Laravel 7 due to illuminate/events 5.5.*|5.6.*|5.7.*|5.8.*|^6.0

@antonkomarev Could you please release a new version with Laravel 7 compatibility?

Thanks a lot!

Is delete ban necessary

Is it necessary to delete ban?
Why not just check if the expired_at time is > than now( ).
If yes, allow user
If no, don't allow user?
I'm thinking of editing your code to behave like this in my project so that I don't need to set cron job. What do you advise ? How can I do this in your code.

$user->isBanned() not working

Hi,
I've installed component like instructions but I have some issue.
Ban seam working if I sue method Ban() but if I put a future expired date, users are always not banned.
Second $user->isBanned() give me always false.
Can you help me?

I've Laravel 5.8
to protect routes I use this code in middleware
Route::group(['middleware' => ['auth','logs-out-banned-user']], function () {......

Thanks

Not working with Laravel 5.5

Trying to add to Laravel 5.5 results in the following composer error:

Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package laravel/framework (locked at v5.4.32, required as 5.5.) is satisfiable by laravel/framework[v5.4.32] but these conflict with your requirements or minimum-stability.
Problem 2
- The requested package phpunit/phpunit (locked at 5.7.21, required as ~6.0) is satisfiable by phpunit/phpunit[5.7.21] but these conflict with your requirements or minimum-stability.
Problem 3
- backpack/base 0.7.21 requires laravel/framework 5.3.
|5.4.* -> satisfiable by laravel/framework[5.3.x-dev, 5.4.x-dev, v5.3.0, v5.3.0-RC1, v5.3.1, v5.3.10, v5.3.11, v5.3.12, v5.3.13, v5.3.14, v5.3.15, v5.3.16, v5.3.17, v5.3.18, v5.3.19, v5.3.2, v5.3.20, v5.3.21, v5.3.22, v5.3.23, v5.3.24, v5.3.25, v5.3.26, v5.3.27, v5.3.28, v5.3.29, v5.3.3, v5.3.30, v5.3.31, v5.3.4, v5.3.5, v5.3.6, v5.3.7, v5.3.8, v5.3.9, v5.4.0, v5.4.1, v5.4.10, v5.4.11, v5.4.12, v5.4.13, v5.4.14, v5.4.15, v5.4.16, v5.4.17, v5.4.18, v5.4.19, v5.4.2, v5.4.20, v5.4.21, v5.4.22, v5.4.23, v5.4.24, v5.4.25, v5.4.26, v5.4.27, v5.4.28, v5.4.29, v5.4.3, v5.4.30, v5.4.31, v5.4.32, v5.4.33, v5.4.34, v5.4.35, v5.4.36, v5.4.4, v5.4.5, v5.4.6, v5.4.7, v5.4.8, v5.4.9] but these conflict with your requirements or minimum-stability.
- backpack/base 0.7.21 requires laravel/framework 5.3.|5.4. -> satisfiable by laravel/framework[5.3.x-dev, 5.4.x-dev, v5.3.0, v5.3.0-RC1, v5.3.1, v5.3.10, v5.3.11, v5.3.12, v5.3.13, v5.3.14, v5.3.15, v5.3.16, v5.3.17, v5.3.18, v5.3.19, v5.3.2, v5.3.20, v5.3.21, v5.3.22, v5.3.23, v5.3.24, v5.3.25, v5.3.26, v5.3.27, v5.3.28, v5.3.29, v5.3.3, v5.3.30, v5.3.31, v5.3.4, v5.3.5, v5.3.6, v5.3.7, v5.3.8, v5.3.9, v5.4.0, v5.4.1, v5.4.10, v5.4.11, v5.4.12, v5.4.13, v5.4.14, v5.4.15, v5.4.16, v5.4.17, v5.4.18, v5.4.19, v5.4.2, v5.4.20, v5.4.21, v5.4.22, v5.4.23, v5.4.24, v5.4.25, v5.4.26, v5.4.27, v5.4.28, v5.4.29, v5.4.3, v5.4.30, v5.4.31, v5.4.32, v5.4.33, v5.4.34, v5.4.35, v5.4.36, v5.4.4, v5.4.5, v5.4.6, v5.4.7, v5.4.8, v5.4.9] but these conflict with your requirements or minimum-stability.
- backpack/base 0.7.21 requires laravel/framework 5.3.|5.4. -> satisfiable by laravel/framework[5.3.x-dev, 5.4.x-dev, v5.3.0, v5.3.0-RC1, v5.3.1, v5.3.10, v5.3.11, v5.3.12, v5.3.13, v5.3.14, v5.3.15, v5.3.16, v5.3.17, v5.3.18, v5.3.19, v5.3.2, v5.3.20, v5.3.21, v5.3.22, v5.3.23, v5.3.24, v5.3.25, v5.3.26, v5.3.27, v5.3.28, v5.3.29, v5.3.3, v5.3.30, v5.3.31, v5.3.4, v5.3.5, v5.3.6, v5.3.7, v5.3.8, v5.3.9, v5.4.0, v5.4.1, v5.4.10, v5.4.11, v5.4.12, v5.4.13, v5.4.14, v5.4.15, v5.4.16, v5.4.17, v5.4.18, v5.4.19, v5.4.2, v5.4.20, v5.4.21, v5.4.22, v5.4.23, v5.4.24, v5.4.25, v5.4.26, v5.4.27, v5.4.28, v5.4.29, v5.4.3, v5.4.30, v5.4.31, v5.4.32, v5.4.33, v5.4.34, v5.4.35, v5.4.36, v5.4.4, v5.4.5, v5.4.6, v5.4.7, v5.4.8, v5.4.9] but these conflict with your requirements or minimum-stability.
- Installation request for backpack/base (locked at 0.7.21, required as ^0.7.16) -> satisfiable by backpack/base[0.7.21].

Laravel API Middleware useage

I have tried to include the middleware provided by the package. I have been back and forth trying to restrict banned users from logging in. Any solution to this or what am I required to do? I simply wanted users who are currently logged in to be logged out

shouldApplyBannedAtScope() causes unban() to be unusable.

I tried to apply the shouldApplyBannedAtScope() method on the User model, and when I called $user->unban() in my unit test, it started complaining about the bans property being called on NULL in BanObserver. That's because the morphTo wasn't able to locate the now-deleted model through the bannable property.

many bans? how?

Hi there!

Just checking out this new package after you told me about it on your Love package.. I'm going to be using both of course :)

I also mentioned I was looking for a tool to handle per-user bans/blocks. To tell you the truth I'm working on a dating site so you can imagine it needs all these functionalities

As soon as I started reading the features of this package, the very first one you mention is "models can have many bans" and immediately in my head I started thinking I could use this not only to handle full-on bans in my application, but I could also use it to handle "reports" in a way.

In the sense that, if one user gets reported for abuse by another user.. then he isn't banned yet, but if 3 users report him, then that converts into a ban

I thought your "many bans" implied that I could set a threshold where the user would only get banned after x number of bans had been applied to it.

Is that not at all what you meant?

It would be nice to write a little more about this mysterious feature that made it to the top of the list =D

Another small thing so I don't create an issue for it.. I'm confused about what you mean in the "Scope auto-apply" section. Do you mean that we have to add the shouldApplyBannedAtScope => true if we want to always apply the withoutBanned() by default on all queries on the bannable model?

Big thanks for putting all this love into these packages of course :) extremely handy and useful!

Package usage questions

Im just trying to see if this package is truly what im looking for. Maybe I can get some insight. With package am I (ADMIN) able to ban users from accessing my site in a way where they can still login but instead of seeing the index they will instead see a custom banned message or something along those lines.

Also if possible am I able to ban users from say there profile page in which I can select a time limit of ban, and comment area to explain why they were banned in which would be displayed like said above.

Lastly is there any sample views controllers on how this can be accomplished with this package?

Inertia compatibility

I'm using the middleware 'forbid-banned-user', which is working as expected but inertiajs has a little problem with redirects, you must specify the redirect response code 303 which is explained here, it would be useful to have like a setting that enables/disables the inertia fix, like:

// ...
'inertia-fix' => false, // default false, you can change it to true.
// ...

and if it's true you will add 303 as redirect response code. I would do it by myself but I'm a bit busy.

allow us to configure the table on different connection / database please

Hello!

As you know me from my heavy usage of your awesome laravel-love library, I like to split my laravel projects into many databases and I'm doing this for one that uses your laravel-ban package.

My bans table is on a different database then my main one. Oddly, methods such as isBanned() do not return any error. To be clear, my bans table is on a different database and the isBanned does correctly return true or false.. so it somehow is capable of interacting with the bans table on a different connection. How this is working right now is a bit puzzling!!

But when I try to actually ->ban() someone I get an error because it's looking for the bans table on the wrong connection.

Would it be possible for you to add a configuration to allow us to set a different connection please?

The same way you did it on laravel-love would be perfect:


'storage' => [
        'database' => [
            'connection' => env('DB_CONNECTION', 'mysql'),

Many many thanks!

How to display Ban Comment

I want to display banned user comment,
ex:Your is ban reason: bla bla...
Are there defined method for this? I cant see it.

bannable trait

Hi

Cog\Laravel\Ban\Services\BanService::ban(): Argument #1 ($bannable) must be of type Cog\Contracts\Ban\Bannable, App\Models\User given, called in /home/project/vendor/cybercog/laravel-ban/src/Traits/HasBannedAtHelpers.php on line 74

I get this error in my project why do I get this error.

something weird when banning models multiple times.

hello
I was trying your package
not sure if I did something wrong but when I Tinkered with a user and I banned him twice (for fun);
the Bans table updated for the number of bans (that's normal, I guess for history); but when I tried to unban him only the last ban got soft deleted on the Bans table, and the Banned_at column on Users table didn't update to Nulled.
so, I was stuck with a Banned User

steps to reproduce :

  • fresh Laravel install with your Package
  • tinker and create a user
  • ban him more than 1 time via $user->ban(); in Tinker always
  • unban Him with $user->unban();
  • he won't be..

Add support for more states

This package is awesome, but it can still be more useful if you allow the user to set other states.

For example:
I want to temporarily give my user access privileges only for a week, so I give him a "VIP" state (instead of "banned" state) for a week.
Hope you got it.

  • Second:
    Why only the user model? support for other models to have temporary "tags" can be added.
    here we are actually tagging a user with the label of "banned" for a period of time.

In an online shop, we can tag a product model, "out_of_stock" or "discount" for a week.

I can do the coding but I do not like to copy and paste someone else 's code as my starter kit. event if MIT
On the other hand, it is a big breaking change to create a PR for it.
So I if you allow it I use your code as an inspiration to create a new package out of it.

ModelWasBanned doesn't fire - here's why.

So, today I ran into a problem that caused me to have to solve the issue with some of Laravel Ban's events not firing. I found out that only in the created method of BanObserver, if you try to save the bannable, then it stops the event from firing. Likewise, if that event fires, then it also stops the method from running to completion.

The only thing I can think of that would do something like that is exit or some kind of exception or error. The problem is that I never use exit in my own code. (I even did a file search on all of my code, and nothing uses that language construct.)

In my dev environment, I have it set to log all of the errors and exceptions to a single file. It doesn't show any. Plus, Laravel uses filp/Whoops (lol) to display exceptions that crash the system. None of that happened.

I've spent hours trying to debug this issue, and I'm at an impasse. Any chance you can have a go at it and make the event start firing for everyone?

how can I ban only once?

Is there a way to ban only if model is not already banned? So that I'd have just 0 or 1 ban record per user.
What method should I overwrite?

Thank you!

Send notification on unban

@antonkomarev Is there any way:

When the user clicks a button, an unban link will be sent to that user's email address.

When the user clicks on the unban link or button it triggers a controller which trigger's this
$user->unban which unbans the user.

Thank you, Unable to pull a request.

Originally posted by @maxillarious in #40 (comment)

Refactor namespaces

We need to refactor all namespaces and implement new package architecture similar to Laravel Love v6

Jailer - possible name for model who bans bannable model.
Jailee - banned model.

best way to define a default route for banned users?

I got your package implemented and working now but I see that when a banned user tries to access a page that requires auth they are just bounced back to the landing page as if they were not authorized

I am not using your forbid-banned-user route middleware because I actually need to allow users to log in so I can show them a customized page telling them they are suspended where I can also retrieve the "comment" added when the ban was done

When users log in I catch that they are banned and send them to this page. But if they then try to navigate to an authorized page then it creates a problem.

I guess I can create a "isBanned" middleware and handle all this. But I thought this should be part of this package.. with a configuration file where one can set the default route to send all users that are both authenticated and banned

Or maybe I'm missing something and this is already baked in ?

Ban ip?

Hello all, but I can ban user ip?

Ban expiration event

Hello,
Because I work with spatie/laravel-permission, I'd like to add a rank to a banned user. This works.
But if the ban expires, I would like a query to be executed to remove the rank.
Is this possible?

Showing expired_at in blade view

Hello,

How do i show the expired_at in my view. I followed this tutorial: http://itsolutionstuff.com/post/how-to-create-ban-revoke-user-functionality-in-laravel-5-example-example.html

Atm i have this in my view, but the {{$user->expired_at}} doesn't work.. any ideas

@extends('layouts.app')

@section('content')

    <section class="contact-2">
        <div class="container">
            <div class="row contact-details">
                <div class="m-auto">
                    <h2 id="center_h2">Gebruikers</h2>
                    <div class="divider"></div>
                    @if(Session::has('success'))
                        <div class="alert alert-success">
                            {{ Session::get('success') }}
                            @php
                                Session::forget('success');
                            @endphp
                        </div>
                    @endif
                    @if (count($users) > 0)
                        <table class="table">
                            <thead>
                            <tr>
                                <th>#</th>
                                <th>Naam</th>
                                <th>Email</th>
                                <th>Voornaam</th>
                                <th>Achternaam</th>
                                <th>Geboortedatum</th>
                                <th>Verbannen tot</th>
                                <th>Ban?</th>
                                <th>Rol_id</th>
                            </tr>
                            </thead>
                            <tbody>
                            @foreach($users as $key => $user)
                                <tr>
                                    <td><a href="{{route('editUser',$user->id)}}">{{$user->id}}</a></td>
                                    <td>{{$user->username}}</td>
                                    <td>{{$user->email}}</td>
                                    <td>{{$user->first_name}}</td>
                                    <td>{{$user->last_name}}</td>
                                    <td>{{$user->date_of_birth}}</td>
                                    <td>
                                        {{--@if($user->isBanned())--}}
                                            {{--verbanen tot--}}
                                            {{--{{$user->expired_at}}--}}
                                        {{--@else--}}
                                            {{--Niet --}}
                                        {{--@endif--}}
                                    </td>
                                    <td>
                                        @if($user->isBanned())
                                            <a href="{{ route('revokeUser',$user->id) }}"
                                               class="btn btn-success btn-sm"> Revoke</a>
                                        @else
                                            <a class="btn btn-success ban btn-sm" data-id="{{ $user->id }}"
                                               data-action="{{ URL::route('banUser') }}"> Ban</a>
                                        @endif
                                    </td>
                                    <td>{{$user->role_id}}</td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    @endif
                </div>

            </div>
        </div>
    </section>

@endsection

I hope u can help me.

Greetings,

Dosen´t refresh the collection when I ban a user

Hi everyone! Excelent work with the package!!!

I have found in one of my tests that the variable that contained the user model instance was not updated after applying the ban() function to it.

Example:
$user = User::find($id);
$user->ban();
if i look into the $user dosen´t have updated the field banned_at.

I think this should not be the case and should be updated.
Hope this helps!

Thanks!!!

support to ban by visiter not users

Hi, Does this package support ban visiter ??? no user here , I want to ban the visiter based on his ip address.
So I will have additional table related to the ip address im going to block

thank you for helping :)

ban:delete-expired problem

When I run ban: delete-expired, I get this error:

In BanObserver.php line 65: Call to a member function count() on null

Full error text:

[2019-06-16 05:30:01] local.ERROR: Call to a member function count() on null {"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Call to a member function count() on null at /vendor/cybercog/laravel-ban/src/Observers/BanObserver.php:65)
[stacktrace]
$0 [internal function]: Cog\Laravel\Ban\Observers\BanObserver->deleted(Object(Cog\Laravel\Ban\Models\Ban))
$1 /vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(369): call_user_func_array(Array, Array)
$2 /vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(200): Illuminate\Events\Dispatcher->Illuminate\Events\{closure}('eloquent.delete...', Array)
$3 /vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(173): Illuminate\Events\Dispatcher->dispatch('eloquent.delete...', Array, false)
$4 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php(148): Illuminate\Events\Dispatcher->fire('eloquent.delete...', Object(Cog\Laravel\Ban\Models\Ban))
$5 /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(790): Illuminate\Database\Eloquent\Model->fireModelEvent('deleted', false)
$6 /vendor/cybercog/laravel-ban/src/Services/BanService.php(61): Illuminate\Database\Eloquent\Model->delete()
$7 /vendor/laravel/framework/src/Illuminate/Support/Collection.php(339): Cog\Laravel\Ban\Services\BanService->Cog\Laravel\Ban\Services\{closure}(Object(Cog\Laravel\Ban\Models\Ban), 3)
$8 /vendor/cybercog/laravel-ban/src/Services/BanService.php(62): Illuminate\Support\Collection->each(Object(Closure))
$9 /vendor/cybercog/laravel-ban/src/Console/Commands/DeleteExpiredBans.php(54): Cog\Laravel\Ban\Services\BanService->deleteExpiredBans()
$10 [internal function]: Cog\Laravel\Ban\Console\Commands\DeleteExpiredBans->handle()
$11 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
$12 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
$13 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
$14 /vendor/laravel/framework/src/Illuminate/Container/Container.php(549): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
$15 /vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
$16 /vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArrayInput), Object(Illuminate\Console\OutputStyle))
$17 /vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArrayInput), Object(Illuminate\Console\OutputStyle))
$18 /vendor/symfony/console/Application.php(960): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArrayInput), Object(Symfony\Component\Console\Output\BufferedOutput))
$19 /vendor/symfony/console/Application.php(255): Symfony\Component\Console\Application->doRunCommand(Object(Cog\Laravel\Ban\Console\Commands\DeleteExpiredBans), Object(Symfony\Component\Console\Input\ArrayInput), Object(Symfony\Component\Console\Output\BufferedOutput))
$20 /vendor/symfony/console/Application.php(148): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArrayInput), Object(Symfony\Component\Console\Output\BufferedOutput))
$21 /vendor/laravel/framework/src/Illuminate/Console/Application.php(88): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArrayInput), Object(Symfony\Component\Console\Output\BufferedOutput))
$22 /vendor/laravel/framework/src/Illuminate/Console/Application.php(177): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArrayInput), Object(Symfony\Component\Console\Output\BufferedOutput))
$23 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(249): Illuminate\Console\Application->call('ban:delete-expi...', Object(Illuminate\Support\Collection), NULL)
$24 /vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php(221): Illuminate\Foundation\Console\Kernel->call('ban:delete-expi...')
$25 /app/Console/Kernel.php(35): Illuminate\Support\Facades\Facade::__callStatic('call', Array)
$26 [internal function]: App\Console\Kernel->App\Console\{closure}()
$27 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Object(Closure), Array)
$28 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(75): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
$29 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Object(Closure), Object(Closure))
$30 /vendor/laravel/framework/src/Illuminate/Container/Container.php(549): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Object(Closure), Array, NULL)
$31 /vendor/laravel/framework/src/Illuminate/Console/Scheduling/CallbackEvent.php(74): Illuminate\Container\Container->call(Object(Closure), Array)
$32 /vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php(59): Illuminate\Console\Scheduling\CallbackEvent->run(Object(Illuminate\Foundation\Application))
$33 [internal function]: Illuminate\Console\Scheduling\ScheduleRunCommand->handle()
$34 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
$35 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
$36 /vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
$37 /vendor/laravel/framework/src/Illuminate/Container/Container.php(549): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
$38 /vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\Container\Container->call(Array)
$39 /vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
$40 /vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
$41 /vendor/symfony/console/Application.php(960): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
$42 /vendor/symfony/console/Application.php(255): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Console\Scheduling\ScheduleRunCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
$43 /vendor/symfony/console/Application.php(148): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
$44 /vendor/laravel/framework/src/Illuminate/Console/Application.php(88): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
$45 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(121): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
$46 /artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
$47 {main}
"}

Events don't fire in phpunit. How do I make them fire?

So, I've been struck trying to figure out why the events don't fire for Laravel Ban in PHPUnit, but they function just fine when running the code in the browser.

Is there something special that I need to do to test for events in packages and make them fire?

Just an FYI, I ran the Laravel Ban tests and those pass without issue. The code I wrote for my project works just the same as in those tests and in the docs. (Albeit going through application specific code) So, it functions just fine when the browser-based version runs over the LOC that the tests are running.

I've tested to see if PHPUnit runs the service provider to observe the Ban model in the first place, and it runs that code. I've even manually added the code to observe the model, directly into the test as the first line of code, and that doesn't work. I've also removed all mocking from the tests to allow every event to fire, but the observer doesn't fire, and so the code that checks if a model got banned by the observer setting it in the DB properly, fails the check. It just doesn't fire.

Something is vehemently trying to make it NOT fire, and I need to know why. I have a hunch that it has to do with the way the code is bootstrapped.

Here are my tests:

/**
	 * @group current
	 */
	public function testCanSuspendUser()
	{
		$this->expectsEvents(ModelWasBanned::class);
		
		$user = factory(User::class)->create();
		$this->assertFalse($user->isBanned());
		
		$user->ban([
			'comment'		=> 'blah',
			'expired_at'	=> null,
		]);
		
		$this->assertTrue($user->isBanned());
	}
	
	/**
	 * @group current
	 */
	public function testCanUnsuspendUser()
	{
		$this->expectsEvents(ModelWasUnbanned::class);
		
		$user = factory(User::class)->create();
		$user->ban();
		
		$user->unban();
		
		$this->assertFalse($user->isBanned());
	}

Getting a way to know who banned

Hello there, I see that the table "bans" store the ban user ID and type of "banner" (if user or else) which led me to think there was a simple way to get the user id of the administrator or entity who banned the user, but sadly, there is none ... is it planned ?

Or shall we make a PR ?

Thank you for this great repo,
Epistol

Mass Bans?

What's the most efficient way to handle mass bans?

Right now looping through all bannable models and then applying the ban is making 3 queries each (So if I was to ban say 1k users, that's 3k queries and isn't good TBH). So if I was to do mass ban, then it's not really efficient.

So I wanna know if there's a better way to achieve this?

Support for user UUIDs

I'd like to see this working for user UUIDs out of the box. For now, I help myself with 2 subsequent migrations which alter the columns bannable_id and created_by_id to string(36). This works so far but I am not sure about any side effects. It would be great if there would be a config option for this.

Laravel 8 unsupport and bug

Details

  • Laravel version: 8.1.0
  • cyborg version 4.2.x
  • mysql version:
    Production: Ver 15.1 Distrib 10.3.23-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
    Local (dev): Ver 15.1 Distrib 10.4.14-MariaDB, for Linux (x86_64) using EditLine wrapper

Description

Hello i have don't heck if your package is ready for laravel 8 so is my fault if is this case.

My problem is if i run this command: ban:delete-expired every day at 7:00 in UTC timezone i will got these bug:

  • Some of my model of Advertise.php,Category.php,'Topic.php,ProductCategory.php` will be deleted, and if one user or multiples users is banned, in the next schedule your command will ban every users, i have softDelete so i can recover everythings for that is really good 😄

Step to reproduce:

  • install of cyborg in laravel version 7.25.x : all work like schedule, ban, ...
  • upgrade laravel version 8.1.0 from 7.25.x because laravel telescope have bug in version 7.25.x by following docs
  • install of composer require laravel/legacy-factory support legacy models and factories
  • adding command for check and unban users from your package in app\Console\Kernel.php.
  • wait schedule.
  • some models will be deleted

Answer

Did your package support laravel 8 ?
Your package can access to relation from any models ? ( that really not good because some model can be delete with onDeleteCascade() )

$user->isNotBanned not working in a blade file

I did everything just as the instruction, everything seems to be working fine.

But, there is an issue,

When i use @if($post->user->isNotBanned() == true) in blade file,
i get this error: Call to a member function isNotBanned() on null

EDIT
i have this in my blade file:

@if($posts->count() != 0)

    @foreach($posts as $post)
     
     <!-- If this post's user is not banned display his post -->
    @if($post->user->isNotBanned() == true)
     Show Bookmarked post
    @endif

    @endforeach

@endif

Thank you

Middlewares

I just wanted to mention that the middlewares need some improvements.
And please if you could add some new features such as blocking IP addresses and so on.

Where does `banned_at` get set?

I've looked around and I cannot seem to find where banned_at ever gets set or unset. Expired bans do not set it to null (as it's simply a deletion on the ban record) and creation of bans don't seem to set it either.

I'm a little confused. Am I missing something?

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.