Пример #1
0
 public function save()
 {
     $this->hash = CryptoTool::sault(12);
     $this->scriptType = empty($this->scriptId) ? 'local' : 'scalr';
     if (!isset($this->orderIndex)) {
         $this->orderIndex = 10;
     }
     if (!isset($this->issync)) {
         $this->issync = 0;
     }
     parent::save();
 }
Пример #2
0
 public function xCreateAction()
 {
     $this->request->defineParams(array('listeners' => array('type' => 'json'), 'healthcheck' => array('type' => 'json'), 'zones' => array('type' => 'array'), 'subnets' => array('type' => 'array'), 'scheme' => array('type' => 'string')));
     $healthCheck = $this->getParam('healthcheck');
     $elb = $this->environment->aws($this->getParam('cloudLocation'))->elb;
     //prepare listeners
     $listenersList = new ListenerList();
     $li = 0;
     foreach ($this->getParam('listeners') as $listener) {
         $listener_chunks = explode("#", $listener);
         $listenersList->append(new ListenerData(trim($listener_chunks[1]), trim($listener_chunks[2]), trim($listener_chunks[0]), null, trim($listener_chunks[3])));
     }
     $availZones = $this->getParam('zones');
     $subnets = $this->getParam('subnets');
     $scheme = $this->getParam('scheme');
     $elb_name = sprintf("scalr-%s-%s", CryptoTool::sault(10), rand(100, 999));
     $healthCheckType = new HealthCheckData();
     $healthCheckType->target = $healthCheck['target'];
     $healthCheckType->healthyThreshold = $healthCheck['healthyThreshold'];
     $healthCheckType->interval = $healthCheck['interval'];
     $healthCheckType->timeout = $healthCheck['timeout'];
     $healthCheckType->unhealthyThreshold = $healthCheck['unhealthyThreshold'];
     //Creates a new ELB
     $dnsName = $elb->loadBalancer->create($elb_name, $listenersList, !empty($availZones) ? $availZones : null, !empty($subnets) ? $subnets : null, null, !empty($scheme) ? $scheme : null);
     $tags = [['key' => \Scalr_Governance::SCALR_META_TAG_NAME, 'value' => $this->environment->applyGlobalVarsToValue(\Scalr_Governance::SCALR_META_TAG_VALUE)]];
     //Tags governance
     $governance = new \Scalr_Governance($this->environment->id);
     $gTags = (array) $governance->getValue('ec2', \Scalr_Governance::AWS_TAGS);
     if (count($gTags) > 0) {
         foreach ($gTags as $tKey => $tValue) {
             $tags[] = array('key' => $tKey, 'value' => $this->environment->applyGlobalVarsToValue($tValue));
         }
     }
     $elb->loadBalancer->addTags($elb_name, $tags);
     try {
         $elb->loadBalancer->configureHealthCheck($elb_name, $healthCheckType);
     } catch (Exception $e) {
         $elb->loadBalancer->delete($elb_name);
         throw $e;
     }
     // return all as in xListElb
     $this->response->data(array('elb' => array('name' => $elb_name, 'dnsName' => $dnsName)));
 }
Пример #3
0
 public function xSaveAction()
 {
     $user = Scalr_Account_User::init();
     $validator = new Scalr_Validator();
     if (!$this->getParam('email')) {
         throw new Scalr_Exception_Core('Email must be provided.');
     }
     if ($validator->validateEmail($this->getParam('email'), null, true) !== true) {
         throw new Scalr_Exception_Core('Email should be correct');
     }
     if ($this->user->canManageAcl() || $this->user->isTeamOwner()) {
         $newUser = false;
         if ($this->getParam('id')) {
             $user->loadById((int) $this->getParam('id'));
             if (!$this->user->canEditUser($user)) {
                 throw new Scalr_Exception_InsufficientPermissions();
             }
             $user->updateEmail($this->getParam('email'));
         } else {
             $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_USERS, 1);
             $user->create($this->getParam('email'), $this->user->getAccountId());
             $user->type = Scalr_Account_User::TYPE_TEAM_USER;
             $newUser = true;
         }
         $sendResetLink = false;
         if (!$this->getParam('password')) {
             $password = CryptoTool::sault(10);
             $sendResetLink = true;
         } else {
             $password = $this->getParam('password');
         }
         if ($password != '******') {
             $user->updatePassword($password);
         }
         if (in_array($this->getParam('status'), array(Scalr_Account_User::STATUS_ACTIVE, Scalr_Account_User::STATUS_INACTIVE)) && !$user->isAccountOwner()) {
             $user->status = $this->getParam('status');
         }
         $user->fullname = $this->getParam('fullname');
         $user->comments = $this->getParam('comments');
         $user->save();
         if ($this->getParam('enableApi')) {
             $keys = Scalr::GenerateAPIKeys();
             $user->setSetting(Scalr_Account_User::SETTING_API_ENABLED, true);
             $user->setSetting(Scalr_Account_User::SETTING_API_ACCESS_KEY, $keys['id']);
             $user->setSetting(Scalr_Account_User::SETTING_API_SECRET_KEY, $keys['key']);
         }
         if ($newUser) {
             if ($sendResetLink) {
                 try {
                     $hash = $this->getCrypto()->sault(10);
                     $user->setSetting(Scalr_Account::SETTING_OWNER_PWD_RESET_HASH, $hash);
                     $clientinfo = array('email' => $user->getEmail(), 'fullname' => $user->fullname);
                     // Send reset password E-mail
                     $res = $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/user_account_confirm.eml', array("{{fullname}}" => $clientinfo['fullname'], "{{pwd_link}}" => "https://{$_SERVER['HTTP_HOST']}/#/guest/updatePassword/?hash={$hash}"), $clientinfo['email'], $clientinfo['fullname']);
                 } catch (Exception $e) {
                 }
             }
         }
         $this->response->data(array('user' => array('id' => $user->getId(), 'email' => $user->getEmail(), 'fullname' => $user->fullname)));
         $this->response->success('User successfully saved');
     } else {
         throw new Scalr_Exception_InsufficientPermissions();
     }
 }
