PHP code example of enlivenapp / flight-shield

1. Go to this page and download the library: Download enlivenapp/flight-shield 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/ */

    

enlivenapp / flight-shield example snippets


// app/config/shield.php
return [
    'routePrepend' => 'auth',
    // ... your overrides here
];

use Enlivenapp\FlightShield\Middlewares\SessionAuthMiddleware;

Flight::route('/dashboard', function () {
    $user = auth()->user();
    echo 'Hello, ' . $user->username;
})->addMiddleware(new SessionAuthMiddleware(Flight::app()));

$result = auth()->attempt(['email' => '[email protected]', 'password' => 'secret']);

if ($result->isOK()) {
    Flight::redirect('/dashboard');
} else {
    echo $result->reason();
}

$user = auth()->user();

if ($user->can('users.edit')) {
    // allowed
}

if ($user->inGroup('admin', 'superadmin')) {
    // allowed
}

$user->can(*) = true

$id = user_id(); // returns int|string|null

$auth = Flight::auth();

// Superadmin visibility: superadmins see everyone,
// Superadmins are hidden from every other user group.
$isSuper = $auth->user()?->inGroup('superadmin') ?? false;

$result = $auth->users()->create($username, $email, $password, 'editor');
if ($result->isOK()) {
    $user = $result->extraInfo();
} else {
    echo $result->reason();
}

$auth->users()->paginated($page, 20, $isSuper);
$auth->users()->updateProfile($user, ['email' => $newEmail, 'password' => $newPassword]);
$auth->groups()->syncPermissions('editor', ['posts.create', 'posts.edit']);
$auth->permissions()->create('posts.create', 'Create blog posts');

'session' => [
    'field'                => 'user',         // Session key
    'allow_remembering'    => true,
    'remember_cookie_name' => 'remember',
    'remember_length'      => 30 * 86400,     // 30 days
],

'authenticators' => [
    'session' => \Enlivenapp\FlightShield\Authentication\Authenticators\Session::class,
    'tokens'  => \Enlivenapp\FlightShield\Authentication\Authenticators\AccessTokens::class,
    'hmac'    => \Enlivenapp\FlightShield\Authentication\Authenticators\HmacSha256::class,
    'jwt'     => \Enlivenapp\FlightShield\Authentication\Authenticators\JWT::class,
],

'jwt' => [
    'header'         => 'Authorization',
    'time_to_live'   => 3600,
    'default_claims' => ['iss' => 'https://example.com'],
    'keys' => [
        'default' => [
            ['kid' => '', 'alg' => 'HS256', 'secret' => 'your-256-bit-secret'],
        ],
    ],
],

$jwt = auth('jwt')->getAuthenticator()->generateToken($user);

use Enlivenapp\FlightShield\Middlewares\ChainAuthMiddleware;

Flight::route('/api/resource', function () {
    // accessible by session, Bearer token, or HMAC
})->addMiddleware(new ChainAuthMiddleware(Flight::app()));

$user = auth()->user();

// Check group membership
$user->inGroup('admin');               // true if in 'admin'
$user->inGroup('admin', 'superadmin'); // true if in either

// Check permission
$user->can('users.edit');

// Modify via the Authorizable trait (no ORM handle needed)
$user->addGroup('editor');
$user->removeGroup('editor');
$user->addPermission('posts.create');
$user->addPermission('posts.create', true); // explicit deny
$user->removePermission('posts.create');

// Or use the management services directly
auth()->groups()->syncPermissions('editor', ['posts.create', 'posts.edit']);
auth()->permissions()->create('posts.create', 'Create blog posts');

'passwords' => [
    'algorithm'      => PASSWORD_DEFAULT, // PASSWORD_BCRYPT or PASSWORD_ARGON2ID
    'cost'           => 12,
    'memory_cost'    => 65536,   // Argon2 only
    'time_cost'      => 4,       // Argon2 only
    'threads'        => 1,       // Argon2 only
    'min_length'     => 8,
    'max_similarity' => 50,
    'validators'     => [
        \Enlivenapp\FlightShield\Passwords\CompositionValidator::class,
        \Enlivenapp\FlightShield\Passwords\NothingPersonalValidator::class,
        \Enlivenapp\FlightShield\Passwords\DictionaryValidator::class,
        // \Enlivenapp\FlightShield\Passwords\PwnedValidator::class,
    ],
],

