Completed
Pull Request — 5.6 (#2830)
by Jeroen
14:14
created

AdminBundle/Helper/Security/Acl/AclHelper.php (2 issues)

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
18
/**
19
 * AclHelper is a helper class to help setting the permissions when querying using ORM
20
 *
21
 * @see https://gist.github.com/1363377
22
 */
23
class AclHelper
24
{
25
    /**
26
     * @var EntityManager
27
     */
28
    private $em = null;
29
30
    /**
31
     * @var TokenStorageInterface
32
     */
33
    private $tokenStorage = null;
34
35
    /**
36
     * @var QuoteStrategy
37
     */
38
    private $quoteStrategy = null;
39
40
    /**
41
     * @var RoleHierarchyInterface
42
     */
43
    private $roleHierarchy = null;
44
45
    /**
46
     * @var bool
47
     */
48
    private $permissionsEnabled;
49
50
    /**
51
     * Constructor.
52
     *
53
     * @param EntityManager          $em           The entity manager
54
     * @param TokenStorageInterface  $tokenStorage The security token storage
55
     * @param RoleHierarchyInterface $rh           The role hierarchies
56
     */
57 5 View Code Duplication
    public function __construct(EntityManager $em, TokenStorageInterface $tokenStorage, RoleHierarchyInterface $rh, $permissionsEnabled = true)
58
    {
59 5
        $this->em = $em;
60 5
        $this->tokenStorage = $tokenStorage;
61 5
        $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
62 5
        $this->roleHierarchy = $rh;
63 5
        $this->permissionsEnabled = $permissionsEnabled;
64 5
    }
65
66
    /**
67
     * Clone specified query with parameters.
68
     *
69
     * @return Query
70
     */
71 2
    protected function cloneQuery(Query $query)
72
    {
73 2
        $aclAppliedQuery = clone $query;
74 2
        $params = $query->getParameters();
75
        /* @var $param Parameter */
76 2
        foreach ($params as $param) {
77 2
            $aclAppliedQuery->setParameter($param->getName(), $param->getValue(), $param->getType());
78
        }
79
80 2
        return $aclAppliedQuery;
81
    }
82
83
    /**
84
     * Apply the ACL constraints to the specified query builder, using the permission definition
85
     *
86
     * @param QueryBuilder         $queryBuilder  The query builder
87
     * @param PermissionDefinition $permissionDef The permission definition
88
     *
89
     * @return Query
90
     */
91 2
    public function apply(QueryBuilder $queryBuilder, PermissionDefinition $permissionDef)
92
    {
93 2
        if (!$this->permissionsEnabled) {
94
            return $queryBuilder->getQuery();
95
        }
96
97 2
        $whereQueryParts = $queryBuilder->getDQLPart('where');
98 2
        if (empty($whereQueryParts)) {
99 2
            $queryBuilder->where('1 = 1'); // this will help in cases where no where query is specified
100
        }
101
102 2
        $query = $this->cloneQuery($queryBuilder->getQuery());
103
104 2
        $builder = new MaskBuilder();
105 2 View Code Duplication
        foreach ($permissionDef->getPermissions() as $permission) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
106 2
            $mask = \constant(\get_class($builder) . '::MASK_' . strtoupper($permission));
107 2
            $builder->add($mask);
108
        }
109 2
        $query->setHint('acl.mask', $builder->get());
110 2
        $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Kunstmaan\AdminBundle\Helper\Security\Acl\AclWalker');
111
112 2
        $rootEntity = $permissionDef->getEntity();
113 2
        $rootAlias = $permissionDef->getAlias();
114
        // If either alias or entity was not specified - use default from QueryBuilder
115 2
        if (empty($rootEntity) || empty($rootAlias)) {
116 2
            $rootEntities = $queryBuilder->getRootEntities();
117 2
            $rootAliases = $queryBuilder->getRootAliases();
118 2
            $rootEntity = $rootEntities[0];
119 2
            $rootAlias = $rootAliases[0];
120
        }
121 2
        $query->setHint('acl.root.entity', $rootEntity);
122 2
        $query->setHint('acl.extra.query', $this->getPermittedAclIdsSQLForUser($query));
123
124 2
        $classMeta = $this->em->getClassMetadata($rootEntity);
125 2
        $entityRootTableName = $this->quoteStrategy->getTableName(
126 2
            $classMeta,
127 2
            $this->em->getConnection()->getDatabasePlatform()
128
        );
129 2
        $query->setHint('acl.entityRootTableName', $entityRootTableName);
130 2
        $query->setHint('acl.entityRootTableDqlAlias', $rootAlias);
131
132 2
        return $query;
133
    }
134
135
    /**
136
     * 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
137
     * http://www.scribd.com/doc/14683263/Efficient-Pagination-Using-MySQL
138
     * This will only check permissions on the first entity added in the from clause, it will not check permissions
139
     * By default the number of rows returned are 10 starting from 0
140
     *
141
     * @return string
142
     */
143 3
    private function getPermittedAclIdsSQLForUser(Query $query)
144
    {
145 3
        $aclConnection = $this->em->getConnection();
146 3
        $databasePrefix = is_file($aclConnection->getDatabase()) ? '' : $aclConnection->getDatabase() . '.';
147 3
        $mask = $query->getHint('acl.mask');
148 3
        $rootEntity = '"' . str_replace('\\', '\\\\', $query->getHint('acl.root.entity')) . '"';
149
150
        /* @var $token TokenInterface */
151 3
        $token = $this->tokenStorage->getToken();
152 3
        $userRoles = [];
153 3
        $user = null;
154 3 View Code Duplication
        if (!\is_null($token)) {
155 3
            $user = $token->getUser();
156 3
            if (method_exists($this->roleHierarchy, 'getReachableRoleNames')) {
157 3
                $userRoles = $this->roleHierarchy->getReachableRoleNames($token->getRoleNames());
158
            } else {
159
                // Symfony 3.4 compatibility
160
                $userRoles = $this->roleHierarchy->getReachableRoles($token->getRoles());
161
            }
162
        }
163
164
        // Security context does not provide anonymous role automatically.
165 3
        $uR = ['"IS_AUTHENTICATED_ANONYMOUSLY"'];
166
167 3 View Code Duplication
        foreach ($userRoles as $role) {
168
            // The reason we ignore this is because by default FOSUserBundle adds ROLE_USER for every user
169 3
            if (is_string($role)) {
170 3
                if ($role !== 'ROLE_USER') {
171 3
                    $uR[] = '"' . $role . '"';
172
                }
173
            } else {
174
                // Symfony 3.4 compatibility
175
                if ($role->getRole() !== 'ROLE_USER') {
176
                    $uR[] = '"' . $role->getRole() . '"';
177
                }
178
            }
179
        }
180 3
        $uR = array_unique($uR);
181 3
        $inString = implode(' OR s.identifier = ', $uR);
182
183 3 View Code Duplication
        if (\is_object($user)) {
184 2
            $inString .= ' OR s.identifier = "' . str_replace(
185 2
                '\\',
186 2
                '\\\\',
187 2
                \get_class($user)
188 2
            ) . '-' . $user->getUserName() . '"';
189
        }
190
191
        $selectQuery = <<<SELECTQUERY
192 3
SELECT DISTINCT o.object_identifier as id FROM {$databasePrefix}acl_object_identities as o
193 3
INNER JOIN {$databasePrefix}acl_classes c ON c.id = o.class_id
194 3
LEFT JOIN {$databasePrefix}acl_entries e ON (
195
    e.class_id = o.class_id AND (e.object_identity_id = o.id
196 3
    OR {$aclConnection->getDatabasePlatform()->getIsNullExpression('e.object_identity_id')})
197
)
198 3
LEFT JOIN {$databasePrefix}acl_security_identities s ON (
199
s.id = e.security_identity_id
200
)
201 3
WHERE c.class_type = {$rootEntity}
202 3
AND (s.identifier = {$inString})
203 3
AND e.mask & {$mask} > 0
204
SELECTQUERY;
205
206 3
        return $selectQuery;
207
    }
208
209
    /**
210
     * Returns valid IDs for a specific entity with ACL restrictions for current user applied
211
     *
212
     * @throws InvalidArgumentException
213
     *
214
     * @return array
215
     */
216 2
    public function getAllowedEntityIds(PermissionDefinition $permissionDef)
217
    {
218 2
        $rootEntity = $permissionDef->getEntity();
219 2
        if (empty($rootEntity)) {
220 1
            throw new InvalidArgumentException('You have to provide an entity class name!');
221
        }
222 1
        $builder = new MaskBuilder();
223 1 View Code Duplication
        foreach ($permissionDef->getPermissions() as $permission) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
224 1
            $mask = \constant(\get_class($builder) . '::MASK_' . strtoupper($permission));
225 1
            $builder->add($mask);
226
        }
227
228 1
        $query = new Query($this->em);
229 1
        $query->setHint('acl.mask', $builder->get());
230 1
        $query->setHint('acl.root.entity', $rootEntity);
231 1
        $sql = $this->getPermittedAclIdsSQLForUser($query);
232
233 1
        $rsm = new ResultSetMapping();
234 1
        $rsm->addScalarResult('id', 'id');
235 1
        $nativeQuery = $this->em->createNativeQuery($sql, $rsm);
236
237
        $transform = function ($item) {
238 1
            return $item['id'];
239 1
        };
240 1
        $result = array_map($transform, $nativeQuery->getScalarResult());
241
242 1
        return $result;
243
    }
244
245
    /**
246
     * @return TokenStorageInterface|null
247
     */
248 1
    public function getTokenStorage()
249
    {
250 1
        return $this->tokenStorage;
251
    }
252
}
253