flagception-bundle icon indicating copy to clipboard operation
flagception-bundle copied to clipboard

[Add] Support roles

Open migo315 opened this issue 6 years ago • 2 comments

Add one standard role provider for active features.

Example:

# For one role
constraint: has_role('ROLE_ADMIN')

# For multiple roles
constraint: "has_role('ROLE_ADMIN') or has_role('ROLE_MOD')"

migo315 avatar May 17 '18 22:05 migo315

Will be implemented in the next version. However, not with the expression language but as a separate field, as in the symfony security component.

flagception:
    features:      
        # Only one role
        feature_123:
            roles: ROLE_ADMIN
            
        # Multiple roles
        feature_456:
            roles: ROLE_ADMIN,ROLE_MOD
        
        # Multiple roles (alternative formatting)
        feature_789:
            roles:
                - ROLE_ADMIN
                - ROLE_MOD

migo315 avatar Sep 28 '18 19:09 migo315

Perhaps this will help others who are looking for a solution. I am using this implementation to get a user context:


namespace App\Utils\FeatureToggle;

use App\Entity\User;
use Flagception\Model\Context;
use Flagception\Decorator\ContextDecoratorInterface;
use Symfony\Component\Security\Core\Security;

class UserContextDecorator implements ContextDecoratorInterface
{

    /** @var Security */
    private $security;

    public function __construct(Security $security)
    {

        $this->security = $security;
    }

    public function getName(): string
    {
        return 'user_context_decorator';
    }

    public function decorate(Context $context): Context
    {
        $vars = $this->security->getUser() instanceof User
            ? [
                'user_id'    => $this->security->getUser()->getId(),
                'user_roles' => $this->security->getUser()->getRoles(),
            ]
            : [
                'user_id'    => null,
                'user_roles' => [],
            ];

        foreach ($vars as $key => $var) {
            $context->add($key, $var);
        }

        return $context;
    }
}

It is important that the getUser() method is only called in the decorate() method. Security::getUser() is always null when called too early.

dsentker avatar Mar 03 '20 10:03 dsentker