PHP code example of drewlabs / laravel-http-guard

1. Go to this page and download the library: Download drewlabs/laravel-http-guard 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/ */

    

drewlabs / laravel-http-guard example snippets


// app/bootrap.php

// ...

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not 

return [
    // Default values in the auth configuration file
    // ...

    'guards' => [
        // You add other guard drivers
        // ... 
        // Configuration of the http guard driver
        'http' => [
            'driver' => 'http'
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */
    // Here in the providers key of the array, we define the basic configuration that will be loaded by the library service provider at runtime as follow:
    'providers' => [
        // ...
        'http' => [
            // Model class to be used by the package providers
            'model' => \Drewlabs\HttpGuard\User::class,
            // For Http request we must define the endpoint where is located the
            // authorization server(s)
            'hosts' => [
                // When not using a cluster of servers, this default host is used
                'default' => 'http://localhost:4300',

                // Cluster of servers to be used for authentication
                'cluster' => [
                    [
                        'host' => '<HOST_URL>',
                        'primary' => true, // Boolean value indicating whether the host should be query first as primary node
                    ]
                ]
            ]
        ]
    ],
  
    // ...

];


// auth.php

// ...
return [
    // ..
    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as 

// app/Http/Middleware.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Factory as Auth;

class Authenticate
{


    /**
     * @var Factory
     */
    protected $auth;

    /**
     * Create a new BaseMiddleware instance.
     *
     * @param Auth $auth
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }


    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $this->authenticate($guards);
        return $next($request);
    }

    /**
     * Determine if the user is ged in to any of the given guards.
     *
     * @param  array  $guards
     * @return void
     *
     * @throws AuthenticationException
     */
    protected function authenticate(array $guards)
    {
        if (empty($guards)) {
            $guards = [null];
        }
        // To authenticate users, loop through all the guards provided as parameter
        // to the middleware and check if users are authenticated
        foreach ($guards as $guard) {
            if ($this->auth->guard($guard)->check()) {
                return $this->auth->shouldUse($guard);
            }
        }
        $this->unauthenticated($guards);
    }

    /**
     * Handle an unauthenticated user.
     *
     * @param  array  $guards
     * @return void
     *
     * @throws AuthenticationException
     */
    protected function unauthenticated(array $guards)
    {
        throw new AuthenticationException('Unauthenticated.', $guards);
    }
}

// app/Http/Kernel.php

class Kernel extends HttpKernel {

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        // ...
        'auth' => \App\Http\Middleware\Authenticate::class,
    ];

    // ...
}

// app/bootstrap.php

// ...

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
 */

$app = $app->routeMiddleware([
        // ...
        'auth' => \App\Http\Middleware\Authenticate::class,
]);


// app/Providers/AuthServiceProvider.php

class AuthServiceProvider extends ServiceProvider
{
    // ...

    /**
     * Boot the authentication services for the application.
     *
     * @return void
     */
    public function boot()
    {
        // Configure the Http-Guard library to use cache
        \Drewlabs\HttpGuard\HttpGuardGlobals::usesCache(true);
        // Configure the http-guard library to use PHP 'memcached' storage as default driver
        \Drewlabs\HttpGuard\HttpGuardGlobals::useCacheDriver('memcached');
        // ...
    }
}

    // Configure the Http-Guard library to use cache
    \Drewlabs\HttpGuard\HttpGuardGlobals::usesCache(true);
    // Configure the http-guard library to use redis storage as default driver
    \Drewlabs\HttpGuard\HttpGuardGlobals::useCacheDriver('redis');

    // Define the redis connection configuration as defined in predis documentation
    \Drewlabs\HttpGuard\HttpGuardGlobals::forRedis([
            'scheme' => 'tcp',
            'host'   => '10.0.0.1',
            'port'   => 6379,
    ]);
    // ...

// app/AuthServiceProvider.php

use Drewlabs\HttpGuard\HttpGuardGlobals;

class AuthServiceProvider extends ServiceProvider
{
    // ...
    public function boot()
    {
        // ...
        HttpGuardGlobals::userPath('auth/v2/user'); // Set the api prefix to equal auth instead of api
        HttpGuardGlobals::revokePath('auth/v2/logout');
    }
}

// app/AuthServiceProvider.php

use Drewlabs\HttpGuard\HttpGuardGlobals;

class AuthServiceProvider extends ServiceProvider
{
    // ...
    public function boot()
    {
        // ...
        HttpGuardGlobals::guard('api'); // Defines the guard name to be used by the library as `api`
    }
}


// app/AuthServiceProvider.php

use Drewlabs\HttpGuard\Contracts\UserFactory;

class AuthServiceProvider extends ServiceProvider
{
    // ...
    public function register()
    {
        // ...
        // Defining the user factory
        $this->app->bind(UserFactory::class, function() {
            return function(array $attributes = [], ?string $token = null) {
                // Creates the instance of Authenticatable class
                return $user;
            };
        });
    }
}

return [
    // Default values in the auth configuration file
    // ...

    'guards' => [
        // You add other guard drivers
        // ... 
        // Configuration of the http guard driver
        'http' => [
            'driver' => 'http'
        ],
    ],
    // ....
    'providers' => [
        // ...
        'http' => [
            // ...
            // Using a class : Uncomment the code below to use the class
            // 'userFactory' => \App\UserFactory::class,
            // Using a closure
            'userFactory' => function(array $attributes = [], ?string $token = null) {
              
            }
        ]
    ],
];