Exemplo n.º 1
0
 protected function request($path, $args = array(), $files = array(), $envId = 0, $version = 'v1')
 {
     try {
         $httpRequest = new HttpRequest();
         $httpRequest->setMethod(HTTP_METH_POST);
         $postData = json_encode($args);
         $stringToSign = "/{$version}{$path}:" . $this->API_ACCESS_KEY . ":{$envId}:{$postData}:" . $this->API_SECRET_KEY;
         $validToken = Scalr_Util_CryptoTool::hash($stringToSign);
         $httpRequest->setHeaders(array("X_SCALR_AUTH_KEY" => $this->API_ACCESS_KEY, "X_SCALR_AUTH_TOKEN" => $validToken, "X_SCALR_ENV_ID" => $envId));
         $httpRequest->setUrl("http://scalr-trunk.localhost/{$version}{$path}");
         $httpRequest->setPostFields(array('rawPostData' => $postData));
         foreach ($files as $name => $file) {
             $httpRequest->addPostFile($name, $file);
         }
         $httpRequest->send();
         if ($this->debug) {
             print "<pre>";
             var_dump($httpRequest->getRequestMessage());
             var_dump($httpRequest->getResponseCode());
             var_dump($httpRequest->getResponseData());
         }
         $data = $httpRequest->getResponseData();
         return @json_decode($data['body']);
     } catch (Exception $e) {
         echo "<pre>";
         if ($this->debug) {
             var_dump($e);
         } else {
             var_dump($e->getMessage());
         }
     }
 }
Exemplo n.º 2
0
 private function getSshKeygenValue($args, $tmpFileContents, $readTmpFile = false)
 {
     $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
     $filePath = CACHEPATH . "/_tmp." . Scalr_Util_CryptoTool::hash($tmpFileContents);
     if (!$readTmpFile) {
         @file_put_contents($filePath, $tmpFileContents);
         @chmod($filePath, 0600);
     }
     $pipes = array();
     $process = @proc_open("/usr/bin/ssh-keygen -f {$filePath} {$args}", $descriptorspec, $pipes);
     if (@is_resource($process)) {
         @fclose($pipes[0]);
         $retval = trim(stream_get_contents($pipes[1]));
         fclose($pipes[1]);
         fclose($pipes[2]);
     }
     if ($readTmpFile) {
         $retval = file_get_contents($filePath);
     }
     @unlink($filePath);
     return $retval;
 }
Exemplo n.º 3
0
 public function save()
 {
     $container = \Scalr::getContainer();
     if (!$this->ID) {
         $this->ID = 0;
         $this->Hash = substr(Scalr_Util_CryptoTool::hash(uniqid(rand(), true)), 0, 14);
         if (!$this->ClientID && $container->initialized('environment')) {
             $this->ClientID = $container->environment->clientId;
         }
         if (!$this->EnvID && $container->initialized('environment')) {
             $this->EnvID = $container->environment->id;
         }
     }
     if ($this->DB->GetOne("\n                SELECT id FROM farms\n                WHERE name = ?\n                AND env_id = ?\n                AND id != ?\n                LIMIT 1\n            ", array($this->Name, $this->EnvID, $this->ID))) {
         throw new Exception(sprintf('The name "%s" is already used.', $this->Name));
     }
     if (!$this->ID) {
         $this->DB->Execute("\n                INSERT INTO farms\n                SET status = ?,\n                    name = ?,\n                    clientid = ?,\n                    env_id = ?,\n                    hash = ?,\n                    created_by_id = ?,\n                    created_by_email = ?,\n                    changed_by_id = ?,\n                    changed_time = ?,\n                    dtadded = NOW(),\n                    farm_roles_launch_order = ?,\n                    comments = ?\n            ", array(FARM_STATUS::TERMINATED, $this->Name, $this->ClientID, $this->EnvID, $this->Hash, $this->createdByUserId, $this->createdByUserEmail, $this->changedByUserId, $this->changedTime, $this->RolesLaunchOrder, $this->Comments));
         $this->ID = $this->DB->Insert_ID();
     } else {
         $this->DB->Execute("\n                UPDATE farms\n                SET name = ?,\n                    status = ?,\n                    farm_roles_launch_order = ?,\n                    term_on_sync_fail = ?,\n                    comments = ?,\n                    created_by_id = ?,\n                    created_by_email = ?,\n                    changed_by_id = ?,\n                    changed_time = ?\n                WHERE id = ?\n                LIMIT 1\n            ", array($this->Name, $this->Status, $this->RolesLaunchOrder, $this->TermOnSyncFail, $this->Comments, $this->createdByUserId, $this->createdByUserEmail, $this->changedByUserId, $this->changedTime, $this->ID));
     }
     if (Scalr::getContainer()->analytics->enabled) {
         Scalr::getContainer()->analytics->tags->syncValue($this->ClientID, \Scalr\Stats\CostAnalytics\Entity\TagEntity::TAG_ID_FARM, $this->ID, $this->Name);
     }
 }
