I have two different roles in my project: ROLE_USER and ROLE_ADMIN.
I want to get list of all users through REST API's url '/users', but some fields (for example email) can see only those person, who authenticated with ROLE_ADMIN.
So, I have generally 2 questions:
1) On which abstraction level (in MVC pattern) should I decide which information can be returned based on ROLE
2) Which is the best way to implement such a Role-based REST API in Symfony?
Thanks
If you are using JMSSerializer you can use groups to decide what can be seen or not. Then in your controller, or where ever, you could set the group based on the role.
For example with the mapping (in YAML)..
Fully\Qualified\Class\Name:
exclusion_policy: ALL
properties:
id:
groups: [user]
userAndAdmin:
groups: [user]
adminOnly:
groups: [admin]
And then in your controller you would set the group like...
public function getUsersAction(Request $request)
{
$users = $this->getRepository()->findAll();
$serializer = $this->get('jms_serializer.serializer');
$json = $serializer->serialize(
$users,
'json',
SerializationContext::create()->setGroups($this->generateGroups())
);
return new Response($json);
// If you are using FOSRestBundle, which I would recommend, then you would just need to do...
$view = $this
->view($this->getRepository()->findAll();)
->setExclusionGroups($this->generateGroups())
;
return $this->handleView($view);
}
private function generateGroups()
{
$securityContext = $this->get('security.context');
$groups = array();
if ($securityContext->isGranted('ROLE_USER')) {
$groups[] = 'user';
}
if ($securityContext->isGranted('ROLE_ADMIN')) {
$groups[] = 'admin';
}
return $groups;
}
Although the whole "generateGroups" and setting the groups would be better placed in a customer view handler or response generator.
Assuming your hierarchy has ROLE_ADMIN as a parent of ROLE_USER you would get the following results.
ROLE_USER
{
"users": [
{
"id": 1,
"userAndAdmin": "val"
}
]
}
ROLE_ADMIN
{
"users": [
{
"id": 1,
"userAndAdmin": "val",
"adminOnly": "val"
}
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With