Completed
Push — master ( aba493...5356ed )
by Ruud
315:38 queued 305:00
created

AdminBundle/Helper/Security/Acl/AclHelper.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\AdminBundle\Helper\Security\Acl;
4
5
use Doctrine\ORM\EntityManager;
6
use Doctrine\ORM\Mapping\QuoteStrategy;
7
use Doctrine\ORM\Query;
8
use Doctrine\ORM\Query\Parameter;
9
use Doctrine\ORM\Query\ResultSetMapping;
10
use Doctrine\ORM\QueryBuilder;
11
use InvalidArgumentException;
12
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\MaskBuilder;
13
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionDefinition;
14
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
15
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
16
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
17
use Symfony\Component\Security\Core\Role\RoleInterface;
18
19
/**
20
 * AclHelper is a helper class to help setting the permissions when querying using ORM
21
 *
22
 * @see https://gist.github.com/1363377
23
 */
24
class AclHelper
25
{
26
    /**
27
     * @var EntityManager
28
     */
29
    private $em = null;
30
31
    /**
32
     * @var TokenStorageInterface
33
     */
34
    private $tokenStorage = null;
35
36
    /**
37
     * @var QuoteStrategy
38
     */
39
    private $quoteStrategy = null;
40
41
    /**
42
     * @var RoleHierarchyInterface
43
     */
44
    private $roleHierarchy = null;
45
46
    /**
47
     * Constructor.
48
     *
49
     * @param EntityManager          $em           The entity manager
50
     * @param TokenStorageInterface  $tokenStorage The security token storage
51
     * @param RoleHierarchyInterface $rh           The role hierarchies
52
     */
53 5
    public function __construct(EntityManager $em, TokenStorageInterface $tokenStorage, RoleHierarchyInterface $rh)
0 ignored issues
show
You have injected the EntityManager via parameter $em. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
54
    {
55 5
        $this->em = $em;
56 5
        $this->tokenStorage = $tokenStorage;
57 5
        $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
58 5
        $this->roleHierarchy = $rh;
59 5
    }
60
61
    /**
62
     * Clone specified query with parameters.
63
     *
64
     * @param Query $query
65
     *
66
     * @return Query
67
     */
68 2
    protected function cloneQuery(Query $query)
69
    {
70 2
        $aclAppliedQuery = clone $query;
71 2
        $params = $query->getParameters();
72
        /* @var $param Parameter */
73 2
        foreach ($params as $param) {
74 2
            $aclAppliedQuery->setParameter($param->getName(), $param->getValue(), $param->getType());
75
        }
76
77 2
        return $aclAppliedQuery;
78
    }
79
80
    /**
81
     * Apply the ACL constraints to the specified query builder, using the permission definition
82
     *
83
     * @param QueryBuilder         $queryBuilder  The query builder
84
     * @param PermissionDefinition $permissionDef The permission definition
85
     *
86
     * @return Query
87
     */
88 2
    public function apply(QueryBuilder $queryBuilder, PermissionDefinition $permissionDef)
89
    {
90 2
        $whereQueryParts = $queryBuilder->getDQLPart('where');
91 2
        if (empty($whereQueryParts)) {
92 2
            $queryBuilder->where('1 = 1'); // this will help in cases where no where query is specified
93
        }
94
95 2
        $query = $this->cloneQuery($queryBuilder->getQuery());
96
97 2
        $builder = new MaskBuilder();
98 2 View Code Duplication
        foreach ($permissionDef->getPermissions() as $permission) {
99 2
            $mask = constant(get_class($builder) . '::MASK_' . strtoupper($permission));
100 2
            $builder->add($mask);
101
        }
102 2
        $query->setHint('acl.mask', $builder->get());
103 2
        $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Kunstmaan\AdminBundle\Helper\Security\Acl\AclWalker');
104
105 2
        $rootEntity = $permissionDef->getEntity();
106 2
        $rootAlias = $permissionDef->getAlias();
107
        // If either alias or entity was not specified - use default from QueryBuilder
108 2
        if (empty($rootEntity) || empty($rootAlias)) {
109 2
            $rootEntities = $queryBuilder->getRootEntities();
110 2
            $rootAliases = $queryBuilder->getRootAliases();
111 2
            $rootEntity = $rootEntities[0];
112 2
            $rootAlias = $rootAliases[0];
113
        }
114 2
        $query->setHint('acl.root.entity', $rootEntity);
115 2
        $query->setHint('acl.extra.query', $this->getPermittedAclIdsSQLForUser($query));
116
117 2
        $classMeta = $this->em->getClassMetadata($rootEntity);
118 2
        $entityRootTableName = $this->quoteStrategy->getTableName(
119 2
            $classMeta,
120 2
            $this->em->getConnection()->getDatabasePlatform()
121
        );
122 2
        $query->setHint('acl.entityRootTableName', $entityRootTableName);
123 2
        $query->setHint('acl.entityRootTableDqlAlias', $rootAlias);
124
125 2
        return $query;
126
    }
127
128
    /**
129
     * This query works well with small offset, but if want to use it with large offsets please refer to the link on how to implement
130
     * http://www.scribd.com/doc/14683263/Efficient-Pagination-Using-MySQL
131
     * This will only check permissions on the first entity added in the from clause, it will not check permissions
132
     * By default the number of rows returned are 10 starting from 0
133
     *
134
     * @param Query $query
135
     *
136
     * @return string
137
     */
138 3
    private function getPermittedAclIdsSQLForUser(Query $query)
139
    {
140 3
        $aclConnection = $this->em->getConnection();
141 3
        $databasePrefix = is_file($aclConnection->getDatabase()) ? '' : $aclConnection->getDatabase().'.';
142 3
        $mask = $query->getHint('acl.mask');
143 3
        $rootEntity = '"' . str_replace('\\', '\\\\', $query->getHint('acl.root.entity')) . '"';
144
145
        /* @var $token TokenInterface */
146 3
        $token = $this->tokenStorage->getToken();
147 3
        $userRoles = array();
148 3
        $user = null;
149 3 View Code Duplication
        if (!is_null($token)) {
150 3
            $user = $token->getUser();
151 3
            $userRoles = $this->roleHierarchy->getReachableRoles($token->getRoles());
152
        }
153
154
        // Security context does not provide anonymous role automatically.
155 3
        $uR = array('"IS_AUTHENTICATED_ANONYMOUSLY"');
156
157
        /* @var $role RoleInterface */
158 3 View Code Duplication
        foreach ($userRoles as $role) {
159
            // The reason we ignore this is because by default FOSUserBundle adds ROLE_USER for every user
160 2
            if ($role->getRole() !== 'ROLE_USER') {
161 2
                $uR[] = '"' . $role->getRole() . '"';
162
            }
163
        }
164 3
        $uR = array_unique($uR);
165 3
        $inString = implode(' OR s.identifier = ', $uR);
166
167 3 View Code Duplication
        if (is_object($user)) {
168 2
            $inString .= ' OR s.identifier = "' . str_replace(
169 2
                    '\\',
170 2
                    '\\\\',
171 2
                    get_class($user)
172 2
                ) . '-' . $user->getUserName() . '"';
173
        }
174
175
        $selectQuery = <<<SELECTQUERY
176 3
SELECT DISTINCT o.object_identifier as id FROM {$databasePrefix}acl_object_identities as o
177 3
INNER JOIN {$databasePrefix}acl_classes c ON c.id = o.class_id
178 3
LEFT JOIN {$databasePrefix}acl_entries e ON (
179
    e.class_id = o.class_id AND (e.object_identity_id = o.id
180 3
    OR {$aclConnection->getDatabasePlatform()->getIsNullExpression('e.object_identity_id')})
181
)
182 3
LEFT JOIN {$databasePrefix}acl_security_identities s ON (
183
s.id = e.security_identity_id
184
)
185 3
WHERE c.class_type = {$rootEntity}
186 3
AND (s.identifier = {$inString})
187 3
AND e.mask & {$mask} > 0
188
SELECTQUERY;
189
190 3
        return $selectQuery;
191
    }
192
193
    /**
194
     * Returns valid IDs for a specific entity with ACL restrictions for current user applied
195
     *
196
     * @param PermissionDefinition $permissionDef
197
     *
198
     * @throws InvalidArgumentException
199
     *
200
     * @return array
201
     */
202 2
    public function getAllowedEntityIds(PermissionDefinition $permissionDef)
203
    {
204 2
        $rootEntity = $permissionDef->getEntity();
205 2
        if (empty($rootEntity)) {
206 1
            throw new InvalidArgumentException('You have to provide an entity class name!');
207
        }
208 1
        $builder = new MaskBuilder();
209 1 View Code Duplication
        foreach ($permissionDef->getPermissions() as $permission) {
210 1
            $mask = constant(get_class($builder) . '::MASK_' . strtoupper($permission));
211 1
            $builder->add($mask);
212
        }
213
214 1
        $query = new Query($this->em);
215 1
        $query->setHint('acl.mask', $builder->get());
216 1
        $query->setHint('acl.root.entity', $rootEntity);
217 1
        $sql = $this->getPermittedAclIdsSQLForUser($query);
218
219 1
        $rsm = new ResultSetMapping();
220 1
        $rsm->addScalarResult('id', 'id');
221 1
        $nativeQuery = $this->em->createNativeQuery($sql, $rsm);
222
223
        $transform = function ($item) {
224 1
            return $item['id'];
225 1
        };
226 1
        $result = array_map($transform, $nativeQuery->getScalarResult());
227
228 1
        return $result;
229
    }
230
231
    /**
232
     * @return null|TokenStorageInterface
233
     */
234 1
    public function getTokenStorage()
235
    {
236 1
        return $this->tokenStorage;
237
    }
238
}
239