use Enlivenapp\FlightShield\Middlewares\SessionAuthMiddleware;

Flight::route('/dashboard', function () { ... })
    ->addMiddleware(new SessionAuthMiddleware(Flight::app()));

use Enlivenapp\FlightShield\Middlewares\TokenAuthMiddleware;

Flight::route('/api/data', function () { ... })
    ->addMiddleware(new TokenAuthMiddleware(Flight::app()));

use Enlivenapp\FlightShield\Middlewares\HmacAuthMiddleware;

Flight::route('POST /api/webhook', function () { ... })
    ->addMiddleware(new HmacAuthMiddleware(Flight::app()));

use Enlivenapp\FlightShield\Middlewares\JWTAuthMiddleware;

Flight::route('/api/secure', function () { ... })
    ->addMiddleware(new JWTAuthMiddleware(Flight::app()));

use Enlivenapp\FlightShield\Middlewares\ChainAuthMiddleware;

Flight::route('/mixed', function () { ... })
    ->addMiddleware(new ChainAuthMiddleware(Flight::app()));

use Enlivenapp\FlightShield\Middlewares\GroupMiddleware;

Flight::group('/admin', function () { ... }, [
    new GroupMiddleware(Flight::app(), 'admin', 'superadmin'),
]);

use Enlivenapp\FlightShield\Middlewares\PermissionMiddleware;

Flight::route('/posts/create', function () { ... })
    ->addMiddleware(new PermissionMiddleware(Flight::app(), 'posts.create'));

use Enlivenapp\FlightShield\Middlewares\ForcePasswordResetMiddleware;

Flight::route('/account', function () { ... })
    ->addMiddleware(new ForcePasswordResetMiddleware(Flight::app()));

use Enlivenapp\FlightShield\Middlewares\RateLimitMiddleware;

Flight::route('POST /custom-auth', function () { ... })
    ->addMiddleware(new RateLimitMiddleware(Flight::app()));

// app/config/shield.php - return the keys you want to override
return [
    'routePrepend' => 'auth',
    'default_authenticator' => 'session',
    // ... any other overrides
];

'session' => [
    'field'                => 'user',
    'allow_remembering'    => true,
    'remember_cookie_name' => 'remember',
    'remember_length'      => 30 * 86400, // 30 days
],

'passwords' => [
    'algorithm'      => PASSWORD_DEFAULT,
    'cost'           => 12,
    'memory_cost'    => 65536,
    'time_cost'      => 4,
    'threads'        => 1,
    'min_length'     => 8,
    'max_similarity' => 50,
    'validators'     => [
        \Enlivenapp\FlightShield\Passwords\CompositionValidator::class,
        \Enlivenapp\FlightShield\Passwords\NothingPersonalValidator::class,
        \Enlivenapp\FlightShield\Passwords\DictionaryValidator::class,
    ],
],

'hmac' => [
    'encryption_keys'        => [],         // populated by shield:hmac init/addkey
    'encryption_current_key' => '',         // alias of the active key
    'encryption_cipher'      => 'aes-256-gcm',
    'secret2_storage_limit'  => 255,
],

'jwt' => [
    'header'         => 'Authorization',
    'time_to_live'   => 3600,
    'default_claims' => ['iss' => ''],
    'keys' => [
        'default' => [
            ['kid' => '', 'alg' => 'HS256', 'secret' => ''],
        ],
    ],
],

'rate_limiting' => [
    'enabled'         => true,
    'max_attempts'    => 10,
    'decay_minutes'   => 30,
    'lockout_minutes' => 30,
],

'redirects' => [
    'login'             => '/auth/login',
    'logout'            => '/',
    'after_login'       => '/',
    'after_login_admin' => '/admin',
    'after_register'    => '/',
    'after_logout'      => '/auth/login',
    'force_reset'       => '/auth/reset-password',
    'permission_denied' => '/auth/login',
    'group_denied'      => '/auth/login',
],

'email_sender' => function (string $to, string $subject, string $body): void {
    mail($to, $subject, $body);
},
bash
php runway migrate:all
bash
php runway shield
bash
php runway shield:permission list
php runway shield:permission create -a posts.create -d "Create posts"
php runway shield:permission update -a posts.create -d "Create blog posts"
php runway shield:permission delete -a posts.create

app/Views/enlivenapp/flight-shield/login.php