Exemplo n.º 4
0
 /**
  * Gets the list of the security groups for the specified db server.
  *
  * If server does not have required security groups this method will create them.
  *
  * @param   DBServer               $DBServer The DB Server instance
  * @param   \Scalr\Service\Aws\Ec2 $ec2      Ec2 Client instance
  * @param   string                 $vpcId    optional The ID of VPC
  * @return  array  Returns array looks like array(groupid-1, groupid-2, ..., groupid-N)
  */
 private function GetServerSecurityGroupsList(DBServer $DBServer, \Scalr\Service\Aws\Ec2 $ec2, $vpcId = "", \Scalr_Governance $governance = null)
 {
     $retval = array();
     $checkGroups = array();
     $sgGovernance = true;
     $allowAdditionalSgs = true;
     $vpcId = null;
     if ($governance) {
         $sgs = $governance->getValue(\SERVER_PLATFORMS::EUCALYPTUS, \Scalr_Governance::EUCALYPTUS_SECURITY_GROUPS);
         if ($sgs !== null) {
             $governanceSecurityGroups = @explode(",", $sgs);
             if (!empty($governanceSecurityGroups)) {
                 foreach ($governanceSecurityGroups as $sg) {
                     if ($sg != '') {
                         array_push($checkGroups, trim($sg));
                     }
                 }
             }
             $sgGovernance = false;
             $allowAdditionalSgs = $governance->getValue(\SERVER_PLATFORMS::EUCALYPTUS, \Scalr_Governance::EUCALYPTUS_SECURITY_GROUPS, 'allow_additional_sec_groups');
         }
     }
     if (!$sgGovernance || $allowAdditionalSgs) {
         if ($DBServer->farmRoleId != 0) {
             $dbFarmRole = $DBServer->GetFarmRoleObject();
             if ($dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_SECURITY_GROUPS_LIST) !== null) {
                 // New SG management
                 $sgs = @json_decode($dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_SECURITY_GROUPS_LIST));
                 if (!empty($sgs)) {
                     foreach ($sgs as $sg) {
                         if (stripos($sg, 'sg-') === 0) {
                             array_push($retval, $sg);
                         } else {
                             array_push($checkGroups, $sg);
                         }
                     }
                 }
             }
         } else {
             array_push($checkGroups, 'scalr-rb-system');
         }
     }
     // No name based security groups, return only SG ids.
     if (empty($checkGroups)) {
         return $retval;
     }
     // Filter groups
     $filter = array(array('name' => SecurityGroupFilterNameType::groupName(), 'value' => $checkGroups));
     // Get filtered list of SG required by scalr;
     try {
         $list = $ec2->securityGroup->describe(null, null, $filter);
         $sgList = array();
         foreach ($list as $sg) {
             /* @var $sg \Scalr\Service\Aws\Ec2\DataType\SecurityGroupData */
             if ($vpcId == '' && !$sg->vpcId || $vpcId && $sg->vpcId == $vpcId) {
                 $sgList[$sg->groupName] = $sg->groupId;
             }
         }
         unset($list);
     } catch (\Exception $e) {
         throw new \Exception("Cannot get list of security groups (1): {$e->getMessage()}");
     }
     foreach ($checkGroups as $groupName) {
         // Check default SG
         if ($groupName == 'default') {
             array_push($retval, $sgList[$groupName]);
             // Check Roles builder SG
         } elseif ($groupName == 'scalr-rb-system') {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create('scalr-rb-system', "Security group for Roles Builder", $vpcId);
                     $ipRangeList = new IpRangeList();
                     foreach (\Scalr::config('scalr.aws.ip_pool') as $ip) {
                         $ipRangeList->append(new IpRangeData($ip));
                     }
                     sleep(2);
                     $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 22, 22, $ipRangeList), new IpPermissionData('tcp', 8008, 8013, $ipRangeList)), $securityGroupId);
                     $sgList['scalr-rb-system'] = $securityGroupId;
                 } catch (\Exception $e) {
                     throw new \Exception(sprintf(_("Cannot create security group '%s': %s"), 'scalr-rb-system', $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
             //Check scalr-farm.* security group
         } elseif (stripos($groupName, 'scalr-farm.') === 0) {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create($groupName, sprintf("Security group for FarmID N%s", $DBServer->farmId), $vpcId);
                     sleep(2);
                     $userIdGroupPairList = new UserIdGroupPairList(new UserIdGroupPairData($DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::ACCOUNT_ID), null, $groupName));
                     $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 0, 65535, null, $userIdGroupPairList), new IpPermissionData('udp', 0, 65535, null, $userIdGroupPairList)), $securityGroupId);
                     $sgList[$groupName] = $securityGroupId;
                 } catch (\Exception $e) {
                     throw new \Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
             //Check scalr-role.* security group
         } elseif (stripos($groupName, 'scalr-role.') === 0) {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create($groupName, sprintf("Security group for FarmRoleID N%s on FarmID N%s", $DBServer->GetFarmRoleObject()->ID, $DBServer->farmId), $vpcId);
                     sleep(2);
                     // DB rules
                     $dbRules = $DBServer->GetFarmRoleObject()->GetRoleObject()->getSecurityRules();
                     $groupRules = array();
                     foreach ($dbRules as $rule) {
                         $groupRules[\Scalr_Util_CryptoTool::hash($rule['rule'])] = $rule;
                     }
                     // Behavior rules
                     foreach (\Scalr_Role_Behavior::getListForFarmRole($DBServer->GetFarmRoleObject()) as $bObj) {
                         $bRules = $bObj->getSecurityRules();
                         foreach ($bRules as $r) {
                             if ($r) {
                                 $groupRules[\Scalr_Util_CryptoTool::hash($r)] = array('rule' => $r);
                             }
                         }
                     }
                     // Default rules
                     $userIdGroupPairList = new UserIdGroupPairList(new UserIdGroupPairData($DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::ACCOUNT_ID), null, $groupName));
                     $rules = array(new IpPermissionData('tcp', 0, 65535, null, $userIdGroupPairList), new IpPermissionData('udp', 0, 65535, null, $userIdGroupPairList));
                     foreach ($groupRules as $rule) {
                         $group_rule = explode(":", $rule["rule"]);
                         $rules[] = new IpPermissionData($group_rule[0], $group_rule[1], $group_rule[2], new IpRangeData($group_rule[3]));
                     }
                     $ec2->securityGroup->authorizeIngress($rules, $securityGroupId);
                     $sgList[$groupName] = $securityGroupId;
                 } catch (\Exception $e) {
                     throw new \Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
         } elseif ($groupName == \Scalr::config('scalr.aws.security_group_name')) {
             if (!isset($sgList[$groupName])) {
                 try {
                     $securityGroupId = $ec2->securityGroup->create($groupName, "Security rules needed by Scalr", $vpcId);
                     $ipRangeList = new IpRangeList();
                     foreach (\Scalr::config('scalr.aws.ip_pool') as $ip) {
                         $ipRangeList->append(new IpRangeData($ip));
                     }
                     // TODO: Open only FOR VPC ranges
                     $ipRangeList->append(new IpRangeData('10.0.0.0/8'));
                     sleep(2);
                     $ec2->securityGroup->authorizeIngress(array(new IpPermissionData('tcp', 3306, 3306, $ipRangeList), new IpPermissionData('tcp', 8008, 8013, $ipRangeList), new IpPermissionData('udp', 8014, 8014, $ipRangeList)), $securityGroupId);
                     $sgList[$groupName] = $securityGroupId;
                 } catch (\Exception $e) {
                     throw new \Exception(sprintf(_("Cannot create security group '%s': %s"), $groupName, $e->getMessage()));
                 }
             }
             array_push($retval, $sgList[$groupName]);
         } else {
             if (!isset($sgList[$groupName])) {
                 throw new \Exception(sprintf(_("Security group '%s' is not found"), $groupName));
             } else {
                 array_push($retval, $sgList[$groupName]);
             }
         }
     }
     return $retval;
 }
