/** * Adds joins and conditions to the QueryBuilder in order to only return entities the given user is allowed to see. * * @param QueryBuilder $queryBuilder The instance of the QueryBuilder to adjust * @param UserInterface $user The user for which the access control is checked * @param int $permission The permission mask for which is checked * @param string $entityClass The class of the entity of which the access control is checked * @param string $entityAlias The alias of the entity used in the query builder */ protected function addAccessControl(QueryBuilder $queryBuilder, UserInterface $user, $permission, $entityClass, $entityAlias) { $queryBuilder->leftJoin(AccessControl::class, 'accessControl', 'WITH', 'accessControl.entityClass = :entityClass AND accessControl.entityId = ' . $entityAlias . '.id'); $queryBuilder->leftJoin('accessControl.role', 'role'); $queryBuilder->andWhere('BIT_AND(accessControl.permissions, :permission) = :permission OR accessControl.permissions IS NULL'); $roleIds = []; foreach ($user->getRoleObjects() as $role) { $roleIds[] = $role->getId(); } $queryBuilder->andWhere('role.id IN(:roleIds) OR role.id IS NULL'); $queryBuilder->setParameter('roleIds', $roleIds); $queryBuilder->setParameter('entityClass', $entityClass); $queryBuilder->setParameter('permission', $permission); }
public function testOnPostSerializeWithApiWrapper() { $apiWrapper = $this->prophesize(ApiWrapper::class); $entity = $this->prophesize(SecuredEntityInterface::class); $entity->getId()->willReturn(7); $entity->getSecurityContext()->willReturn('sulu.example'); $apiWrapper->getEntity()->willReturn($entity); $this->objectEvent->getObject()->willReturn($apiWrapper); $securityCondition = new SecurityCondition('sulu.example', null, get_class($entity->reveal()), 7); $permission = ['_permissions' => ['permission' => 'value']]; $this->accessControlManager->getUserPermissions($securityCondition, $this->user->reveal())->willReturn($permission); $this->visitor->addData('_permissions', $permission)->shouldBeCalled(); $this->securedEntitySubscriber->onPostSerialize($this->objectEvent->reveal()); }
/** * @param $changeset The changeset for the entity * @param $expectedFields List of filds which should be updated/set * * @dataProvider provideLifecycle */ public function testOnFlush($changeset, $expectedFields) { $entity = $this->userBlameObject->reveal(); $this->unitOfWork->getScheduledEntityInsertions()->willReturn([$entity]); $this->unitOfWork->getScheduledEntityUpdates()->willReturn([]); $this->entityManager->getClassMetadata(get_class($entity))->willReturn($this->classMetadata); $this->unitOfWork->getEntityChangeSet($this->userBlameObject->reveal())->willReturn($changeset); foreach (['creator', 'changer'] as $field) { $prophecy = $this->classMetadata->setFieldValue($this->userBlameObject->reveal(), $field, $this->user->reveal()); if (in_array($field, $expectedFields)) { $prophecy->shouldBeCalled(); continue; } $prophecy->shouldNotBeCalled(); } if (count($expectedFields)) { $this->unitOfWork->recomputeSingleEntityChangeSet($this->classMetadata->reveal(), $this->userBlameObject->reveal())->shouldBeCalled(); } $this->subscriber->onFlush($this->onFlushEvent->reveal()); }
/** * @param string $type * @param UserInterface $user */ protected function sendMails($type, UserInterface $user) { if ($user instanceof BaseUser) { // get WebSpace type specific config $from = $this->getConfig($type, Configuration::MAIL_FROM); $to = $this->getConfig($type, Configuration::MAIL_TO); $subject = $this->getConfig($type, Configuration::MAIL_SUBJECT); $replyTo = $this->getConfig($type, Configuration::MAIL_REPLY_TO); $adminTemplate = $this->getTemplate($type, Configuration::TEMPLATE_ADMIN); $userTemplate = $this->getTemplate($type, Configuration::TEMPLATE_USER); if ($userTemplate) { // send email to user $body = $this->renderView($userTemplate, ['user' => $user]); $this->getMailHelper()->send($from, $user->getEmail(), $subject, $body, $replyTo); } if ($adminTemplate) { // send email to admin $body = $this->renderView($adminTemplate, ['user' => $user]); $this->getMailHelper()->send($from, $to, $subject, $body, $user->getEmail()); } } }
/** * Resolves permissions for given user. * * @param Row $row * @param UserInterface $user * * @return array */ private function resolvePermissions(Row $row, UserInterface $user = null) { $permissions = []; if (null !== $user) { foreach ($user->getRoleObjects() as $role) { foreach (array_filter(explode(' ', $row->getValue(sprintf('role%s', $role->getId())))) as $permission) { $permissions[$role->getId()][$permission] = true; } } } return $permissions; }
/** * Map the creator and changer to the document. * * @param Document $document * @param UserInterface $creator * @param UserInterface $changer */ private function mapCreatorAndChanger(Document $document, UserInterface $creator = null, UserInterface $changer = null) { $document->addField($this->factory->createField('changer', $changer ? $changer->getUsername() : null, 'string')); $document->addField($this->factory->createField('changer_id', $changer ? $changer->getId() : null, 'string')); $document->addField($this->factory->createField('creator', $creator ? $creator->getUsername() : null, 'string')); $document->addField($this->factory->createField('creator_id', $creator ? $creator->getId() : null, 'string')); }
public function toArray() { return ['code' => $this->code, 'message' => $this->message, 'limit' => $this->limit, 'user' => $this->user->getUsername()]; }
/** * Data can be set over by array. * * @param $media * @param $data * @param UserInterface $user * * @return Media */ protected function setDataToMedia(Media $media, $data, $user) { foreach ($data as $attribute => $value) { if ($value || $attribute === 'tags' && $value !== null || $attribute === 'size' && $value !== null || $attribute === 'description' && $value !== null || $attribute === 'copyright' && $value !== null) { switch ($attribute) { case 'size': $media->setSize($value); break; case 'title': $media->setTitle($value); break; case 'description': $media->setDescription($value); break; case 'copyright': $media->setCopyright($value); break; case 'version': $media->setVersion($value); break; case 'name': $media->setName($value); break; case 'url': $media->setUrl($value); break; case 'formats': $media->setFormats($value); break; case 'storageOptions': $media->setStorageOptions($value); break; case 'publishLanguages': $media->setPublishLanguages($value); break; case 'contentLanguages': $media->setContentLanguages($value); break; case 'tags': $media->removeTags(); if (count($value)) { foreach ($value as $tag) { $tagEntity = $this->tagManager->findOrCreateByName($tag, $user->getId()); $media->addTag($tagEntity); } } break; case 'properties': $media->setProperties($value); break; case 'changed': $media->setChanged($value); break; case 'created': break; case 'changer': if ($value instanceof UserInterface) { $media->setChanger($value); } break; case 'creator': if ($value instanceof UserInterface) { $media->setCreator($value); } break; case 'mimeType': $media->setMimeType($value); break; case 'collection': $collectionEntity = $this->getCollectionById($value); $media->setCollection($collectionEntity); // set parent break; case 'type': if (isset($value['id'])) { $type = $this->typeManager->get($value['id']); $media->setType($type); } break; } } } return $media; }
/** * Processes the email and adds it to the user. * * @param UserInterface $user * @param string $email * @param null|array $contact * * @throws EmailNotUniqueException */ private function processEmail(UserInterface $user, $email, $contact = null) { if ($contact) { // if no email passed try to use the contact's first email if ($email === null && array_key_exists('emails', $contact) && count($contact['emails']) > 0 && $this->isEmailUnique($contact['emails'][0]['email'])) { $email = $contact['emails'][0]['email']; } if ($email !== null) { if (!$this->isEmailUnique($email)) { throw new EmailNotUniqueException($email); } $user->setEmail($email); } } else { if ($email !== null) { if ($email !== $user->getEmail() && !$this->isEmailUnique($email)) { throw new EmailNotUniqueException($email); } $user->setEmail($email); } else { $user->setEmail(null); } } }
/** * Updates the collaborator with the given connection and user to the entity with the specified identifier. * * @param ConnectionInterface $conn The connection of the user * @param string $type The type of the entity * @param mixed $id The id of the entity * @param string $connectionId The id of the connection of the user * @param UserInterface $user The user being added as collaborator */ private function updateCollaboration(ConnectionInterface $conn, $type, $id, $connectionId, UserInterface $user) { $entityCollaborationUpdated = false; $connectionCollaborationUpdated = false; $identifier = $this->getUniqueCollaborationKey($type, $id); $userId = $user->getId(); /** @var Collaboration[] $entityCollaborations */ $entityCollaborations = $this->collaborationsEntityCache->fetch($identifier) ?: []; /** @var Collaboration[] $connectionCollaborations */ $connectionCollaborations = $this->collaborationsConnectionCache->fetch($connectionId) ?: []; if (!array_key_exists($connectionId, $this->connections)) { $this->connections[$connectionId] = $conn; } if (array_key_exists($identifier, $entityCollaborations)) { $entityCollaborations[$identifier]->setChanged(time()); $entityCollaborationUpdated = true; } if (array_key_exists($connectionId, $connectionCollaborations)) { $connectionCollaborations[$connectionId]->setChanged(time()); $connectionCollaborationUpdated = true; } $collaboration = new Collaboration($connectionId, $userId, $user->getUsername(), $user->getFullName(), $type, $id); if (!$entityCollaborationUpdated) { $entityCollaborations[$connectionId] = $collaboration; } if (!$connectionCollaborationUpdated) { $connectionCollaborations[$identifier] = $collaboration; } $this->collaborationsEntityCache->save($identifier, $entityCollaborations); $this->collaborationsConnectionCache->save($connectionId, $connectionCollaborations); }
/** * Returns the permissions for the given security context for the given user. * * @param string $locale * @param string $securityContext * @param UserInterface $user The user for which the security is checked * @param bool $checkPermissionType Flag to show if the permission type should also be checked. If set to false * it will only check if the user has access to the context in the given locale * * @return array */ private function getUserSecurityContextPermissions($locale, $securityContext, UserInterface $user, $checkPermissionType) { $userPermissions = []; foreach ($user->getUserRoles() as $userRole) { $userPermissions = $this->cumulatePermissions($userPermissions, $this->getUserRoleSecurityContextPermission($locale, $securityContext, $userRole, $checkPermissionType)); } return $userPermissions; }
/** * Get Email address of a user; fallback to contact / account if not defined * * @param UserInterface $user * @param bool $useFallback * * @return null|string */ public function getEmailAddressOfUser(UserInterface $user, $useFallback = true) { // take users email address $userEmail = $user->getEmail(); if ($userEmail) { return $userEmail; } // fallback: get contacts / accounts main-email $contact = $user->getContact(); if ($useFallback && $contact) { return $this->getEmailAddressOfContact($contact); } return null; }
/** * @param UserInterface $user * @param null|string $locale * @param null|string $currency * @param bool $persistEmptyCart Define if an empty cart should be persisted * @param bool $updatePrices Defines if prices should be updated * * @return null|ApiOrder */ public function getUserCart($user = null, $locale = null, $currency = null, $persistEmptyCart = false, $updatePrices = false) { // cart by session ID if (!$user) { // TODO: get correct locale $locale = 'de'; $cartsArray = $this->findCartBySessionId(); } else { // TODO: check if cart for this sessionId exists and assign it to user // default locale from user $locale = $locale ?: $user->getLocale(); // get carts $cartsArray = $this->findCartsByUser($user, $locale); } // cleanup cart array: remove duplicates and expired carts $this->cleanupCartsArray($cartArray); // check if cart exists if ($cartsArray && count($cartsArray) > 0) { // multiple carts found, do a cleanup $cart = $cartsArray[0]; } else { // user has no cart - return empty one $cart = $this->createEmptyCart($user, $persistEmptyCart, $locale); } // check if all products are still available $cartNoRemovedProducts = $this->checkProductsAvailability($cart); // create api entity $apiOrder = $this->orderFactory->createApiEntity($cart, $locale); if (!$cartNoRemovedProducts) { $apiOrder->addCartErrorCode(self::CART_STATUS_PRODUCT_REMOVED); } $this->orderManager->updateApiEntity($apiOrder, $locale); // check if prices have changed if ($apiOrder->hasChangedPrices()) { $apiOrder->addCartErrorCode(self::CART_STATUS_PRICE_CHANGED); } if ($updatePrices) { $this->updateCartPrices($apiOrder->getItems()); } return $apiOrder; }