public function save(Mage_Admin_Model_User $user) { $this->_write->beginTransaction(); try { $data = array('firstname' => $user->getFirstname(), 'lastname' => $user->getLastname(), 'email' => $user->getEmail(), 'username' => $user->getUsername(), 'modified' => now()); if (!is_null($user->getReloadAclFlag())) { $data['reload_acl_flag'] = $user->getReloadAclFlag(); } if ($user->getPassword()) { $data['password'] = $this->_encryptPassword($user->getPassword()); } if ($user->getId()) { $condition = $this->_write->quoteInto('user_id=?', $user->getId()); $this->_write->update($this->_userTable, $data, $condition); } else { $data['created'] = now(); $this->_write->insert($this->_userTable, $data); $user->setUserId($this->_write->lastInsertId()); } $this->_write->commit(); } catch (Exception $e) { $this->_write->rollback(); throw $e; } return $user; }
/** * Ensure that an exception is not thrown, if the user does not exist */ public function testLoadByUsername() { $this->_model->loadByUsername('non_existing_user'); $this->assertNull($this->_model->getId(), 'The admin user has an unexpected ID'); //$this->_model->loadByUsername(Magento_Test_Bootstrap::ADMIN_NAME); $this->_model->loadByUsername(''); $this->assertNotEmpty($this->_model->getId(), 'The admin user should have been loaded'); }
/** * @param Mage_Admin_Model_User $user * * @return $this */ public function addAdminUserFilter($user) { $this->getSelect()->joinLeft(array('dep_perm' => $this->getTable('aw_hdu3/department_permission')), 'main_table.department_id = dep_perm.department_id', array()); /** * @var $agent AW_Helpdesk3_Model_Department_Agent */ $agent = Mage::getModel('aw_hdu3/department_agent')->loadAgentByUserId($user->getId()); $agentFullDepartmentCollection = $agent->getFullDepartmentCollection(); $agentFullDepartmentIds = $agentFullDepartmentCollection->getAllIds(); $mainTableDepartmentSql = '1=0'; if (!empty($agentFullDepartmentIds)) { $mainTableDepartmentSql = 'FIND_IN_SET(main_table.department_id, \'' . join(',', $agentFullDepartmentCollection->getAllIds()) . '\')'; } $agentDepartmentCollection = $agent->getDepartmentCollection(); $departmentIdConditionList = array(); foreach ($agentDepartmentCollection->getAllIds() as $departmentId) { $departmentIdConditionList[] = 'FIND_IN_SET(' . $departmentId . ', department_ids)'; } $departmentIdSql = '1=0'; if (count($departmentIdConditionList)) { $departmentIdSql = join(' OR ', $departmentIdConditionList); } $adminRoleIdSql = 'FIND_IN_SET(' . $user->getRole()->getId() . ', admin_role_ids)'; $whereSql = '(' . $mainTableDepartmentSql . ' OR ' . $departmentIdSql . ' OR ' . $adminRoleIdSql . ')'; $this->getSelect()->where($whereSql); return $this; }
/** * Retrieve all groups tah has been assigned to user * * @param Mage_Admin_Model_User $user * @return array */ public function getGroupsByUser(Mage_Admin_Model_User $user) { $connection = $this->getResource()->getReadConnection(); $select = $connection->select()->from($this->_groupUserTable, array('group_id'))->where('user_id = :user_id'); $bind = array('user_id' => (int) $user->getId()); return $connection->fetchAssoc($select, $bind); }
/** * Loads role rules into ACL for admin user * * @param Mage_Admin_Model_User $user * @param Mage_Admin_Model_Acl $acl * @param array $allowedResources * * @return $this */ public function loadRules(Mage_Admin_Model_User $user, Mage_Admin_Model_Acl $acl, array $allowedResources = array()) { $userRole = Mage::getModel('admin/acl_role_user', Mage_Admin_Model_Acl::ROLE_TYPE_USER . $user->getId()); $acl->addRole($userRole); if (empty($allowedResources)) { $acl->allow($userRole); $acl->allow($userRole, $acl->getResources()); return $this; } $aclResources = $acl->getResources(); $allow = array(); foreach ($allowedResources as $resource) { $childResources = array_filter($aclResources, function ($entry) use($resource) { return strpos($entry, 'admin/' . $resource) === 0; }); $allow = array_merge($allow, $childResources); } $deny = array(); foreach ($aclResources as $resource) { if (!in_array($resource, $allow)) { $deny[] = $resource; } } $acl->allow($userRole, $allow); $acl->deny($userRole, $deny); return $this; }
/** * Validate the CSR user to ensure it is active and has a role assigned. * * @param Mage_Admin_Model_User $user * @throws EbayEnterprise_Eb2cCustomerService_Exception_Authentication * @return self */ protected function _validateUser(Mage_Admin_Model_User $user) { if (!$user->getIsActive()) { throw new EbayEnterprise_Eb2cCustomerService_Exception_Authentication('This account is inactive.'); } if (!$user->hasAssigned2Role($user->getId())) { throw new EbayEnterprise_Eb2cCustomerService_Exception_Authentication('Access denied.'); } return $this; }
/** * Save the login history item for the given user * * @param Mage_Admin_Model_User $user User * @param string $message Message * @throws Exception */ protected function _saveLoginHistory($user, $failure = false, $message = '') { /* @var $history FireGento_AdminMonitoring_Model_History */ $history = Mage::getModel('firegento_adminmonitoring/history'); $history->setForcedLogging(true); $history->setData(array('object_id' => $user->getId(), 'object_type' => get_class($user), 'user_agent' => $this->getUserAgent(), 'ip' => $this->getRemoteAddr(), 'user_id' => $user->getId(), 'user_name' => $user->getUsername(), 'action' => FireGento_AdminMonitoring_Helper_Data::ACTION_LOGIN, 'created_at' => now())); // Add some error information when login failed if ($failure) { $history->setData('status', FireGento_AdminMonitoring_Helper_Data::STATUS_FAILURE); $history->setData('history_message', $message); } $history->save(); }
/** * @param Mage_Admin_Model_User $user * * @return bool */ public function isCanViewTicket($user) { $agent = Mage::getModel('aw_hdu3/department_agent')->loadAgentByUserId($user->getId()); $agentDepartmentCollection = $agent->getDepartmentCollection(); $departmentIds = $agentDepartmentCollection->getAllIds(); //check department foreach ($departmentIds as $depId) { if (in_array($depId, $this->getDepartmentIds())) { return true; } } //check admin role if (in_array($user->getRole()->getId(), $this->getAdminRoleIds())) { return true; } return false; }
/** * Remember a password hash for further usage * * @param Mage_Admin_Model_User $user * @param string $passwordHash * @param int $lifetime */ public function trackPassword($user, $passwordHash, $lifetime) { $now = time(); $this->_getWriteAdapter()->insert($this->getTable('enterprise_pci/admin_passwords'), array('user_id' => $user->getId(), 'password_hash' => $passwordHash, 'expires' => $now + $lifetime, 'last_updated' => $now)); }
/** * Add a user to a group. * * @param Mage_Admin_Model_Role $role * @param Mage_Admin_Model_Role $parentRole * @param Mage_Admin_Model_User $user */ public function createUserRole(Mage_Admin_Model_Role $role, Mage_Admin_Model_Role $parentRole, Mage_Admin_Model_User $user) { return $role->setRoleName($parentRole->getRoleName())->setUserId($user->getId())->setRoleType(self::TYPE_USER)->setTreeLevel(self::TREE_LEVEL_USER)->setParentId($parentRole->getId())->save(); }
/** * @param string $text * @param Mage_Customer_Model_Customer|Varien_Object|false $customer * @param Mage_Admin_Model_User|false $user * @param string $triggeredBy * @param string $messageType * @param bool|Mirasvit_Helpdesk_Model_Email $email * @param bool|string $bodyFormat * * @return Mirasvit_Helpdesk_Model_Message * * @throws Exception */ public function addMessage($text, $customer, $user, $triggeredBy, $messageType = Mirasvit_Helpdesk_Model_Config::MESSAGE_PUBLIC, $email = false, $bodyFormat = false) { $message = Mage::getModel('helpdesk/message')->setTicketId($this->getId())->setType($messageType)->setBody($text)->setBodyFormat($bodyFormat)->setTriggeredBy($triggeredBy); if ($triggeredBy == Mirasvit_Helpdesk_Model_Config::CUSTOMER) { $message->setCustomerId($customer->getId()); $message->setCustomerName($customer->getName()); $message->setCustomerEmail($customer->getEmail()); $message->setIsRead(true); $this->setLastReplyName($customer->getName()); } elseif ($triggeredBy == Mirasvit_Helpdesk_Model_Config::USER) { $message->setUserId($user->getId()); if ($this->getOrigData('user_id') == $this->getData('user_id')) { if ($messageType != Mirasvit_Helpdesk_Model_Config::MESSAGE_INTERNAL) { $this->setUserId($user->getId()); // In case of different departments of ticket and owner, correct department id $departments = Mage::getModel('helpdesk/department')->getCollection(); $departments->addUserFilter($user->getId())->addFieldToFilter('is_active', true); if ($departments->count()) { $this->_department = null; $this->setDepartmentId($departments->getFirstItem()->getId()); } } } $this->setLastReplyName($user->getName()); if ($message->isThirdParty()) { $message->setThirdPartyEmail($this->getThirdPartyEmail()); } } elseif ($triggeredBy == Mirasvit_Helpdesk_Model_Config::THIRD) { $message->setThirdPartyEmail($this->getThirdPartyEmail()); if ($email) { $this->setLastReplyName($email->getSenderNameOrEmail()); $message->setThirdPartyName($email->getSenderName()); } } if ($email) { $message->setEmailId($email->getId()); } //если тикет был закрыт, затем поступило сообщение от пользователя - мы его открываем if ($triggeredBy != Mirasvit_Helpdesk_Model_Config::USER) { if ($this->isClosed()) { $status = Mage::getModel('helpdesk/status')->loadByCode(Mirasvit_Helpdesk_Model_Config::STATUS_OPEN); $this->setStatusId($status->getId()); } $this->setIsArchived(false); } $message->save(); if ($email) { $email->setIsProcessed(true)->setAttachmentMessageId($message->getId())->save(); } else { Mage::helper('helpdesk')->saveAttachments($message); } if (!$this->getIsSpam()) { if ($this->getReplyCnt() == 0) { Mage::helper('helpdesk/notification')->newTicket($this, $customer, $user, $triggeredBy, $messageType); } else { Mage::helper('helpdesk/notification')->newMessage($this, $customer, $user, $triggeredBy, $messageType); } } $this->setReplyCnt($this->getReplyCnt() + 1); if (!$this->getFirstReplyAt() && $user) { $this->setFirstReplyAt(Mage::getSingleton('core/date')->gmtDate()); } $this->setLastReplyAt(Mage::getSingleton('core/date')->gmtDate()); $this->save(); Mage::helper('helpdesk/history')->addMessage($this, $text, $triggeredBy, array('customer' => $customer, 'user' => $user, 'email' => $email), $messageType); return $message; }
/** * Given a admin user, return a option map with the username as the label * and user id as the value. * @param Mage_Admin_Model_User $user * @return array * @SuppressWarnings(PHPMD.UnusedPrivateMethod) */ private function _userMap(Mage_Admin_Model_User $user) { return array('label' => $user->getUsername(), 'value' => $user->getId()); }
/** * @param Mage_Admin_Model_User $user * * @return Bronto_Common_Model_Email_Template_Filter */ protected function _filterAdmin(Mage_Admin_Model_User $user) { if (!in_array('admin', $this->_filteredObjects)) { $this->setField('adminName', $user->getUsername()); $this->setField('adminPassword', $user->getPlainPassword()); $this->setField('adminLoginURL', Mage::helper('adminhtml')->getUrl('adminhtml/system_account/')); if (Mage::helper('bronto_common')->isVersionMatch(Mage::getVersionInfo(), 1, array(array('>=', '6')))) { $this->setField('adminPasswordResetLink', Mage::helper('adminhtml')->getUrl('adminhtml/index/resetpassword', array('_query' => array('id' => $user->getId(), 'token' => $user->getRpToken())))); } $this->_filteredObjects[] = 'admin'; } return $this; }
/** * Assign an admin user to a api2 role (create the role if it's missing) * * NOTE: this role allows you to view the catalog. This is defined by the 'resource' role parameter below. * * @param Mage_Admin_Model_User $adminUser */ public function assignAdminUserToApi2Role($adminUser) { $roleData = array('in_role_users' => array($adminUser->getId()), 'role_name' => self::API2_ROLE_NAME, 'resource' => '__root__,group-catalog,resource-styla_category,privilege-styla_category-retrieve,resource-styla_product,privilege-styla_product-retrieve', 'all' => '0'); //a little trick - mage implementation needs these params to be in POST.... foreach ($roleData as $key => $value) { Mage::app()->getRequest()->setPost($key, $value); } $role = Mage::getModel('api2/acl_global_role'); $roles = $role->getCollection()->addFieldToFilter('role_name', $roleData['role_name']); $existingRole = $roles->getFirstItem(); if ($existingRole->getId()) { $role = $existingRole; } else { //create the new role $role->setRoleName($roleData['role_name'])->save(); } foreach ($roleData['in_role_users'] as $roleUser) { $this->_addUserToRole($roleUser, $role->getId()); } /** @var $rule Mage_Api2_Model_Acl_Global_Rule */ $rule = Mage::getModel('api2/acl_global_rule'); //save API2 access rules /** @var $ruleTree Mage_Api2_Model_Acl_Global_Rule_Tree */ $ruleTree = Mage::getSingleton('api2/acl_global_rule_tree', array('type' => Mage_Api2_Model_Acl_Global_Rule_Tree::TYPE_PRIVILEGE)); $resources = $ruleTree->getPostResources(); $id = $role->getId(); foreach ($resources as $resourceId => $privileges) { foreach ($privileges as $privilege => $allow) { if (!$allow) { continue; } $rule->setId(null)->isObjectNew(true); $rule->setRoleId($id)->setResourceId($resourceId)->setPrivilege($privilege)->save(); } } }
/** * Invoke Latch lib for unpair admin account with Latch * * @param Mage_Admin_Model_User $user * @return array */ public function unpairAdmin($user = null) { $appId = $this->getApplicationId(); $appSecret = $this->getSecretKey(); $apiUrl = $this->getApiUrl(); if (!empty($appId) && !empty($appSecret)) { require_once Mage::getBaseDir('lib') . '/Latch/latch.php'; if ($apiUrl) { $api = new Latch($appId, $appSecret, $apiUrl); } else { $api = new Latch($appId, $appSecret); } $latchId = Mage::getModel('admin/user')->load($user->getId())->getData('latch_id'); $apiResponse = $api->unpair($latchId); if ($latchId) { if ($apiResponse->getError() == NULL) { $user->setData('latch_id', ''); $mustSave = Mage::getSingleton('core/session')->getAdminMustSave(); if ($mustSave) { $user->save(); } return array("status" => 1, "message" => $this->__("The account was unlinked with Latch successfully.")); } else { return array("status" => 0, "message" => $this->__("Couldn't unlink the account with Latch: ") . $this->__($apiResponse->getError()->getMessage())); } } else { return array("status" => 0, "message" => $this->__("There is no Latch Id to unlink.")); } } else { return array("status" => 0, "message" => $this->__("The account wasn't unlinked with Latch. Please try again later.")); } }
/** * Check is user logged in and permissions * * @param Mage_Admin_Model_User|null $user * @return bool */ protected function _checkUserAccess($user = null) { if ($user && !$user->getId()) { $this->addMessage('error', 'Invalid user name or password'); $this->controller()->setAction('login'); } elseif ($this->getUserId() || $user && $user->getId()) { if ($this->_session->isAllowed('all')) { return true; } else { $this->logout(); $this->addMessage('error', 'Access Denied', true); $this->controller()->setAction('login'); } } return false; }
/** * @param Mage_Admin_Model_User $user * * @return bool */ public function agentCanViewTicket($user) { $ticketDepartmentAgentIds = $this->getDepartment()->getAgentCollection()->getAllIds(); $agent = Mage::getModel('aw_hdu3/department_agent')->loadAgentByUserId($user->getId()); if ($agent && in_array($agent->getId(), $ticketDepartmentAgentIds)) { return true; } return false; }