Exemplo n.º 5
0
 protected static function createCookieHash($userId, $sault, $hash)
 {
     $pass = self::getUserPassword($userId);
     return Scalr_Util_CryptoTool::hash("{$sault}:{$hash}:{$userId}:{$pass}:" . self::getInstance()->hashpwd);
 }
Exemplo n.º 6
0
 private function saveRules($groupData, $newRules)
 {
     $ruleTypes = array('rules', 'sgRules');
     $addRulesSet = array();
     $rmRulesSet = array();
     foreach ($ruleTypes as $ruleType) {
         $addRulesSet[$ruleType] = array();
         $rmRulesSet[$ruleType] = array();
         foreach ($newRules[$ruleType] as $r) {
             if (!$r['id']) {
                 if ($ruleType == 'rules') {
                     $rule = "{$r['ipProtocol']}:{$r['fromPort']}:{$r['toPort']}:{$r['cidrIp']}";
                 } elseif ($ruleType == 'sgRules') {
                     $rule = "{$r['ipProtocol']}:{$r['fromPort']}:{$r['toPort']}:{$r['sg']}";
                 }
                 $id = Scalr_Util_CryptoTool::hash($rule);
                 if (!$groupData[$ruleType][$id]) {
                     $addRulesSet[$ruleType][] = $r;
                     if ($r['comment']) {
                         //UNIQUE KEY `main` (`env_id`,`sg_name`,`rule`)
                         $this->db->Execute("\n                                INSERT `comments`\n                                SET `env_id` = ?,\n                                    `sg_name` = ?,\n                                    `rule` = ?,\n                                    `comment` = ?\n                                ON DUPLICATE KEY UPDATE\n                                    `comment` = ?\n                                ", array($this->getEnvironmentId(), $groupData['name'], $rule, $r['comment'], $r['comment']));
                     }
                 }
             }
         }
         foreach ($groupData[$ruleType] as $r) {
             $found = false;
             foreach ($newRules[$ruleType] as $nR) {
                 if ($nR['id'] == $r['id']) {
                     $found = true;
                     break;
                 }
             }
             if (!$found) {
                 $rmRulesSet[$ruleType][] = $r;
             }
         }
     }
     if (count($addRulesSet['rules']) > 0 || count($addRulesSet['sgRules']) > 0) {
         $this->updateRules($groupData['platform'], $groupData['cloudLocation'], $groupData['id'], $addRulesSet, 'add');
     }
     if (count($rmRulesSet['rules']) > 0 || count($rmRulesSet['sgRules']) > 0) {
         $this->updateRules($groupData['platform'], $groupData['cloudLocation'], $groupData['id'], $rmRulesSet, 'remove');
     }
 }
