PHP code example of elenyum / authorization

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

    

elenyum / authorization example snippets


use Elenyum\Authorization\Attribute\Auth;
use App\Entity\Figure;

#[Auth(name: 'Bearer', model: Figure::class)]
public function someAction()
{
    // Action logic
}

namespace App\Security\Voter;

use App\Entity\Figure;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class FigureVoter extends Voter
{
    private $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    protected function supports(string $attribute, $subject): bool
    {
        return in_array($attribute, ['VIEW', 'EDIT']) && $subject instanceof Figure;
    }

    protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();
        if (!$user instanceof UserInterface) {
            return false;
        }

        // Check if the user is the owner of the record
        return $subject->getOwnerId() === $user->getId();
    }
}

if (!$this->isGranted('EDIT', $figure)) {
    throw $this->createAccessDeniedException('Access denied.');
}
bash
php bin/console doctrine:migrations:migrate