Check ACL permissions of several users for an object - symfony

I'm using Symfony Security/ACL component to check permissions of a group of "random" users for a given domain object.
$article = ...; // domain object
$users = ...; // array of users
$oid = ObjectIdentity::fromDomainObject($article);
$sids = array();
for ($users as $user) {
$sids[] = UserSecurityIdentity::fromAccount($user);
}
$aclProvider = ...; // "security.acl.provider" service
$acl = $aclProvider->findAcl($oid, $sids);
However, I'm having trouble checking whether given permission is granted for a given user. How can I do that?

I think you should use Acl Voter:
http://symfony.com/doc/current/cookbook/security/acl.html#checking-access

Related

In Symfony2 how can I get a users full list of roles

I would like to pass the authenticated users list of roles to my front end apps, so I can use the same access control structure in the front and back end.
I was looking in the security / authentication classes as that is where the isGranted function are for me to do this
$this->container->get('security.context')->isGranted('ROLE_SUPER_ADMIN')
I can't find anything to get a list of roles though, is this not a supported feature?
nb: I don't want the entire role hierarchy, just the list of roles for the authenticated user
I ended up adding a new repository function and a service method to get this info.
MyProject/UserBundle/Entity/Repository/UserRepository
public function getRoles($userId)
{
$queryBuilder = $this->createQueryBuilder('u');
$queryBuilder
->select('u.id, u.roles AS user_roles, g.roles AS group_roles')
->leftJoin('u.groups', 'g')
->andWhere('u.id = :user_id')
->setParameter('user_id', $userId);
return $queryBuilder->getQuery()->getArrayResult();
}
MyProject/UserBundle/Service/UserService
public function getUserRoles($user)
{
$groupRoles = $this->repository->getRoles($user->getId());
$roles = array('user_roles' => array(), 'group_roles' => array());
foreach ($groupRoles as $groupRole) {
$roles['user_roles'] = array_merge($roles['user_roles'], $groupRole['user_roles']);
$roles['group_roles'] = array_merge($roles['group_roles'], $groupRole['group_roles']);
}
return $roles;
}
This gives me an array like this
"roles":{
"user_roles":[],
"group_roles":["ROLE_ADMIN","ROLE_ONE","ROLE_TWO","ROLE_BEST"]
}
Assuming you're using the Symfony security component, the user interface which your user class implements has this already included:
$user = $this->get('security.token_storage')->getToken()->getUser();
var_dump($user->getRoles());
http://api.symfony.com/3.1/Symfony/Component/Security/Core/User/UserInterface.html#method_getRoles

Symfony 2: Form Permissions Authorization Strategy