Exemplo n.º 7
0
 public static function keepSession()
 {
     $session = self::getInstance();
     $tm = time() + 86400 * 30;
     $setHttpsCookie = $_SERVER['HTTPS'] ? true : false;
     $signature = self::createCookieHash($session->userId, $session->sault, $session->hash);
     $token = Scalr_Util_CryptoTool::hash("{$signature}:" . $session->hashpwd);
     setcookie('scalr_user_id', $session->userId, $tm, "/", null, $setHttpsCookie, true);
     setcookie('scalr_sault', $session->sault, $tm, "/", null, $setHttpsCookie, true);
     setcookie('scalr_hash', $session->hash, $tm, "/", null, $setHttpsCookie, true);
     setcookie('scalr_signature', $signature, $tm, "/", null, $setHttpsCookie, true);
     setcookie('scalr_token', $token, $tm, "/", null, $setHttpsCookie, false);
     $session->setToken($token);
 }
Exemplo n.º 8
0
 private function saveGroupRules($platform, $cloudLocation, $groupData, $newRules)
 {
     $ruleTypes = array('rules', 'sgRules');
     $addRulesSet = array();
     $rmRulesSet = array();
     foreach ($ruleTypes as $ruleType) {
         $addRulesSet[$ruleType] = array();
         $rmRulesSet[$ruleType] = array();
         foreach ($newRules[$ruleType] as $r) {
             if (!$r['id']) {
                 if ($ruleType == 'rules') {
                     $rule = "{$r['ipProtocol']}:{$r['fromPort']}:{$r['toPort']}:{$r['cidrIp']}";
                 } elseif ($ruleType == 'sgRules') {
                     $rule = "{$r['ipProtocol']}:{$r['fromPort']}:{$r['toPort']}:{$r['sg']}";
                 }
                 $id = Scalr_Util_CryptoTool::hash($rule);
                 if (!$groupData[$ruleType][$id]) {
                     $addRulesSet[$ruleType][] = $r;
                     if ($r['comment']) {
                         if ($this->db->GetRow("SHOW TABLES LIKE 'security_group_rules_comments'")) {
                             $this->db->Execute("\n                                    INSERT `security_group_rules_comments`\n                                    SET `env_id` = ?,\n                                        `platform` = ?,\n                                        `cloud_location` = ?,\n                                        `vpc_id` = ?,\n                                        `group_name` = ?,\n                                        `rule` = ?,\n                                        `comment` = ?\n                                    ON DUPLICATE KEY UPDATE\n                                        `comment` = ?\n                                    ", array($this->getEnvironmentId(), $platform, PlatformFactory::isCloudstack($platform) ? '' : $cloudLocation, $groupData['vpcId'] ? $groupData['vpcId'] : '', $groupData['name'], $rule, $r['comment'], $r['comment']));
                         } else {
                             $this->db->Execute("\n                                    INSERT `comments`\n                                    SET `env_id` = ?,\n                                        `sg_name` = ?,\n                                        `rule` = ?,\n                                        `comment` = ?\n                                    ON DUPLICATE KEY UPDATE\n                                        `comment` = ?\n                                    ", array($this->getEnvironmentId(), $groupData['name'], $rule, $r['comment'], $r['comment']));
                         }
                     }
                 }
             }
         }
         foreach ($groupData[$ruleType] as $r) {
             $found = false;
             foreach ($newRules[$ruleType] as $nR) {
                 if ($nR['id'] == $r['id']) {
                     $found = true;
                     break;
                 }
             }
             if (!$found) {
                 $rmRulesSet[$ruleType][] = $r;
             }
         }
     }
     if (count($addRulesSet['rules']) > 0 || count($addRulesSet['sgRules']) > 0) {
         $this->callPlatformMethod($platform, __FUNCTION__, array($platform, $cloudLocation, $groupData['id'], $addRulesSet, 'add'));
     }
     if (count($rmRulesSet['rules']) > 0 || count($rmRulesSet['sgRules']) > 0) {
         $this->callPlatformMethod($platform, __FUNCTION__, array($platform, $cloudLocation, $groupData['id'], $rmRulesSet, 'remove'));
     }
 }
