public function testGetByIdentifierNamespace()
 {
     $userId = 1;
     $namespace = 'some_namespace';
     $identifier = 'current';
     $this->userContext->expects($this->once())->method('getUserId')->willReturn($userId);
     $fieldUserId = new Filter([Filter::KEY_FIELD => 'user_id', Filter::KEY_VALUE => $userId, Filter::KEY_CONDITION_TYPE => 'eq']);
     $fieldIdentifier = new Filter([Filter::KEY_FIELD => 'identifier', Filter::KEY_VALUE => $identifier, Filter::KEY_CONDITION_TYPE => 'eq']);
     $fieldNamespace = new Filter([Filter::KEY_FIELD => 'namespace', Filter::KEY_VALUE => $namespace, Filter::KEY_CONDITION_TYPE => 'eq']);
     $bookmarkId = 1;
     $bookmark = $this->getMockBuilder('Magento\\Ui\\Api\\Data\\BookmarkInterface')->getMockForAbstractClass();
     $bookmark->expects($this->once())->method('getId')->willReturn($bookmarkId);
     $searchCriteria = $this->getMockBuilder('Magento\\Framework\\Api\\SearchCriteriaInterface')->getMockForAbstractClass();
     $this->filterBuilder->expects($this->at(0))->method('create')->willReturn($fieldUserId);
     $this->filterBuilder->expects($this->at(1))->method('create')->willReturn($fieldIdentifier);
     $this->filterBuilder->expects($this->at(2))->method('create')->willReturn($fieldNamespace);
     $this->searchCriteriaBuilder->expects($this->once())->method('addFilters')->with([$fieldUserId, $fieldIdentifier, $fieldNamespace]);
     $this->searchCriteriaBuilder->expects($this->once())->method('create')->willReturn($searchCriteria);
     $searchResult = $this->getMockBuilder('Magento\\Ui\\Api\\Data\\BookmarkSearchResultsInterface')->getMockForAbstractClass();
     $searchResult->expects($this->once())->method('getTotalCount')->willReturn(1);
     $searchResult->expects($this->once())->method('getItems')->willReturn([$bookmark]);
     $this->bookmarkRepository->expects($this->once())->method('getList')->with($searchCriteria)->willReturn($searchResult);
     $this->bookmarkRepository->expects($this->once())->method('getById')->with($bookmarkId)->willReturn($bookmark);
     $this->assertEquals($bookmark, $this->bookmarkManagement->getByIdentifierNamespace($identifier, $namespace));
 }
 /**
  * {@inheritDoc}
  */
 public function getOverriddenValue()
 {
     if ($this->userContext->getUserType() === UserContextInterface::USER_TYPE_CUSTOMER) {
         return $this->userContext->getUserId();
     }
     return null;
 }
Esempio n. 3
0
 /**
  * Check if resource for which access is needed has self permissions defined in webapi config.
  *
  * @param \Magento\Framework\Authorization $subject
  * @param callable $proceed
  * @param string $resource
  * @param string $privilege
  *
  * @return bool true If resource permission is self, to allow
  * customer access without further checks in parent method
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundIsAllowed(\Magento\Framework\Authorization $subject, \Closure $proceed, $resource, $privilege = null)
 {
     if ($resource == AuthorizationService::PERMISSION_SELF && $this->userContext->getUserId() && $this->userContext->getUserType() === UserContextInterface::USER_TYPE_CUSTOMER) {
         return true;
     } else {
         return $proceed($resource, $privilege);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function getAclRoleId()
 {
     $userId = $this->userContext->getUserId();
     $userType = $this->userContext->getUserType();
     $roleCollection = $this->roleCollectionFactory->create();
     /** @var Role $role */
     $role = $roleCollection->setUserFilter($userId, $userType)->getFirstItem();
     if (!$role->getId()) {
         return null;
     }
     return $role->getId();
 }
 /**
  * {@inheritdoc}
  */
 public function getByIdentifierNamespace($identifier, $namespace)
 {
     $this->searchCriteriaBuilder->addFilters([$this->filterBuilder->setField('user_id')->setConditionType('eq')->setValue($this->userContext->getUserId())->create(), $this->filterBuilder->setField('identifier')->setConditionType('eq')->setValue($identifier)->create(), $this->filterBuilder->setField('namespace')->setConditionType('eq')->setValue($namespace)->create()]);
     $searchCriteria = $this->searchCriteriaBuilder->create();
     $searchResults = $this->bookmarkRepository->getList($searchCriteria);
     if ($searchResults->getTotalCount() > 0) {
         foreach ($searchResults->getItems() as $searchResult) {
             $bookmark = $this->bookmarkRepository->getById($searchResult->getId());
             return $bookmark;
         }
     }
     return null;
 }
 /**
  * Override parameter values based on webapi.xml
  *
  * @param array $inputData Incoming data from request
  * @param array $parameters Contains parameters to replace or default
  * @return array Data in same format as $inputData with appropriate parameters added or changed
  */
 public function override(array $inputData, array $parameters)
 {
     foreach ($parameters as $name => $paramData) {
         $arrayKeys = explode('.', $name);
         if ($paramData[Converter::KEY_FORCE] || !$this->isNestedArrayValueSet($inputData, $arrayKeys)) {
             if ($paramData[Converter::KEY_VALUE] == '%customer_id%' && $this->userContext->getUserType() === UserContextInterface::USER_TYPE_CUSTOMER) {
                 $value = $this->userContext->getUserId();
             } else {
                 $value = $paramData[Converter::KEY_VALUE];
             }
             $this->setNestedArrayValue($inputData, $arrayKeys, $value);
         }
     }
     return $inputData;
 }