Пример #4
0
 /**
  * Set scripts of the Role
  * TODO refactor this method to new Entities
  *
  * @param   array   $scripts
  */
 public function setScripts($scripts)
 {
     if (!$this->id) {
         return;
     }
     if (!is_array($scripts)) {
         return;
     }
     $ids = array();
     foreach ($scripts as $script) {
         // TODO: check permission for script_id
         if (!$script['role_script_id']) {
             $this->db()->Execute('INSERT INTO role_scripts SET
                 `role_id` = ?,
                 `event_name` = ?,
                 `target` = ?,
                 `script_id` = ?,
                 `version` = ?,
                 `timeout` = ?,
                 `issync` = ?,
                 `params` = ?,
                 `order_index` = ?,
                 `hash` = ?,
                 `script_path` = ?,
                 `run_as` = ?,
                 `script_type` = ?
             ', array($this->id, $script['event_name'], $script['target'], $script['script_id'] != 0 ? $script['script_id'] : NULL, $script['version'], $script['timeout'], $script['isSync'], serialize($script['params']), $script['order_index'], !$script['hash'] ? CryptoTool::sault(12) : $script['hash'], $script['script_path'], $script['run_as'], $script['script_type']));
             $ids[] = $this->db()->Insert_ID();
         } else {
             $this->db()->Execute('UPDATE role_scripts SET
                 `event_name` = ?,
                 `target` = ?,
                 `script_id` = ?,
                 `version` = ?,
                 `timeout` = ?,
                 `issync` = ?,
                 `params` = ?,
                 `order_index` = ?,
                 `script_path` = ?,
                 `run_as` = ?,
                 `script_type` = ?
                 WHERE id = ? AND role_id = ?
             ', array($script['event_name'], $script['target'], $script['script_id'] != 0 ? $script['script_id'] : NULL, $script['version'], $script['timeout'], $script['isSync'], serialize($script['params']), $script['order_index'], $script['script_path'], $script['run_as'], $script['script_type'], $script['role_script_id'], $this->id));
             $ids[] = $script['role_script_id'];
         }
     }
     $toRemove = $this->db()->Execute('SELECT id, hash FROM role_scripts WHERE role_id = ? AND id NOT IN (\'' . implode("','", $ids) . '\')', array($this->id));
     while ($rScript = $toRemove->FetchRow()) {
         $this->db()->Execute("DELETE FROM farm_role_scripting_params WHERE hash = ? AND farm_role_id IN (SELECT id FROM farm_roles WHERE role_id = ?)", array($rScript['hash'], $this->id));
         $this->db()->Execute("DELETE FROM role_scripts WHERE id = ?", array($rScript['id']));
     }
 }
Пример #5
0
 /**
  * Return account's hash. It's used for reseting keepSession on a whole account
  *
  * @param   int     $userId
  * @return  string
  */
 protected static function getAccountHash($userId)
 {
     $db = \Scalr::getDb();
     $hash = $db->GetOne("\n            SELECT `value`\n            FROM client_settings\n            JOIN account_users ON account_users.account_id = client_settings.clientid\n            WHERE `key` = ? AND account_users.id = ?\n            LIMIT 1\n        ", array(Scalr_Account::SETTING_AUTH_HASH, $userId));
     if (!$hash) {
         $accountId = $db->GetOne('SELECT account_id FROM account_users WHERE id = ? LIMIT 1', array($userId));
         if ($accountId) {
             $hash = CryptoTool::sault();
             $acc = new Scalr_Account();
             $acc->loadById($accountId);
             $acc->setSetting(Scalr_Account::SETTING_AUTH_HASH, $hash);
         }
     }
     return $hash;
 }
Пример #6
0
 public static function getKey()
 {
     return CryptoTool::sault(8);
 }
Пример #7
0
 public function save()
 {
     $this->hash = CryptoTool::sault(12);
     parent::save();
 }
Пример #8
0
 /**
  * @param   string              $newRoleName
  * @param   Scalr_Account_User  $user
  * @param   int                 $envId
  * @return  int
  * @throws Exception
  */
 public function cloneRole($newRoleName, $user, $envId)
 {
     $this->db->BeginTrans();
     $accountId = $user->getAccountId();
     try {
         $this->db->Execute("INSERT INTO roles SET\n                name            = ?,\n                origin          = ?,\n                client_id       = ?,\n                env_id          = ?,\n                cat_id          = ?,\n                description     = ?,\n                behaviors       = ?,\n                generation      = ?,\n                os_id           = ?,\n                dtadded         = NOW(),\n                added_by_userid = ?,\n                added_by_email  = ?\n            ", array($newRoleName, $accountId ? ROLE_TYPE::CUSTOM : ROLE_TYPE::SHARED, empty($accountId) ? null : intval($accountId), empty($envId) ? null : intval($envId), $this->catId, $this->description, $this->behaviorsRaw, 2, $this->osId, $user->getId(), $user->getEmail()));
         $newRoleId = $this->db->Insert_Id();
         //Set behaviors
         foreach ($this->getBehaviors() as $behavior) {
             $this->db->Execute("INSERT IGNORE INTO role_behaviors SET role_id = ?, behavior = ?", array($newRoleId, $behavior));
         }
         // Set images
         $rsr7 = $this->db->Execute("SELECT * FROM role_images WHERE role_id = ?", array($this->id));
         while ($r7 = $rsr7->FetchRow()) {
             $this->db->Execute("INSERT INTO role_images SET\n                    `role_id` = ?,\n                    `cloud_location` = ?,\n                    `image_id` = ?,\n                    `platform` = ?\n                ", array($newRoleId, $r7['cloud_location'], $r7['image_id'], $r7['platform']));
         }
         $props = $this->db->Execute("SELECT * FROM role_properties WHERE role_id=?", array($this->id));
         while ($p1 = $props->FetchRow()) {
             $this->db->Execute("\n                    INSERT INTO role_properties\n                    SET `role_id` = ?,\n                        `name`\t= ?,\n                        `value`\t= ?\n                    ON DUPLICATE KEY UPDATE\n                        `value` = ?\n                ", array($newRoleId, $p1['name'], $p1['value'], $p1['value']));
         }
         //Set global variables
         $variables = new Scalr_Scripting_GlobalVariables($this->clientId, $this->envId, ScopeInterface::SCOPE_ROLE);
         $variables->setValues($variables->getValues($this->id), $newRoleId);
         //Set scripts
         $rsr8 = $this->db->Execute("SELECT * FROM role_scripts WHERE role_id = ?", array($this->id));
         while ($r8 = $rsr8->FetchRow()) {
             $this->db->Execute("INSERT INTO role_scripts SET\n                    role_id = ?,\n                    event_name = ?,\n                    target = ?,\n                    script_id = ?,\n                    version = ?,\n                    timeout = ?,\n                    issync = ?,\n                    params = ?,\n                    order_index = ?,\n                    script_type = ?,\n                    script_path = ?,\n                    hash = ?\n                ", array($newRoleId, $r8['event_name'], $r8['target'], $r8['script_id'], $r8['version'], $r8['timeout'], $r8['issync'], $r8['params'], $r8['order_index'], $r8['script_type'], $r8['script_path'], CryptoTool::sault(12)));
         }
         //Set environments only for account-scope roles
         if (!empty($accountId) && empty($envId)) {
             $rsr9 = $this->db->Execute("SELECT * FROM role_environments WHERE role_id = ?", array($this->id));
             while ($r9 = $rsr9->FetchRow()) {
                 $this->db->Execute("INSERT INTO role_environments SET\n                    role_id = ?,\n                    env_id = ?\n                ", array($newRoleId, $r9['env_id']));
             }
         }
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw $e;
     }
     $this->db->CommitTrans();
     if (!empty($newRoleId)) {
         $newRole = self::loadById($newRoleId);
         $newRole->syncAnalyticsTags();
     }
     return $newRoleId;
 }
Пример #9
0
 /**
  * @param string     $cloudLocation                     Ec2 Region
  * @param JsonData   $listeners                         Listeners list
  * @param bool       $crossLoadBalancing                Enable Cross balancing
  * @param JsonData   $healthcheck                       Health check data
  * @param string     $scheme                            optional Scheme
  * @param JsonData   $securityGroups                    optional Security groups
  * @param string     $vpcId                             optional Vpc id
  * @param JsonData   $zones                             optional Availability zones
  * @param JsonData   $subnets                           optional Subnets
  * @param string     $name                              optional Name
  * @throws Exception
  */
 public function xCreateAction($cloudLocation, JsonData $listeners, $crossLoadBalancing, JsonData $healthcheck, $scheme = null, JsonData $securityGroups = null, $vpcId = null, JsonData $zones = null, JsonData $subnets = null, $name = null)
 {
     $this->request->restrictAccess(Acl::RESOURCE_AWS_ELB, Acl::PERM_AWS_ELB_MANAGE);
     $elb = $this->environment->aws($cloudLocation)->elb;
     //prepare listeners
     $listenersList = new ListenerList();
     foreach ($listeners as $listener) {
         $listener_chunks = explode("#", $listener);
         $listenersList->append(new ListenerData(trim($listener_chunks[1]), trim($listener_chunks[2]), trim($listener_chunks[0]), null, trim($listener_chunks[3])));
     }
     $zones = !empty($zones) ? (array) $zones : null;
     $subnets = !empty($subnets) ? (array) $subnets : null;
     if (empty($name)) {
         $name = sprintf("scalr-%s-%s", CryptoTool::sault(10), rand(100, 999));
     } else {
         if (!preg_match('/^[-a-zA-Z0-9]+$/', $name)) {
             throw new Exception('Load Balancer names must only contain alphanumeric characters or dashes.');
         }
     }
     $healthCheckType = new HealthCheckData();
     $healthCheckType->target = $healthcheck['target'];
     $healthCheckType->healthyThreshold = $healthcheck['healthyThreshold'];
     $healthCheckType->interval = $healthcheck['interval'];
     $healthCheckType->timeout = $healthcheck['timeout'];
     $healthCheckType->unhealthyThreshold = $healthcheck['unhealthyThreshold'];
     $securityGroupIds = [];
     foreach ($securityGroups as $securityGroup) {
         $securityGroupIds[] = $securityGroup['id'];
     }
     $result = self::loadController('Aws', 'Scalr_UI_Controller_Tools')->checkSecurityGroupsPolicy($securityGroups, Aws::SERVICE_INTERFACE_ELB);
     if ($result === true) {
         $result = self::loadController('Aws', 'Scalr_UI_Controller_Tools')->checkVpcPolicy($vpcId, $subnets, $cloudLocation);
     }
     if ($result !== true) {
         throw new Exception($result);
     }
     //Creates a new ELB
     $dnsName = $elb->loadBalancer->create($name, $listenersList, $zones, $subnets, !empty($securityGroupIds) ? $securityGroupIds : null, !empty($scheme) ? $scheme : null);
     if ($crossLoadBalancing) {
         $attributes = new AttributesData();
         $attributes->setCrossZoneLoadBalancing(new CrossZoneLoadBalancingData($crossLoadBalancing));
         $requestData = new ModifyLoadBalancerAttributes($name, $attributes);
         $elb->loadBalancer->modifyAttributes($requestData);
     }
     $elb->loadBalancer->addTags($name, $this->getEnvironment()->getAwsTags());
     try {
         $elb->loadBalancer->configureHealthCheck($name, $healthCheckType);
     } catch (Exception $e) {
         $elb->loadBalancer->delete($name);
         throw $e;
     }
     $lb = $elb->loadBalancer->describe($name)->get(0);
     // return all as in xListElb
     $this->response->data(['elb' => ['name' => $name, 'dnsName' => $dnsName, 'dtcreated' => $lb->createdTime->format('c'), 'subnets' => $lb->subnets]]);
 }
Пример #10
0
 /**
  * @param $qr
  * @param $code
  * @throws Exception
  */
 public function xSettingsEnable2FaGglAction($qr, $code)
 {
     if ($this->user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL) == 1) {
         throw new Exception('Two-factor authentication has been already enabled for this user');
     }
     if ($qr && $code) {
         if (Scalr_Util_Google2FA::verifyKey($qr, $code)) {
             $resetCode = CryptoTool::sault(12);
             $this->user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL, 1);
             $this->user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_KEY, $this->getCrypto()->encrypt($qr));
             $this->user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_RESET_CODE, CryptoTool::hash($resetCode));
             $this->response->data(['resetCode' => $resetCode]);
         } else {
             $this->response->data(array('errors' => array('code' => 'Invalid code')));
             $this->response->failure();
         }
     } else {
         $this->response->failure('Invalid data');
     }
 }