我正在使用Symfony 2.3,我找不到一个在两个表上添加安全性的好解决方案。
我有一个用户,这个用户可以获得一个应用程序,他可以使用以下路径访问他的应用程序:/ application / {id}
因此,如果用户链接到应用程序,我想保护此页面。我做了一些检查我的控制器,但这不是很干净:
/**
*
* @param int $idApplication
* @return UserApplication
*/
public function testUserApplication($idApplication){
//get the application
$applicationRepository = $this->getDoctrine()->getRepository('PhoneApplicationBundle:Application');
$application = $applicationRepository->find($idApplication);
if($application==null){
return null;
}
$userApplicationRepository = $this->getDoctrine()->getRepository('PhoneApplicationBundle:UserApplication');
$userApplication = $userApplicationRepository->findOneBy(array(
'user' => $this->getUser(),
'application' => $application
));
return $userApplication;
}
我不知道我是否可以使用安全性来做到这一点。
我尝试了另一种创建服务的解决方案来检查这个
class Test
{
/** @var \Doctrine\ORM\EntityManager */
private $doctrine;
/**
* Constructor
*
* @param Doctrine $doctrine
*/
public function __construct(Doctrine $doctrine)
{
$this->doctrine = $doctrine;
}
public function userApplication($idApplication){
//get the application
$applicationRepository = $this->doctrine->getRepository('PhoneApplicationBundle:Application');
$application = $applicationRepository->find($idApplication);
if($application==null){
return null;
}
$userApplicationRepository = $this->doctrine->getRepository('PhoneApplicationBundle:UserApplication');
$userApplication = $userApplicationRepository->findOneBy(array(
'user' => $this->getUser(),
'application' => $application
));
return $userApplication;
}
}
service.yml:
parameters:
phone_application.test_user_application.class: Phone\ApplicationBundle\Service\Test
services:
phone_application.test_user_application:
class: %phone_application.test_user_application.class%
arguments: [@doctrine]
但我真的不明白如何在控制器中使用它
感谢您的帮助。
答案 0 :(得分:1)
<强>第一强>
如果您想在控制器中使用服务,请执行
$serv = $this->get('nameoftheservice);
//then
$serv->yourFunctionOfTheService();
在你的情况下:
$serv = $this->get('phone_application.test_user_application');
//then
$serv->userApplication($id);
<强>第二强>
另一种方法:
如果控制器中的$user
对象完全可用,请执行以下操作:
//get the app
$application = $this->getDoctrine()->getRepository('PhoneApplicationBundle:Application')->find($idApplication);
//check if this user owns this app, considering you have sets the right doctrine annotation for relation in your entity file
if($user->getApplications()->contains($application)) {
//do your stuff
}
else
throw new \Exception('No right there ! ');