Esempio n. 7
0
 protected function setUp()
 {
     $this->_objectManager = new \Magento\TestFramework\Helper\ObjectManager($this);
     $userId = 'userId';
     $userType = 'userType';
     $this->userContext = $this->getMockBuilder('Magento\\Authorization\\Model\\CompositeUserContext')->disableOriginalConstructor()->setMethods(['getUserId', 'getUserType'])->getMock();
     $this->userContext->expects($this->once())->method('getUserId')->will($this->returnValue($userId));
     $this->userContext->expects($this->once())->method('getUserType')->will($this->returnValue($userType));
     $this->roleCollectionFactory = $this->getMockBuilder('Magento\\Authorization\\Model\\Resource\\Role\\CollectionFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock();
     $this->roleCollection = $this->getMockBuilder('Magento\\Authorization\\Model\\Resource\\Role\\Collection')->disableOriginalConstructor()->setMethods(['setUserFilter', 'getFirstItem'])->getMock();
     $this->roleCollectionFactory->expects($this->once())->method('create')->will($this->returnValue($this->roleCollection));
     $this->roleCollection->expects($this->once())->method('setUserFilter')->with($userId, $userType)->will($this->returnValue($this->roleCollection));
     $this->role = $this->getMockBuilder('Magento\\Authorization\\Model\\Role')->disableOriginalConstructor()->setMethods(['getId', '__wakeup'])->getMock();
     $this->roleCollection->expects($this->once())->method('getFirstItem')->will($this->returnValue($this->role));
     $this->locator = $this->_objectManager->getObject('Magento\\Webapi\\Model\\WebapiRoleLocator', ['userContext' => $this->userContext, 'roleCollectionFactory' => $this->roleCollectionFactory]);
 }
 /**
  * {@inheritDoc}
  */
 public function getOverriddenValue()
 {
     try {
         if ($this->userContext->getUserType() === UserContextInterface::USER_TYPE_CUSTOMER) {
             $customerId = $this->userContext->getUserId();
             /** @var \Magento\Quote\Api\Data\CartInterface */
             $cart = $this->cartManagement->getCartForCustomer($customerId);
             if ($cart) {
                 return $cart->getId();
             }
         }
     } catch (NoSuchEntityException $e) {
         /* do nothing and just return null */
     }
     return null;
 }
 /**
  * Check if access to the specified resources is prohibited to the user.
  *
  * @param int $integrationId
  * @param string[] $resources
  */
 protected function _ensurePermissionsAreNotGranted($integrationId, $resources)
 {
     $this->userContextMock->expects($this->any())->method('getUserId')->will($this->returnValue($integrationId));
     foreach ($resources as $resource) {
         $this->assertFalse($this->libAuthorization->isAllowed($resource), "Access to resource '{$resource}' is expected to be prohibited.");
     }
 }
Esempio n. 10
0
 /**
  * Update bookmarks based on request params
  *
  * @param BookmarkInterface $bookmark
  * @param string $identifier
  * @param string $title
  * @param string $config
  * @return void
  */
 protected function updateBookmark(BookmarkInterface $bookmark, $identifier, $title, $config)
 {
     $updateBookmark = $this->checkBookmark($identifier);
     if ($updateBookmark !== false) {
         $bookmark = $updateBookmark;
     }
     $bookmark->setUserId($this->userContext->getUserId())->setNamespace($this->_request->getParam('namespace'))->setIdentifier($identifier)->setTitle($title)->setConfig($config);
     $this->bookmarkRepository->save($bookmark);
 }
Esempio n. 11
0
 /**
  * @param array $requestData Data from the request
  * @param array $parameters Data from config about which parameters to override
  * @param array $expectedOverriddenParams Result of overriding $requestData when applying rules from $parameters
  * @param int $userId The id of the user invoking the request
  * @param int $userType The type of user invoking the request
  *
  * @dataProvider overrideParmasDataProvider
  */
 public function testOverrideParams($requestData, $parameters, $expectedOverriddenParams, $userId, $userType)
 {
     $this->_routeMock->expects($this->once())->method('getParameters')->will($this->returnValue($parameters));
     $this->_routeMock->expects($this->any())->method('getAclResources')->will($this->returnValue(['1']));
     $this->_authorizationMock->expects($this->once())->method('isAllowed')->will($this->returnValue(true));
     $this->_requestMock->expects($this->any())->method('getRequestData')->will($this->returnValue($requestData));
     $this->userContextMock->expects($this->any())->method('getUserId')->will($this->returnValue($userId));
     $this->userContextMock->expects($this->any())->method('getUserType')->will($this->returnValue($userType));
     // serializer should expect overridden params
     $this->serializerMock->expects($this->once())->method('getInputData')->with($this->equalTo('Magento\\Webapi\\Controller\\TestService'), $this->equalTo('testMethod'), $this->equalTo($expectedOverriddenParams));
     $this->_restController->dispatch($this->_requestMock);
 }
Esempio n. 12
0
 /**
  * Update bookmarks based on request params
  *
  * @param BookmarkInterface $bookmark
  * @param string $identifier
  * @param string $title
  * @param array $config
  * @return void
  */
 protected function updateBookmark(BookmarkInterface $bookmark, $identifier, $title, array $config = [])
 {
     $this->filterVars($config);
     $bookmark->setUserId($this->userContext->getUserId())->setNamespace($this->_request->getParam('namespace'))->setIdentifier($identifier)->setTitle($title)->setConfig($config)->setCurrent($identifier !== self::CURRENT_IDENTIFIER);
     $this->bookmarkRepository->save($bookmark);
     $bookmarks = $this->bookmarkManagement->loadByNamespace($this->_request->getParam('namespace'));
     foreach ($bookmarks->getItems() as $bookmark) {
         if ($bookmark->getIdentifier() == $identifier) {
             continue;
         }
         $bookmark->setCurrent(false);
         $this->bookmarkRepository->save($bookmark);
     }
 }
Esempio n. 13
0
 /**
  * Override parameter values based on webapi.xml
  *
  * @param array $inputData Incoming data from request
  * @param array $parameters Contains parameters to replace or default
  * @return array Data in same format as $inputData with appropriate parameters added or changed
  */
 protected function overrideParams(array $inputData, array $parameters)
 {
     foreach ($parameters as $name => $paramData) {
         if ($paramData[Converter::KEY_FORCE] || !isset($inputData[$name])) {
             if ($paramData[Converter::KEY_VALUE] == '%customer_id%' && $this->userContext->getUserType() === UserContextInterface::USER_TYPE_CUSTOMER) {
                 $value = $this->userContext->getUserId();
             } else {
                 $value = $paramData[Converter::KEY_VALUE];
             }
             $inputData[$name] = $value;
         }
     }
     return $inputData;
 }
Esempio n. 14
0
 /**
  * Creates a cart for the currently logged-in customer.
  *
  * @param int $storeId
  * @return \Magento\Quote\Model\Quote Cart object.
  * @throws CouldNotSaveException The cart could not be created.
  */
 protected function createCustomerCart($storeId)
 {
     $customer = $this->customerRepository->getById($this->userContext->getUserId());
     try {
         $this->quoteRepository->getActiveForCustomer($this->userContext->getUserId());
         throw new CouldNotSaveException(__('Cannot create quote'));
     } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
     }
     /** @var \Magento\Quote\Model\Quote $quote */
     $quote = $this->quoteRepository->create();
     $quote->setStoreId($storeId);
     $quote->setCustomer($customer);
     $quote->setCustomerIsGuest(0);
     return $quote;
 }
