PHP code example of authava / laravel

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

    

authava / laravel example snippets


use Authava\Laravel\Middleware\AuthavaAuthenticate;

Route::middleware([AuthavaAuthenticate::class])->group(function () {
    Route::get('/protected', function (Request $request) {
        // Access the authenticated user
        $user = $request->get('authava_user');
        return response()->json(['user' => $user]);
    });
});

use Authava\Laravel\Middleware\AuthavaAuthenticate;
use Authava\Laravel\Middleware\EnsureUserExists;

Route::middleware([
    AuthavaAuthenticate::class,
    EnsureUserExists::class,
])->group(function () {
    Route::get('/profile', function (Request $request) {
        // Access your local user model
        $user = $request->get('user');
        return response()->json(['user' => $user]);
    });
});

use Authava\Laravel\Facades\Authava;

// Get the current session
$session = Authava::getSession($request->header('Cookie'));

// Clear session cache
Authava::clearSessionCache($cookie);

// Get configuration
$config = Authava::getConfig();

use Authava\Laravel\AuthavaClient;

class UserController extends Controller
{
    public function __construct(private AuthavaClient $authava)
    {
    }

    public function profile(Request $request)
    {
        $session = $this->authava->getSession($request->header('Cookie'));
        // ...
    }
}

Route::middleware([
    AuthavaAuthenticate::class,
    EnsureUserExists::class,
])->group(function () {
    // Routes here will have access to synchronized users
});

use App\Models\User;

class UserService
{
    public function syncAuthavaUser(array $authavaUser): User
    {
        return User::updateOrCreate(
            ['auth_id' => $authavaUser['id']],
            [
                'email' => $authavaUser['email'],
                'name' => $authavaUser['name'] ?? null,
                // Map other fields as needed
            ]
        );
    }
}

// config/authava.php
return [
    'user_model' => \App\Models\User::class,
    'user_fields' => [
        'auth_id' => 'id',
        'email' => 'email',
        'name' => 'name',
        // Add custom field mappings
    ],
];
bash
php artisan vendor:publish --tag=authava-config