为用户动态添加角色 [英] Dynamically adding roles to a user
问题描述
我们正在使用 Symfony2 的角色功能来限制用户访问我们应用程序的某些部分.用户可以购买年度订阅,我们的每个 User
实体都有许多具有开始日期和结束日期的 Subscription
实体.
We are using Symfony2's roles feature to restrict users' access to certain parts of our app. Users can purchase yearly subscriptions and each of our User
entities has many Subscription
entities that have a start date and an end.
现在,有没有一种方法可以根据用户是否有活动"订阅动态地向用户添加角色?在 Rails 中,我会简单地让模型处理它是否具有必要的权限,但我知道 symfony2 实体按设计不应该访问 Doctrine.
Now, is there a way to dynamically add a role to a user based on whether they have an 'active' subscription? In rails i would simply let the model handle whether it has the necessary rights but I know that by design symfony2 entities are not supposed to have access to Doctrine.
我知道您可以从实体实例中访问实体的关联,但这会通过所有用户的订阅对象,这对我来说似乎不必要地麻烦.
I know that you can access an entity's associations from within an entity instance but that would go through all the user's subscription objects and that seems unnecessaryly cumbersome to me.
推荐答案
我认为您最好设置自定义投票者和属性.
I think you would do better setting up a custom voter and attribute.
/**
* @Route("/whatever/")
* @Template
* @Secure("SUBSCRIPTION_X")
*/
public function viewAction()
{
// etc...
}
SUBSCRIPTION_X
角色(又名属性)需要由自定义投票者类处理.
The SUBSCRIPTION_X
role (aka attribute) would need to be handled by a custom voter class.
class SubscriptionVoter implements VoterInterface
{
private $em;
public function __construct($em)
{
$this->em = $em;
}
public function supportsAttribute($attribute)
{
return 0 === strpos($attribute, 'SUBSCRIPTION_');
}
public function supportsClass($class)
{
return true;
}
public function vote(TokenInterface $token, $object, array $attributes)
{
// run your query and return either...
// * VoterInterface::ACCESS_GRANTED
// * VoterInterface::ACCESS_ABSTAIN
// * VoterInterface::ACCESS_DENIED
}
}
您需要配置和标记您的选民:
You would need to configure and tag your voter:
services:
subscription_voter:
class: SubscriptionVoter
public: false
arguments: [ @doctrine.orm.entity_manager ]
tags:
- { name: security.voter }
这篇关于为用户动态添加角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!