Completed
Push — master ( 6593b9...0a00fb )
by Jeroen
13:39 queued 07:42
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
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 2
    public function __construct(EntityManager $em, TokenStorageInterface $tokenStorage, RoleHierarchyInterface $rh)
54
    {
55 2
        $this->em = $em;
56 2
        $this->tokenStorage = $tokenStorage;
57 2
        $this->quoteStrategy = $em->getConfiguration()->getQuoteStrategy();
58 2
        $this->roleHierarchy = $rh;
59 2
    }
60
61
    /**
62
     * Clone specified query with parameters.
63
     *
64
     * @param Query $query
65
     *
66
     * @return Query
67
     */
68
    protected function cloneQuery(Query $query)
69
    {
70
        $aclAppliedQuery = clone $query;
71
        $params = $query->getParameters();
72
        /* @var $param Parameter */
73
        foreach ($params as $param) {
74
            $aclAppliedQuery->setParameter($param->getName(), $param->getValue(), $param->getType());
75
        }
76
77
        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
    public function apply(QueryBuilder $queryBuilder, PermissionDefinition $permissionDef)
89
    {
90
        $whereQueryParts = $queryBuilder->getDQLPart('where');
91
        if (empty($whereQueryParts)) {
92
            $queryBuilder->where('1 = 1'); // this will help in cases where no where query is specified
93
        }
94
95
        $query = $this->cloneQuery($queryBuilder->getQuery());
96
97
        $builder = new MaskBuilder();
98 View Code Duplication
        foreach ($permissionDef->getPermissions() as $permission) {
99
            $mask = constant(get_class($builder) . '::MASK_' . strtoupper($permission));
100
            $builder->add($mask);
101
        }
102
        $query->setHint('acl.mask', $builder->get());
103
        $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Kunstmaan\AdminBundle\Helper\Security\Acl\AclWalker');
104
105
        $rootEntity = $permissionDef->getEntity();
106
        $rootAlias = $permissionDef->getAlias();
107
        // If either alias or entity was not specified - use default from QueryBuilder
108
        if (empty($rootEntity) || empty($rootAlias)) {
109
            $rootEntities = $queryBuilder->getRootEntities();
110
            $rootAliases = $queryBuilder->getRootAliases();
111
            $rootEntity = $rootEntities[0];
112
            $rootAlias = $rootAliases[0];
113
        }
114
        $query->setHint('acl.root.entity', $rootEntity);
115
        $query->setHint('acl.extra.query', $this->getPermittedAclIdsSQLForUser($query));
116
117
        $classMeta = $this->em->getClassMetadata($rootEntity);
118
        $entityRootTableName = $this->quoteStrategy->getTableName(
119
            $classMeta,
120
            $this->em->getConnection()->getDatabasePlatform()
121
        );
122
        $query->setHint('acl.entityRootTableName', $entityRootTableName);
123
        $query->setHint('acl.entityRootTableDqlAlias', $rootAlias);
124
125
        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
    private function getPermittedAclIdsSQLForUser(Query $query)
139
    {
140
        $aclConnection = $this->em->getConnection();
141
        $databasePrefix = is_file($aclConnection->getDatabase()) ? '' : $aclConnection->getDatabase().'.';
142
        $mask = $query->getHint('acl.mask');
143
        $rootEntity = '"' . str_replace('\\', '\\\\', $query->getHint('acl.root.entity')) . '"';
144
145
        /* @var $token TokenInterface */
146
        $token = $this->tokenStorage->getToken();
147
        $userRoles = array();
148
        $user = null;
149 View Code Duplication
        if (!is_null($token)) {
150
            $user = $token->getUser();
151
            $userRoles = $this->roleHierarchy->getReachableRoles($token->getRoles());
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Component\Securi...enInterface::getRoles() has been deprecated with message: since Symfony 4.3, use the getRoleNames() method instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
152
        }
153
154
        // Security context does not provide anonymous role automatically.
155
        $uR = array('"IS_AUTHENTICATED_ANONYMOUSLY"');
156
157
        /* @var $role RoleInterface */
158 View Code Duplication
        foreach ($userRoles as $role) {
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...
159
            // The reason we ignore this is because by default FOSUserBundle adds ROLE_USER for every user
160
            if ($role->getRole() !== 'ROLE_USER') {
161
                $uR[] = '"' . $role->getRole() . '"';
162
            }
163
        }
164
        $uR = array_unique($uR);
165
        $inString = implode(' OR s.identifier = ', $uR);
166
167 View Code Duplication
        if (is_object($user)) {
168
            $inString .= ' OR s.identifier = "' . str_replace(
169
                    '\\',
170
                    '\\\\',
171
                    get_class($user)
172
                ) . '-' . $user->getUserName() . '"';
173
        }
174
175
        $selectQuery = <<<SELECTQUERY
176
SELECT DISTINCT o.object_identifier as id FROM {$databasePrefix}acl_object_identities as o
177
INNER JOIN {$databasePrefix}acl_classes c ON c.id = o.class_id
178
LEFT JOIN {$databasePrefix}acl_entries e ON (
179
    e.class_id = o.class_id AND (e.object_identity_id = o.id
180
    OR {$aclConnection->getDatabasePlatform()->getIsNullExpression('e.object_identity_id')})
181
)
182
LEFT JOIN {$databasePrefix}acl_security_identities s ON (
183
s.id = e.security_identity_id
184
)
185
WHERE c.class_type = {$rootEntity}
186
AND (s.identifier = {$inString})
187
AND e.mask & {$mask} > 0
188
SELECTQUERY;
189
190
        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 1
    public function getAllowedEntityIds(PermissionDefinition $permissionDef)
203
    {
204 1
        $rootEntity = $permissionDef->getEntity();
205 1
        if (empty($rootEntity)) {
206 1
            throw new InvalidArgumentException('You have to provide an entity class name!');
207
        }
208
        $builder = new MaskBuilder();
209 View Code Duplication
        foreach ($permissionDef->getPermissions() as $permission) {
210
            $mask = constant(get_class($builder) . '::MASK_' . strtoupper($permission));
211
            $builder->add($mask);
212
        }
213
214
        $query = new Query($this->em);
215
        $query->setHint('acl.mask', $builder->get());
216
        $query->setHint('acl.root.entity', $rootEntity);
217
        $sql = $this->getPermittedAclIdsSQLForUser($query);
218
219
        $rsm = new ResultSetMapping();
220
        $rsm->addScalarResult('id', 'id');
221
        $nativeQuery = $this->em->createNativeQuery($sql, $rsm);
222
223
        $transform = function ($item) {
224
            return $item['id'];
225
        };
226
        $result = array_map($transform, $nativeQuery->getScalarResult());
227
228
        return $result;
229
    }
230
231
    /**
232
     * @return null|TokenStorageInterface
233
     */
234 1
    public function getTokenStorage()
235
    {
236 1
        return $this->tokenStorage;
237
    }
238
}
239