Exemplo n.º 9
0
    $envId = (int) $_SERVER['HTTP_X_SCALR_ENV_ID'];
    $pathChunks = explode('/', $path);
    $version = array_shift($pathChunks);
    $path = '/' . $path;
    //if (! $envId)
    //throw new Exception('Environment not defined');
    // TODO: how to check if needed ?
    $user = Scalr_Account_User::init();
    $user->loadByApiAccessKey($keyId);
    if (!$user->getSetting(Scalr_Account_User::SETTING_API_ENABLED)) {
        throw new Exception("API disabled for this account");
    }
    //Check IP whitelist
    $postData = isset($_POST['rawPostData']) ? $_POST['rawPostData'] : '';
    $secretKey = $user->getSetting(Scalr_Account_User::SETTING_API_SECRET_KEY);
    $stringToSign = "{$path}:{$keyId}:{$envId}:{$postData}:{$secretKey}";
    $validToken = Scalr_Util_CryptoTool::hash($stringToSign);
    if ($validToken != $token) {
        throw new Exception("Invalid authentification token");
    }
    Scalr_UI_Request::initializeInstance(Scalr_UI_Request::REQUEST_TYPE_API, $user->id, $envId);
    // prepate input data
    $postDataConvert = array();
    foreach (json_decode($postData, true) as $key => $value) {
        $postDataConvert[str_replace('.', '_', $key)] = $value;
    }
    Scalr_Api_Controller::handleRequest($pathChunks, $postDataConvert);
} catch (Exception $e) {
    Scalr_UI_Response::getInstance()->failure($e->getMessage());
    Scalr_UI_Response::getInstance()->sendResponse();
}
Exemplo n.º 10
0
 /**
  * @param string $scalrLogin
  * @param RawData $scalrPass
  * @param bool $scalrKeepSession
  * @param int $accountId
  * @param string $tfaGglCode
  * @param bool $tfaGglReset
  * @param string $scalrCaptcha
  * @param string $scalrCaptchaChallenge
  */
 public function xLoginAction($scalrLogin, RawData $scalrPass, $scalrKeepSession = false, $accountId = 0, $tfaGglCode = '', $tfaGglReset = false, $scalrCaptcha = '', $scalrCaptchaChallenge = '')
 {
     $user = $this->loginUserGet($scalrLogin, $scalrPass, $accountId, $scalrCaptcha, $scalrCaptchaChallenge);
     // check for 2-factor auth
     if (($user->getAccountId() && $user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_2FA) || !$user->getAccountId()) && $user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL) == 1) {
         if ($tfaGglCode) {
             if ($tfaGglReset) {
                 $resetCode = $user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_RESET_CODE);
                 if ($resetCode != Scalr_Util_CryptoTool::hash($tfaGglCode)) {
                     $this->response->data(array('errors' => array('tfaGglCode' => 'Invalid reset code')));
                     $this->response->failure();
                     return;
                 } else {
                     $user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL, '');
                     $user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_KEY, '');
                     $user->setSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_RESET_CODE, '');
                     $this->response->success('Two-factor authentication has been disabled.');
                 }
             } else {
                 $key = $this->getCrypto()->decrypt($user->getSetting(Scalr_Account_User::SETTING_SECURITY_2FA_GGL_KEY));
                 if (!Scalr_Util_Google2FA::verifyKey($key, $tfaGglCode)) {
                     $this->response->data(array('errors' => array('tfaGglCode' => 'Invalid code')));
                     $this->response->failure();
                     return;
                 }
             }
         } else {
             $this->response->data(array('tfaGgl' => true));
             $this->response->failure();
             return;
         }
     }
     $this->loginUserCreate($user, $scalrKeepSession);
 }