I have a Symfony application with five different entities (what they are doesn't really matter).
For each of these entities, a registered user must either have NONE, READ, EDIT, DELETE permissions. The sticky part for me to grasp is that each user can have different permissions for each entity; User A can edit Entity A, but can only view Entity B, etc.
Now on each user's options page, an admin should be able to see his permissions for each form. Radio buttons should be displayed with the four options for each form. Something like:
Entity A: O NONE O READ X EDIT O DELETE
Entity B: O NONE X READ O EDIT O DELETE
...
I know my choices are basically between creating some type of Voter system or an Access Control List.
At first I just started by listing all of the roles currently in the system within my UserType:
$builder
...
->add('roles', 'choice', array(
'choices' => $this->roles,
'choices_as_values' => true,
'label' => 'Roles',
'expanded' => true,
'multiple' => true,
'mapped' => true,
))
;
but I'm feeling like this isn't going to be very effective in the long run. And either way, this also displays other system roles that have nothing to do with access control to specific entities (such as ROLE_USER, ROLE_ADMIN, etc.)
I'm not looking for a complete solution or anything like that, I'm just having a really hard time getting started and seeing the big picture on how to make this happen. (And yes, I am aware of the Symfony documentation...sometimes that stuff just doesn't make a ton of sense at first).
PROGRESS UPDATE
I decided on Access Control List.
First, when a new entity is created, I use the standard ACL creation strategy as mentioned in the Symfony Documentation:
public function postAvrequestAction(Request $request){
$entity = new AvRequest();
$form = $this->get('form.factory')->createNamed('', new AvRequestType(), $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$serializer = $this->get('serializer');
$serialized = $serializer->serialize($entity, 'json');
// creating the ACL
$aclProvider = $this->get('security.acl.provider');
$objectIdentity = ObjectIdentity::fromDomainObject($entity);
$acl = $aclProvider->createAcl($objectIdentity);
// retrieving the security identity of the currently logged-in user
$tokenStorage = $this->get('security.token_storage');
$users = $em->getRepository('AppBundle:User')->findAll();
//$tokenStorage->getToken()->getUser();
foreach($users as $user){
$securityIdentity = UserSecurityIdentity::fromAccount($user);
// grant owner access based on owner's overall permissions for this type of entity
$acl->insertObjectAce($securityIdentity, 0);
$aclProvider->updateAcl($acl);
}
return new Response($serialized, 201);
}
return new JsonResponse(array(
'errors' => $this->getFormErrors($form)
));
}
Next, I created a service with all of the necessary dependencies to update a user's permissions for each entity:
#services.yml
services:
user_service:
class: AppBundle\Resources\Services\UserService
arguments: [ #doctrine.orm.entity_manager, #service_container, #security.authorization_checker, #security.acl.provider ]
The service has the function:
/**
* ACLs grant user permission on every instance of each entity.
* In order to edit permissions across all of these entites for each user,
* first iterate over all entities.
* For each entity, update the permission for the specified user.
*
* #param \AppBundle\Entity\User $user The user object whose permissions should be updated
* #param String $entity The entity whose permissions should be updated (e.g. 'AppBundle:AvRequest')
* #param int $permission The bitmask value of the permission level (e.g. MaskBuilder::MASK_VIEW (=4))
*
* #return null
*/
public function editPermission(User $user, $entity, $permission){
$allEntities = $this->em->getRepository($entity)->findAll();
foreach($allEntities as $oneEntity){
// locate the ACL
$objectIdentity = ObjectIdentity::fromDomainObject($oneEntity);
$acl = $this->aclProvider->findAcl($objectIdentity);
// update user access
$objectAces = $acl->getObjectAces();
foreach($objectAces as $i => $ace) {
$acl->updateObjectAce($i, $permission);
}
}
}
This function goes through every instance of the entity and gives it the same permission level for the specified user.
The next step that I haven't quite figured out yet is setting a master permission level for a user on an entity as described up top with my radio buttons. I need to be able to go to the user's profile page, see a radio list of the user's permissions for each entity type, submit the radio button value and then run the editPermission() function on save.
You are looking for Access Control Lists. It is easy to set permission by user or group of users.
Add access level by user:
$builder = new MaskBuilder();
$builder
->add('view')
->add('edit')
->add('delete')
->add('undelete')
;
$mask = $builder->get(); // int(29)
$identity = new UserSecurityIdentity('johannes', 'AppBundle\Entity\User');
$acl->insertObjectAce($identity, $mask);
Specify min access level by entity:
public function addCommentAction(Post $post)
{
$comment = new Comment();
// ... setup $form, and submit data
if ($form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
// creating the ACL
$aclProvider = $this->get('security.acl.provider');
$objectIdentity = ObjectIdentity::fromDomainObject($comment);
$acl = $aclProvider->createAcl($objectIdentity);
// retrieving the security identity of the currently logged-in user
$tokenStorage = $this->get('security.token_storage');
$user = $tokenStorage->getToken()->getUser();
$securityIdentity = UserSecurityIdentity::fromAccount($user);
// grant owner access
$acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OWNER);
$aclProvider->updateAcl($acl);
}
}
public function editCommentAction(Comment $comment)
{
$authorizationChecker = $this->get('security.authorization_checker');
// check for edit access
if (false === $authorizationChecker->isGranted('EDIT', $comment)) {
throw new AccessDeniedException();
}
// ... retrieve actual comment object, and do your editing here
}

Check if a role is granted for a specific user in Symfony2 ACL

I want to check if a role is granted for a specific user in Symfony2 (not the logged user).
I know that I can check it for the logged user by:
$securityContext = $this->get('security.context');
if (false === $securityContext->isGranted('VIEW', $objectIdentity)) {
//do anything
}
but if I'm the logged user and I wand to check other user if isGranted ??
The "VIEW" is a permission, not a role.
The best way to check if a user has a right (be it a role or permission) would be to access the AccessDecisionManager. Something like:
$token = new UsernamePasswordToken($user, 'none', 'none', $user->getRoles());
$attributes = is_array($attributes) ? $attributes : array($attributes);
$this->get('security.access.decision_manager')->decide($token, $attributes, $object);
See original answer here: https://stackoverflow.com/a/22380765/971254 for details.
You just need to create a custom security context that will take a user object and generate a UserSecurityIdentity out of it. Here are the steps:
Create a new service in YourApp/AppBundle/Resources/config.yml
yourapp.security_context:
class: YourApp\AppBundle\Security\Core\SecurityContext
arguments: [ #security.acl.provider ]
Create a custom Security Context Class like this:
namespace YourApp\AppBundle\Security\Core;
use Symfony\Component\Security\Acl\Model\MutableAclProviderInterface;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Permission\MaskBuilder;
use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
use YourApp\AppBundle\Document\User;
/**
* Allows ACL checking against a specific user object (regardless of whether that user is logged in or not)
*
*/
class SecurityContext
{
public function __construct(MutableAclProviderInterface $aclProvider)
{
$this->aclProvider = $aclProvider;
}
public function isGranted($mask, $object, User $user)
{
$objectIdentity = ObjectIdentity::fromDomainObject($object);
$securityIdentity = UserSecurityIdentity::fromAccount($user);
try {
$acl = $this->aclProvider->findAcl($objectIdentity, array($securityIdentity));
} catch (AclNotFoundException $e) {
return false;
}
if (!is_int($mask)) {
$builder = new MaskBuilder;
$builder->add($mask);
$mask = $builder->get();
}
try {
return $acl->isGranted(array($mask), array($securityIdentity), false);
} catch (NoAceFoundException $e) {
return false;
}
}
}
Now you can inject that service where needed, or use it from a controller like this:
$someUser = $this->findSomeUserFromYourDatabase();
if ($this->get('yourapp.security_context')->isGranted('VIEW', $article, $someUser) {
// ...
}
Checking roles for another user can not be done via the SecurityContext as this will always hold the current user's session token. Your task can be achieved for example via the getRoles method, if the user you need to check implements the UserInterface.
$otherUser = $this->get('doctrine')->... // fetch the user
if( $otherUser instanceof \Symfony\Component\Security\Core\User\UserInterface )
{
$roles = $otherUser->getRoles();
// your role could be VIEW or ROLE_VIEW, check the $roles array above.
if ( in_array( 'VIEW' , $roles ) )
{
// do something else
}
}
If your user entity implement the FosUserBundle UserInterFace, that has a dedicated method hasRole. In that case you could use a one-liner:
$otherUser = $this->get('doctrine')->... // fetch the user
if( $otherUser instanceof \FOS\UserBundle\Model\UserInterface )
{
// your role could be VIEW or ROLE_VIEW, check the proper role names
if ( $otherUser->hasRole( 'VIEW' ) )
{
// do something else
}
}

How to get plain password user with Symfony2?

I have to get the user's plain password for LDAP authentification and then retrieve LDAP user informations in the Active Directory with Symfony2.
/**
* #Route("/infos-profil/{id}", name="infos_profil")
* #Template()
*/
public function infosProfilAction($id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('MyUserBundle:LdapUser')->find($id); // Find User Entity
if (!$user) {
throw $this->createNotFoundException('Unable to find LdapUser entity.');
}
$login = $user->getUsername(); // Login
$pass = $user->getPlainPassword(); // Password
$ds = ldap_connect("12.34.56.789"); // Domain connexion
if ($ds) {
$r = ldap_bind($ds, $login, $pass); // LDAP User connexion
if ($r) {
$filter = "(&(objectClass=user)(samaccountname=".$login.")(cn=*))";
$sr=ldap_search($ds, "ou=DOMAIN, ou=Test, ou=Users, dc=ats, dc=lan", $filter);
$info = ldap_get_entries($ds, $sr); // Retrieve user's Active Direcory informations
}
}
return array(
'user' => $user,
'info' => $info,
}
But it doesn't work, $pass is empty. When I put the plain password manually in the ldap_bind() function it works perfectly, I just have to get the plain password ! ...
Is it possible ?
It isn't possible to retrieve plain password from database for obvious security reasons.
For your problem, you should create a custom Authentication Provider, following this tutorial : https://symfony.com/doc/4.4/security/custom_authentication_provider.html
This way, your provider will get the plain password from the login form and you will be able to send it to your LDAP server.
You don't need the user's password to retrieve information about them from active directory. Once they are authenticated simply look them up via LDAP using their username, with either an anonymous connection or failing that, a known privileged account.

Why does Symfony2 ACL go by username instead of ID?

I just started using Symfony's ACL system and was wondering why UserSecurityIdentity uses the username instead of the id of a User object to determine it's identity?
$user = new User();
$user->setId(new \MongoId());
$user->setUsername("frodo");
$dm->persist($user);
$uid = UserSecurityIdentity::fromAccount($user); // uses "frodo"
Our system allows users to alter their username, so using something more permanent (like the ID) to determine a user's identity seems more appropriate to me. Why was the ACL system implemented to use the username and not the ID? Any security considerations here?
This issue has been discussed here:
https://github.com/symfony/symfony/issues/5787
And has been solved in this commit:
https://github.com/symfony/symfony/commit/8d39213f4cca19466f84a5656a199eee98602ab1
So, now, whenever a user alter it's username, you can update its security indentity. I use a listener to do this:
public function preUpdate(PreUpdateEventArgs $eventArgs)
{
/** Update user security identity in case nick is changed * */
if ($entity instanceof \Acme\UserBundle\Entity\User && $eventArgs->hasChangedField('username')) {
$aclProvider = $this->container->get('security.acl.provider');
$securityId = UserSecurityIdentity::fromAccount($entity);
$aclProvider->updateUserSecurityIdentity($securityId, $eventArgs->getOldValue('username'));
}
}
This is implementation of fromAccount() method from Symfony\Component\Security\Acl\Domain\UserSecurityIdentity class:
public static function fromAccount(UserInterface $user)
{
return new self($user->getUsername(), ClassUtils::getRealClass($user));
}
I think it is answer on your question.

Resources