Guards

Guards are classes that implement the ICanActivate interface in Assegai. They are used to block or allow access to routes based on certain conditions. For example, you might have a guard that only allows access to routes if a user has the necessary permissions.

Here's an example of a simple guard that allows access if a request contains a valid api_key in the query string:

src/Auth/ApiKeyGuard.php
use Assegai\Core\Attributes\Injectable;
use Assegai\Core\Interfaces\ICanActivate;
use Assegai\Core\Interfaces\IExecutionContext;

#[Injectable]
class ApiKeyGuard implements ICanActivate
{
  public function canActivate(IExecutionContext $context): bool
  {
    $request = $context->switchToHttp()->getRequest();
    return $request->getQuery()->has('api_key') && $request->getQuery()->get('api_key') === 'abc123';
  }
}

Using guards

To use this guard, you would add the #[UseGuards] attribute to your controller class or any of its route handler methods and specify the guard class:

src/Spears/SpearsController.php
#[Controller('spears')]
#[UseGuards(guard: [ApiKeyGuard::class])]
class SpearsController
{
  // route handlers go here}

You can also specify multiple guards by including them in an array:

#[Controller('spears')]
class SpearsController
{
  #[Get]
  #[UseGuards(guard: [ApiKeyGuard::class, RolesGuard::class])]
  public function findAll()
  {
    // route handler code goes here    ...
  }
}

In this case, both the ApiKeyGuard and RolesGuard must return true for the route to be accessible. If either guard returns false, the route will be blocked.