PHP code example of mpyw / scoped-auth

1. Go to this page and download the library: Download mpyw/scoped-auth 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/ */

    

mpyw / scoped-auth example snippets




namespace App\Auth;

use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Contracts\Auth\UserProvider;
use Laravel\Fortify\Fortify;

class CustomFortifyAuthenticator
{
    private const PASSWORD_NAME = 'password';

    private readonly UserProvider $provider;

    public function __construct(StatefulGuard $guard)
    {
        // Assert `StatefulGuard` has `getProvider()` which is not declared in the contract
        assert(method_exists($guard, 'getProvider'));
        $provider = $guard->getProvider();

        assert($provider instanceof UserProvider);
        $this->provider = $provider;
    }

    public function __invoke(Request $request): ?Authenticatable
    {
        $user = $this->provider->retrieveByCredentials([
            Fortify::username() => $request->input(Fortify::username()),
        ]);

        return $user && $this->provider->validateCredentials($user, [
            self::PASSWORD_NAME => $request->input(self::PASSWORD_NAME),
        ]) ? $user : null;
    }
}



namespace App\Providers;

use App\Auth\CustomFortifyAuthenticator;
use Illuminate\Support\ServiceProvider;
use Laravel\Fortify\Fortify;

class AuthServiceProvider extends ServiceProvider
{
    public function boot(CustomFortifyAuthenticator $authenticator): void
    {
        Fortify::authenticateUsing($authenticator);
    }
}



namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Mpyw\ScopedAuth\AuthScopable;

class User extends Model implements UserContract, AuthScopable
{
    use Authenticatable;

    public function scopeForAuthentication(Builder $query): Builder
    {
        return $query->where('active', 1);
    }
}



use Illuminate\Support\Facades\Auth;

$user = Auth::user(); // Only 

public function scopeActive(Builder $query): Builder
{
    return $query->where('active', 1);
}

public function scopeForAuthentication(Builder $query): Builder
{
    return $this->scopeActive($query);
}

$user = User::where('email', '[email protected]')->forAuthentication()->firstOrFail();

$user = User::where('email', '[email protected]')->scopes(['forAuthentication'])->firstOrFail();