Esempio n. 15
0
 /**
  * Create cart for current logged in customer
  *
  * @return \Magento\Sales\Model\Quote
  * @throws CouldNotSaveException
  */
 protected function createCustomerCart()
 {
     $storeId = $this->storeManager->getStore()->getId();
     $customer = $this->customerRegistry->retrieve($this->userContext->getUserId());
     $currentCustomerQuote = $this->quoteFactory->create()->loadByCustomer($customer);
     if ($currentCustomerQuote->getId() && $currentCustomerQuote->getIsActive()) {
         throw new CouldNotSaveException('Cannot create quote');
     }
     /** @var \Magento\Sales\Model\Quote $quote */
     $quote = $this->quoteFactory->create();
     $quote->setStoreId($storeId);
     $quote->setCustomer($customer);
     $quote->setCustomerIsGuest(0);
     return $quote;
 }
Esempio n. 16
0
 /**
  * @param \Magento\Quote\Model\GuestCart\GuestCartManagement $subject
  * @param string $cartId
  * @param int $customerId
  * @param int $storeId
  * @throws StateException
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function beforeAssignCustomer(\Magento\Quote\Model\GuestCart\GuestCartManagement $subject, $cartId, $customerId, $storeId)
 {
     if ($customerId !== (int) $this->userContext->getUserId()) {
         throw new StateException(__('Cannot assign customer to the given cart. You don\'t have permission for this operation.'));
     }
 }
Esempio n. 17
0
 /**
  * Check whether access is allowed for create cart resource
  *
  * @param \Magento\Checkout\Service\V1\Cart\WriteServiceInterface $subject
  * @param int $cartId
  * @param int $customerId
  *
  * @return void
  * @throws AuthorizationException if access denied
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function beforeAssignCustomer(\Magento\Checkout\Service\V1\Cart\WriteServiceInterface $subject, $cartId, $customerId)
 {
     if (!in_array($this->userContext->getUserType(), $this->allowedUserTypes)) {
         throw new AuthorizationException('Access denied');
     }
 }
 public function testGetOverriddenValueIsNotCustomer()
 {
     $this->userContext->expects($this->once())->method('getUserType')->will($this->returnValue(UserContextInterface::USER_TYPE_ADMIN));
     $this->assertNull($this->model->getOverriddenValue());
 }
 /**
  * Check whether access is allowed for create cart resource
  *
  * @param \Magento\Quote\Api\CartManagementInterface $subject
  * @param int $cartId
  * @param int $customerId
  * @param int $storeId
  *
  * @return void
  * @throws AuthorizationException if access denied
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function beforeAssignCustomer(\Magento\Quote\Api\CartManagementInterface $subject, $cartId, $customerId, $storeId)
 {
     if (!in_array($this->userContext->getUserType(), $this->allowedUserTypes)) {
         throw new AuthorizationException(__('Access denied'));
     }
 }
 /**
  * Check whether access is allowed for cart list resource
  *
  * @param \Magento\Quote\Api\CartRepositoryInterface $subject
  * @param SearchCriteria $searchCriteria
  *
  * @return void
  * @throws AuthorizationException if access denied
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function beforeGetList(\Magento\Quote\Api\CartRepositoryInterface $subject, SearchCriteria $searchCriteria)
 {
     if (!in_array($this->userContext->getUserType(), $this->allowedUserTypes)) {
         throw new AuthorizationException(__('Access denied'));
     }
 }
Esempio n. 21
0
 /**
  * Check whether access is allowed for cart list resource
  *
  * @param \Magento\Checkout\Service\V1\Cart\ReadServiceInterface $subject
  * @param SearchCriteria $searchCriteria
  *
  * @return void
  * @throws AuthorizationException if access denied
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function beforeGetCartList(\Magento\Checkout\Service\V1\Cart\ReadServiceInterface $subject, SearchCriteria $searchCriteria)
 {
     if (!in_array($this->userContext->getUserType(), $this->allowedUserTypes)) {
         throw new AuthorizationException('Access denied');
     }
 }
Esempio n. 22
0
 /**
  * Generate cache ID using current context: user permissions and store
  *
  * @param string $prefix Prefix is used by hashing function
  * @return string
  */
 public function generateCacheIdUsingContext($prefix)
 {
     return hash('md5', $prefix . $this->storeManager->getStore()->getCode() . $this->userContext->getUserType() . $this->userContext->getUserId());
 }
Esempio n. 23
0
 /**
  * Checks if order is allowed for current customer
  *
  * @param \Magento\Sales\Model\Order $order
  * @return bool
  */
 protected function isAllowed(\Magento\Sales\Model\Order $order)
 {
     return $this->userContext->getUserType() == UserContextInterface::USER_TYPE_CUSTOMER ? $order->getCustomerId() == $this->userContext->getUserId() : true;
 }
Esempio n. 24
0
 /**
  * Check whether quote is allowed for current user context
  *
  * @param \Magento\Quote\Model\Quote $quote
  * @return bool
  */
 protected function isAllowed(\Magento\Quote\Model\Quote $quote)
 {
     return $this->userContext->getUserType() == UserContextInterface::USER_TYPE_CUSTOMER ? $quote->getCustomerId() === null || $quote->getCustomerId() == $this->userContext->getUserId() : true;
 }