PHP code example of masq / guardian

1. Go to this page and download the library: Download masq/guardian library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

masq / guardian example snippets


use Guardian\Concerns\Guardable;

class User extends Authenticatable
{
    use Guardable;

    // Optional hooks Guardian calls when a state is entered:
    public function guardianRestrict(\Guardian\Enums\TrustState $state, array $ctx = []): void
    {
        // soft restriction — e.g. freeze rewards
    }

    public function guardianBan(array $ctx = []): void
    {
        $this->tokens()->delete(); // your definition of "banned"
    }
}

use Guardian\ValueObjects\Signal;

// 1. Record an observation (points fade with the default decay)
$user->raiseSuspicion(Signal::soft('login_velocity', 15, ['ip' => $ip]));

// 2. Read where the subject stands (served from cache, not the DB)
$user->trustState();      // TrustState enum: Trusted / Watch / Restricted / Review / Banned
$user->suspicionScore();  // int — current, decayed score
$user->isBanned();
$user->isFlagged();       // worse than Trusted
$user->needsReview();     // has an open moderator case

// 3. Protect a route
Route::post('/play', ...)->middleware('guardian:banned');

Signal::soft('login_velocity', 15, $evidence);   // heuristic — only accumulates
Signal::hard('rate_limit', 40, $evidence);       // serious; big, slow-fading points
Signal::fatal('clock_skew', $evidence);          // impossible -> bans immediately

// routes/console.php
use Illuminate\Support\Facades\Schedule;
use Guardian\Jobs\ReevaluateTrust;

Schedule::job(new ReevaluateTrust)->daily();

'thresholds' => [
    0   => TrustState::Trusted,
    20  => TrustState::Watch,
    50  => TrustState::Restricted,
    80  => TrustState::Review,     // opens a moderator case
    120 => TrustState::Banned,
],

use Guardian\Contracts\TrustStateContract;

enum TrustState: string implements TrustStateContract
{
    case Trusted = 'trusted';
    case Watch = 'watch';
    case Probation = 'probation';   // your extra rung
    case Review = 'review';
    case Banned = 'banned';

    public function key(): string { return $this->value; }
    public function level(): int  { /* order: lower = more trusted */ }

    public static function base(): self     { return self::Trusted; } // baseline
    public static function terminal(): self { return self::Banned; }  // ban target
    public static function fromKey(string $k): self  { return self::from($k); }
    public static function tryFromKey(?string $k): ?self { return $k === null ? null : self::tryFrom($k); }
    public static function all(): array { return self::cases(); }
}

// config/guardian.php
'state_enum' => App\Trust\TrustState::class,

use Guardian\Detectors\AbstractDetector;
use Guardian\ValueObjects\Signal;

final class RateLimitDetector extends AbstractDetector
{
    public function inspect(object $subject, array $context = []): ?Signal
    {
        $hits = $context['hits'] ?? 0;

        return $hits > $this->option('limit', 100)
            ? Signal::hard($this->key(), 60, ['hits' => $hits])
            : null;          // null = nothing to report
    }
}

'detectors' => [
    'rate_limit' => [
        'class'   => App\Guardian\Detectors\RateLimitDetector::class,
        'enabled' => true,
        'limit'   => 100,
    ],
],

Guardian::inspect($user, ['hits' => $hits]);            // every enabled detector
Guardian::run('rate_limit', $user, ['hits' => $hits]);  // one by key
Guardian::register($adHocDetector);                      // runtime only

// list form — enum case, no ->value
'actions' => [
    ['state' => TrustState::Restricted, 'actions' => [FreezeAction::class]],
    ['state' => TrustState::Review,     'actions' => [QueueForReviewAction::class]],
    ['state' => TrustState::Banned,     'actions' => [QueueForReviewAction::class, BanAction::class]],
],

// keyed map — string keys also work ('restricted' value or 'Restricted' name)
'actions' => [
    'restricted' => [FreezeAction::class],
    'review'     => [QueueForReviewAction::class],
],

Guardian::track('behavior')->run('chat_filter', $user, ['message' => $text]);
Guardian::track('behavior')->ban($user, 'harassment');

$user->isBanned('behavior');   // independent of the default (anti-cheat) track
$user->isBanned();             // default track

Guardian::recordThrottleHit($user, 'login');

'throttle_hits' => [
    'class'                => Guardian\Detectors\ThrottleHitDetector::class,
    'enabled'              => true,
    'allowed_hits'         => 5,    // free hits inside the window
    'window_seconds'       => 900,  // counter window (used to size the cache TTL)
    'base_points'          => 12,   // points once the allowance is exceeded
    'points_per_extra_hit' => 6,    // + per hit beyond the allowance
    'max_points'           => 100,  // cap for one signal
    'decay'                => 'half_life',
],

Route::post('/play', ...)->middleware('guardian:banned');           // default track
Route::post('/chat', ...)->middleware('guardian:banned,behavior');  // behavior track
Route::get('/forum', ...)->middleware('guardian:review,behavior');  // review and worse

Guardian::ban($user, 'cheating confirmed'); // confirm -> permanent ban
Guardian::ban($user, BanReason::Cheating);  // reason accepts an enum too
Guardian::clear($user);                      // false positive -> forgive + unban

class AlertModerators
{
    public function handle(\Guardian\Events\SentToReview $event): void
    {
        // $event->subject, $event->review->evidence
    }
}

return [
    'default_track' => 'default',

    // Independent tracks. Each is self-contained; an undefined track name
    // inherits the default track's rules.
    'tracks' => [
        'default' => [
            'thresholds'      => [/* score => TrustState */],
            'soft_max_state'  => TrustState::Review,   // null = no clamp
            'actions'         => [/* TrustState->value => [Action::class] */],
            'throttle_detector' => 'throttle_hits',    // key recordThrottleHit() drives
            'detectors'       => [/* key => ['class' => ..., 'enabled' => true, ...options] */],
        ],
        // 'behavior' => [ ...own thresholds + detectors... ],
    ],

    // Shared by all tracks:
    'decay' => [
        'default'    => 'half_life',
        'strategies' => [
            'none'      => ['class' => NoDecay::class],
            'linear'    => ['class' => LinearDecay::class, 'days' => 30],
            'half_life' => ['class' => HalfLifeDecay::class, 'days' => 14],
        ],
    ],
    'cache'            => ['store' => env('GUARDIAN_CACHE_STORE'), 'ttl' => 86400, 'prefix' => 'guardian'],
    'ban_method'       => 'guardianBan',  // subject method BanAction calls
    'tables'           => ['events' => 'suspicion_events', 'profiles' => 'trust_profiles', 'reviews' => 'moderator_reviews'],
    'prune_after_days' => 180,            // null = keep the full audit log
];

$user->ban('cheating confirmed');   // permanent ban (this track)
$user->unban();                     // lift ban / forgive
$user->ban('harassment', track: 'behavior');
bash
composer vendor:publish --tag=guardian-config   # optional: gives you config/guardian.php
php artisan migrate                                 # migrations auto-load