Exemplo n.º 11
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 = Scalr_Util_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, Scalr_Util_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');
     }
 }
Exemplo n.º 12
0
 public function save()
 {
     if (!$this->ID) {
         $this->ID = 0;
         $this->Hash = substr(Scalr_Util_CryptoTool::hash(uniqid(rand(), true)), 0, 14);
         //FIXME This is F*CKINK BULLSHIT! REMOVE Scalr_UI_Request From here.
         if (!$this->ClientID) {
             $this->ClientID = Scalr_UI_Request::getInstance()->getUser()->getAccountId();
         }
         if (!$this->EnvID) {
             $this->EnvID = Scalr_UI_Request::getInstance()->getEnvironment()->id;
         }
     }
     if ($this->DB->GetOne('SELECT id FROM farms WHERE name = ? AND env_id = ? AND id != ? LIMIT 1', array($this->Name, $this->EnvID, $this->ID))) {
         throw new Exception('This name already used');
     }
     if (!$this->ID) {
         $this->DB->Execute("INSERT INTO farms SET\n                status\t\t= ?,\n                name\t\t= ?,\n                clientid\t= ?,\n                env_id\t\t= ?,\n                hash\t\t= ?,\n                created_by_id = ?,\n                created_by_email = ?,\n                changed_by_id = ?,\n                changed_time = ?,\n                dtadded\t\t= NOW(),\n                farm_roles_launch_order = ?,\n                comments = ?\n            ", array(FARM_STATUS::TERMINATED, $this->Name, $this->ClientID, $this->EnvID, $this->Hash, $this->createdByUserId, $this->createdByUserEmail, $this->changedByUserId, $this->changedTime, $this->RolesLaunchOrder, $this->Comments));
         $this->ID = $this->DB->Insert_ID();
     } else {
         $this->DB->Execute("UPDATE farms SET\n                name\t\t= ?,\n                status\t\t= ?,\n                farm_roles_launch_order = ?,\n                term_on_sync_fail = ?,\n                comments = ?,\n                changed_by_id = ?,\n                changed_time = ?\n            WHERE id = ?\n            ", array($this->Name, $this->Status, $this->RolesLaunchOrder, $this->TermOnSyncFail, $this->Comments, $this->changedByUserId, $this->changedTime, $this->ID));
     }
 }