public function getAccountUsersList() { if ($this->user->canManageAcl()) { $result = $this->db->getAll('SELECT account_users.id FROM account_users WHERE account_id = ?', array($this->user->getAccountId())); foreach ($result as &$row) { $row = Scalr_Account_User::init()->loadById($row['id'])->getUserInfo(); } } else { $result = array(); $teams = $this->user->getTeams(); if (!empty($teams)) { $sql = ' SELECT u.id, u.fullname, u.email FROM account_users u INNER JOIN account_team_users tu ON u.id = tu.user_id WHERE account_id= ?'; $params[] = $this->user->getAccountId(); foreach ($teams as $team) { $r[] = 'tu.team_id = ?'; $params[] = $team['id']; } $sql .= ' AND (' . implode(' OR ', $r) . ')'; $result = $this->db->getAll($sql, $params); } } return $result; }
/** * @param $type * @param $headers * @param $server * @param $params * @param $files * @param $userId * @param $envId * @return Scalr_UI_Request * @throws Scalr_Exception_Core * @throws Exception */ public static function initializeInstance($type, $headers, $server, $params, $files, $userId, $envId) { if (self::$_instance) { self::$_instance = null; } $class = get_called_class(); $instance = new $class($type, $headers, $server, $params, $files); if ($userId) { try { $user = Scalr_Account_User::init(); $user->loadById($userId); } catch (Exception $e) { throw new Exception('User account is no longer available.'); } if ($user->status != Scalr_Account_User::STATUS_ACTIVE) { throw new Exception('User account has been deactivated. Please contact your account owner.'); } if ($user->getType() != Scalr_Account_User::TYPE_SCALR_ADMIN) { $environment = $user->getDefaultEnvironment($envId); $user->getPermissions()->setEnvironmentId($environment->id); } if ($user->getAccountId()) { if ($user->getAccount()->status == Scalr_Account::STATUS_INACIVE) { if ($user->getType() == Scalr_Account_User::TYPE_TEAM_USER) { throw new Exception('Scalr account has been deactivated. Please contact scalr team.'); } } else { if ($user->getAccount()->status == Scalr_Account::STATUS_SUSPENDED) { if ($user->getType() == Scalr_Account_User::TYPE_TEAM_USER) { throw new Exception('Account was suspended. Please contact your account owner to solve this situation.'); } } } } $ipWhitelist = $user->getVar(Scalr_Account_User::VAR_SECURITY_IP_WHITELIST); if ($ipWhitelist) { $ipWhitelist = unserialize($ipWhitelist); if (!Scalr_Util_Network::isIpInSubnets($instance->getRemoteAddr(), $ipWhitelist)) { throw new Exception('The IP address isn\'t authorized'); } } // check header's variables $headerUserId = !is_null($instance->getHeaderVar('UserId')) ? intval($instance->getHeaderVar('UserId')) : null; $headerEnvId = !is_null($instance->getHeaderVar('EnvId')) ? intval($instance->getHeaderVar('EnvId')) : null; if (!empty($headerUserId) && $headerUserId != $user->getId()) { throw new Scalr_Exception_Core('Session expired. Please refresh page.', 1); } if (!empty($headerEnvId) && !empty($environment) && $headerEnvId != $environment->id) { throw new Scalr_Exception_Core('Session expired. Please refresh page.', 1); } $instance->user = $user; $instance->environment = isset($environment) ? $environment : null; } $container = \Scalr::getContainer(); $container->request = $instance; $container->environment = isset($instance->environment) ? $instance->environment : null; self::$_instance = $instance; return $instance; }
public function xRemoveAction() { $user = Scalr_Account_User::init(); $user->loadById($this->getParam('userId')); if ($user->getEmail() == 'admin') { throw new Scalr_Exception_InsufficientPermissions(); } $user->delete(); $this->response->success('User successfully removed'); }
/** * Gets all active financial admins * * @return array Returns all financial admins array(Scalr_Account_User) */ public function getFinancialAdmins() { $rs = $this->db->Execute("SELECT id FROM account_users WHERE type = ? AND status = ?", [\Scalr_Account_User::TYPE_FIN_ADMIN, \Scalr_Account_User::STATUS_ACTIVE]); $result = []; while ($row = $rs->FetchRow()) { $user = \Scalr_Account_User::init()->loadById($row['id']); $result[$user->id] = $user; } return $result; }
/** * Sets user which is asssociated with the role superposition object * * @param \Scalr_Account_User|int $user User object or ID of the user * @return AccountRoleSuperposition * @throws \InvalidArgumentException */ public function setUser($user) { if ($user === null || $user instanceof \Scalr_Account_User) { $this->user = $user; } else { $userId = intval($user); if (empty($userId)) { throw new \InvalidArgumentException("Invalid ID of the user."); } $this->user = \Scalr_Account_User::init(); $this->user->loadById($userId); } return $this; }
protected function run1($stage) { $this->db->Execute(' ALTER TABLE `timeline_events` ADD `account_id` int(11) NULL AFTER `user_id`, ADD `env_id` int(11) NULL AFTER `account_id`, ADD INDEX `idx_account_id` (`account_id` ASC), ADD INDEX `idx_env_id` (`env_id` ASC) '); $res = $this->db->Execute('SELECT * FROM timeline_events'); while ($item = $res->FetchRow()) { $event = new TimelineEventEntity(); $event->load($item); try { $event->accountId = \Scalr_Account_User::init()->loadById($event->userId)->getAccountId(); } catch (Exception $e) { continue; } $event->save(); } }
public function FarmGetDetails($FarmID) { $response = parent::FarmGetDetails($FarmID); try { $DBFarm = DBFarm::LoadByID($FarmID); if ($DBFarm->EnvID != $this->Environment->id) { throw new Exception("N"); } } catch (Exception $e) { throw new Exception(sprintf("Farm #%s not found", $FarmID)); } $response->ID = $DBFarm->ID; $response->Name = $DBFarm->Name; $response->IsLocked = $DBFarm->GetSetting(DBFarm::SETTING_LOCK); if ($response->IsLocked == 1) { $response->LockComment = $DBFarm->GetSetting(DBFarm::SETTING_LOCK_COMMENT); try { $response->LockedBy = Scalr_Account_User::init()->loadById($DBFarm->GetSetting(DBFarm::SETTING_LOCK_BY))->fullname; } catch (Exception $e) { } } foreach ($response->FarmRoleSet->Item as &$item) { $dbFarmRole = DBFarmRole::LoadByID($item->ID); $item->IsScalingEnabled = $dbFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_ENABLED); $item->{"ScalingAlgorithmSet"} = new stdClass(); $item->{"ScalingAlgorithmSet"}->Item = array(); $metrics = $this->DB->GetAll("SELECT metric_id, name, dtlastpolled FROM `farm_role_scaling_metrics`\n INNER JOIN scaling_metrics ON scaling_metrics.id = farm_role_scaling_metrics.metric_id WHERE farm_roleid = ?", array($item->ID)); foreach ($metrics as $metric) { $itm = new stdClass(); $itm->MetricID = $metric['id']; $itm->MetricName = $metric['name']; $itm->DateLastPolled = $metric['dtlastpolled']; $item->{"ScalingAlgorithmSet"}->Item[] = $itm; } } return $response; }
public static function initializeInstance($type, $userId, $envId) { $instance = new Scalr_UI_Request($type); if ($userId) { try { $user = Scalr_Account_User::init(); $user->loadById($userId); } catch (Exception $e) { throw new Exception('User account is no longer available.'); } if ($user->status != Scalr_Account_User::STATUS_ACTIVE) { throw new Exception('User account has been deactivated. Please contact your account owner.'); } if ($user->getType() != Scalr_Account_User::TYPE_SCALR_ADMIN) { $environment = $user->getDefaultEnvironment($envId); $user->getPermissions()->setEnvironmentId($environment->id); } if ($user->getAccountId()) { if ($user->getAccount()->status == Scalr_Account::STATUS_INACIVE) { if ($user->getType() == Scalr_Account_User::TYPE_TEAM_USER) { throw new Exception('Scalr account has been deactivated. Please contact scalr team.'); } } else { if ($user->getAccount()->status == Scalr_Account::STATUS_SUSPENDED) { if ($user->getType() == Scalr_Account_User::TYPE_TEAM_USER) { throw new Exception('Account was suspended. Please contact your account owner to solve this situation.'); } } } } $instance->user = $user; $instance->environment = $environment; } self::$_instance = $instance; return $instance; }
/** * * @param integer $groupId * @param string $login * @param string $password * @param string $email * @return Scalr_Account_User */ public function createUser($email, $password, $type) { if (!$this->id) { throw new Exception("Account is not created"); } $this->validateLimit(Scalr_Limits::ACCOUNT_USERS, 1); $user = Scalr_Account_User::init()->create($email, $this->id); $user->updatePassword($password); $user->type = $type; $user->status = Scalr_Account_User::STATUS_ACTIVE; $user->save(); $keys = Scalr::GenerateAPIKeys(); $user->setSetting(Scalr_Account_User::SETTING_API_ACCESS_KEY, $keys['id']); $user->setSetting(Scalr_Account_User::SETTING_API_SECRET_KEY, $keys['key']); return $user; }
/** * Launches server * * @param \ServerCreateInfo $ServerCreateInfo optional The server create info * @param \DBServer $DBServer optional The DBServer object * @param bool $delayed optional * @param integer|array $reason optional * @param \Scalr_Account_User|int $user optional The Scalr_Account_User object or its unique identifier * @return DBServer|null Returns the DBServer object on cussess or null otherwise */ public static function LaunchServer(ServerCreateInfo $ServerCreateInfo = null, DBServer $DBServer = null, $delayed = false, $reason = 0, $user = null) { $db = self::getDb(); $farm = null; //Ensures handling identifier of the user instead of the object if ($user !== null && !$user instanceof \Scalr_Account_User) { try { $user = Scalr_Account_User::init()->loadById(intval($user)); } catch (\Exception $e) { } } if (!$DBServer && $ServerCreateInfo) { $ServerCreateInfo->SetProperties(array(SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::ONE_TIME)); $DBServer = DBServer::Create($ServerCreateInfo, false, true); } elseif (!$DBServer && !$ServerCreateInfo) { // incorrect arguments Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Cannot create server")); return null; } $propsToSet = array(); if ($user instanceof \Scalr_Account_User) { $propsToSet[SERVER_PROPERTIES::LAUNCHED_BY_ID] = $user->id; $propsToSet[SERVER_PROPERTIES::LAUNCHED_BY_EMAIL] = $user->getEmail(); } //We should keep role_id and farm_role_id in server properties to use in cost analytics if (!empty($DBServer->farmRoleId)) { $propsToSet[SERVER_PROPERTIES::FARM_ROLE_ID] = $DBServer->farmRoleId; $propsToSet[SERVER_PROPERTIES::ROLE_ID] = $DBServer->farmRoleId ? $DBServer->GetFarmRoleObject()->RoleID : 0; } try { // Ensures the farm object will be fetched as correctly as possible $farm = $DBServer->farmId ? $DBServer->GetFarmObject() : null; $farmRole = $DBServer->farmRoleId ? $DBServer->GetFarmRoleObject() : null; if (!$farmRole instanceof DBFarmRole) { $farmRole = null; } else { if (!$farm instanceof DBFarm) { // Gets farm through FarmRole object in this case $farm = $farmRole->GetFarmObject(); } } if ($farm instanceof DBFarm) { $propsToSet[SERVER_PROPERTIES::FARM_CREATED_BY_ID] = $farm->createdByUserId; $propsToSet[SERVER_PROPERTIES::FARM_CREATED_BY_EMAIL] = $farm->createdByUserEmail; $projectId = $farm->GetSetting(DBFarm::SETTING_PROJECT_ID); if (!empty($projectId)) { try { $projectEntity = ProjectEntity::findPk($projectId); if ($projectEntity instanceof ProjectEntity) { /* @var $projectEntity ProjectEntity */ $ccId = $projectEntity->ccId; } else { $projectId = null; } } catch (Exception $e) { $projectId = null; } } $propsToSet[SERVER_PROPERTIES::FARM_PROJECT_ID] = $projectId; } if ($farmRole instanceof DBFarmRole) { $propsToSet[SERVER_PROPERTIES::INFO_INSTANCE_TYPE_NAME] = $farmRole->GetSetting(DBFarmRole::SETTING_INFO_INSTANCE_TYPE_NAME); } if (!empty($ccId)) { $propsToSet[SERVER_PROPERTIES::ENV_CC_ID] = $ccId; } elseif ($DBServer->envId && ($environment = $DBServer->GetEnvironmentObject()) instanceof Scalr_Environment) { $propsToSet[SERVER_PROPERTIES::ENV_CC_ID] = $environment->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID); } } catch (Exception $e) { Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Could not load related object for recently created server %s. It says: %s", $DBServer->serverId, $e->getMessage())); } if (!empty($propsToSet)) { $DBServer->SetProperties($propsToSet); } $fnGetReason = function ($reasonId) { $args = func_get_args(); $args[0] = DBServer::getLaunchReason($reasonId); return [call_user_func_array('sprintf', $args), $reasonId]; }; if ($delayed) { $DBServer->status = SERVER_STATUS::PENDING_LAUNCH; list($reasonMsg, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason); $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_REASON => $reasonMsg, SERVER_PROPERTIES::LAUNCH_REASON_ID => $reasonId]); $DBServer->Save(); return $DBServer; } if ($ServerCreateInfo && $ServerCreateInfo->roleId) { $dbRole = DBRole::loadById($ServerCreateInfo->roleId); if ($dbRole->generation == 1) { $DBServer->status = SERVER_STATUS::PENDING_LAUNCH; $DBServer->Save(); $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_ERROR => "ami-scripts servers no longer supported", SERVER_PROPERTIES::LAUNCH_ATTEMPT => $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ATTEMPT) + 1, SERVER_PROPERTIES::LAUNCH_LAST_TRY => (new DateTime())->format('Y-m-d H:i:s')]); return $DBServer; } } // Limit amount of pending servers if ($DBServer->isOpenstack()) { $config = \Scalr::getContainer()->config; if ($config->defined("scalr.{$DBServer->platform}.pending_servers_limit")) { $pendingServersLimit = $config->get("scalr.{$DBServer->platform}.pending_servers_limit"); $pendingServers = $db->GetOne("SELECT COUNT(*) FROM servers WHERE platform=? AND status=? AND server_id != ?", array($DBServer->platform, SERVER_STATUS::PENDING, $DBServer->serverId)); if ($pendingServers >= $pendingServersLimit) { Logger::getLogger("SERVER_LAUNCH")->warn("{$pendingServers} servers in PENDING state on {$DBServer->platform}. Limit is: {$pendingServersLimit}. Waiting."); $DBServer->status = SERVER_STATUS::PENDING_LAUNCH; $DBServer->Save(); $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_ATTEMPT => $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ATTEMPT) + 1, SERVER_PROPERTIES::LAUNCH_LAST_TRY => (new DateTime())->format('Y-m-d H:i:s')]); return $DBServer; } else { Logger::getLogger("SERVER_LAUNCH")->warn("{$pendingServers} servers in PENDING state on {$DBServer->platform}. Limit is: {$pendingServersLimit}. Launching server."); } } } try { $account = Scalr_Account::init()->loadById($DBServer->clientId); $account->validateLimit(Scalr_Limits::ACCOUNT_SERVERS, 1); PlatformFactory::NewPlatform($DBServer->platform)->LaunchServer($DBServer); $DBServer->status = SERVER_STATUS::PENDING; $DBServer->Save(); try { if ($reason) { list($reasonMsg, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason); } else { $reasonMsg = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON); $reasonId = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON_ID); } $DBServer->getServerHistory()->markAsLaunched($reasonMsg, $reasonId); $DBServer->updateTimelog('ts_launched'); if ($DBServer->imageId) { //Update Image last used date $image = Image::findOne([['id' => $DBServer->imageId], ['envId' => $DBServer->envId], ['platform' => $DBServer->platform], ['cloudLocation' => $DBServer->cloudLocation]]); if (!$image) { $image = Image::findOne([['id' => $DBServer->imageId], ['envId' => NULL], ['platform' => $DBServer->platform], ['cloudLocation' => $DBServer->cloudLocation]]); } if ($image) { $image->dtLastUsed = new DateTime(); $image->save(); } //Update Role last used date if ($DBServer->farmRoleId) { $dbRole = $DBServer->GetFarmRoleObject()->GetRoleObject(); $dbRole->dtLastUsed = date("Y-m-d H:i:s"); $dbRole->save(); } } } catch (Exception $e) { Logger::getLogger('SERVER_HISTORY')->error(sprintf("Cannot update servers history: {$e->getMessage()}")); } } catch (Exception $e) { Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBServer->farmId, sprintf("Cannot launch server on '%s' platform: %s", $DBServer->platform, $e->getMessage()), $DBServer->serverId)); $existingLaunchError = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ERROR); $DBServer->status = SERVER_STATUS::PENDING_LAUNCH; $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_ERROR => $e->getMessage(), SERVER_PROPERTIES::LAUNCH_ATTEMPT => $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ATTEMPT) + 1, SERVER_PROPERTIES::LAUNCH_LAST_TRY => (new DateTime())->format('Y-m-d H:i:s')]); $DBServer->Save(); if ($DBServer->farmId && !$existingLaunchError) { Scalr::FireEvent($DBServer->farmId, new InstanceLaunchFailedEvent($DBServer, $e->getMessage())); } } if ($DBServer->status == SERVER_STATUS::PENDING) { Scalr::FireEvent($DBServer->farmId, new BeforeInstanceLaunchEvent($DBServer)); $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, ""); } return $DBServer; }
require dirname(__FILE__) . "/../src/prepend.inc.php"; try { $dbFarm = DBFarm::LoadByID($_REQUEST['farmid']); } catch (Exception $e) { die("Error (1)"); } // // Auth user // if (!$_SERVER['PHP_AUTH_USER'] || !$_SERVER['PHP_AUTH_PW']) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); exit; } else { try { $user = Scalr_Account_User::init()->loadBySetting(Scalr_Account_User::SETTING_RSS_LOGIN, $_SERVER['PHP_AUTH_USER']); } catch (Exception $e) { } if (!$user || $_SERVER['PHP_AUTH_PW'] != $user->getSetting(Scalr_Account_User::SETTING_RSS_PASSWORD)) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); exit; } if (!$user->getPermissions()->check(Scalr_Environment::init()->loadById($dbFarm->EnvID))) { die("Error (2)"); } } header("Content-type: application/rss+xml"); // // Check cache //
private function AuthenticateREST($request) { if (!$request['Signature']) { throw new Exception("Signature is missing"); } if (!$request['KeyID']) { throw new Exception("KeyID is missing"); } if (!$request['Timestamp'] && !$request['TimeStamp']) { throw new Exception("Timestamp is missing"); } ksort($request); $string_to_sign = ""; foreach ($request as $k => $v) { if (!in_array($k, array("Signature"))) { if (is_array($v)) { foreach ($v as $kk => $vv) { $string_to_sign .= "{$k}[{$kk}]{$vv}"; } } else { $string_to_sign .= "{$k}{$v}"; } } } $this->debug['stringToSign'] = $string_to_sign; $this->user = Scalr_Account_User::init()->loadByApiAccessKey($request['KeyID']); if (!$this->user) { throw new Exception("API Key #{$request['KeyID']} not found in database"); } $auth_key = $this->user->getSetting(Scalr_Account_User::SETTING_API_SECRET_KEY); if ($this->user->getAccountId()) { if (!$request['EnvID']) { $envs = $this->user->getEnvironments(); if (!$envs[0]['id']) { throw new Exception("User has no access to any environemnts"); } $this->Environment = Scalr_Environment::init()->loadById($envs[0]['id']); } else { $this->Environment = Scalr_Environment::init()->loadById($request['EnvID']); } $this->user->getPermissions()->setEnvironmentId($this->Environment->id)->validate($this->Environment); //We must set environment to DI Container. $this->getContainer()->environment = $this->Environment; } $valid_sign = base64_encode(hash_hmac(self::HASH_ALGO, trim($string_to_sign), $auth_key, 1)); if ($valid_sign != $request['Signature']) { throw new Exception("Signature doesn't match"); } }
public function xRemoveUserAction() { $team = $this->getTeam(); if ($this->user->canManageAcl() || $this->user->isTeamOwner($team->id)) { $user = Scalr_Account_User::init(); $user->loadById($this->getParam('userId')); $this->user->getPermissions()->validate($user); if (!$this->user->isAccountOwner()) { if ($team->isTeamOwner($user->id)) { throw new Scalr_Exception_InsufficientPermissions(); } } $team->removeUser($user->id); $this->response->success('User has been successfully removed from the team.'); } else { throw new Scalr_Exception_InsufficientPermissions(); } }
public function addUser($userId, $permissions) { $user = Scalr_Account_User::init(); $user->loadById($userId); if ($user->getAccountId() == $this->accountId) { $this->removeUser($userId); $this->db->Execute('INSERT INTO `account_team_users` (team_id, user_id, permissions) VALUES(?,?,?)', array($this->id, $userId, $permissions)); } else { throw new Exception('This user doesn\'t belongs to this account'); } }
public function xRemoveAction() { $user = Scalr_Account_User::init(); $user->loadById($this->getParam('userId')); if (!$this->user->canRemoveUser($user)) { throw new Scalr_Exception_InsufficientPermissions(); } $user->delete(); $this->response->success('Selected user successfully removed'); return; }
/** * Marks server as to be terminated. * * @param string|array $reason The reason possibly with the format parameters. * @param bool $forcefully optional Method: forcefully (true) | gracefully (false) * @param Scalr_Account_User|int $user optional The user object or its unique identifier */ public function terminate($reason, $forcefully = null, $user = null) { if ($this->status == SERVER_STATUS::PENDING_TERMINATE || $this->status == SERVER_STATUS::TERMINATED) { return; } $forcefully = $forcefully === null ? true : (bool) $forcefully; //Ensures handling identifier of the user instead of the object if ($user !== null && !$user instanceof \Scalr_Account_User) { try { $user = Scalr_Account_User::init()->loadById(intval($user)); } catch (\Exception $e) { } } $class = get_class($this); $fnGetReason = function ($reason) use($class) { $args = func_get_args(); if (is_string($reason)) { if (defined($class . '::TERMINATE_REASON_' . $reason)) { $args[0] = constant($class . '::TERMINATE_REASON_' . $reason); } elseif (strpos($reason, 'TERMINATE_REASON_') === 0 && defined($class . '::' . $reason)) { $args[0] = constant($class . '::' . $reason); } } return call_user_func_array('sprintf', $args); }; $reason = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason); //Set who does terminate the server if ($user instanceof \Scalr_Account_User) { $this->SetProperties(array(SERVER_PROPERTIES::TERMINATED_BY_ID => $user->id, SERVER_PROPERTIES::TERMINATED_BY_EMAIL => $user->getEmail())); } $this->status = SERVER_STATUS::PENDING_TERMINATE; $this->dateShutdownScheduled = date("Y-m-d H:i:s", $forcefully ? time() : strtotime(Scalr::config('scalr.system.server_terminate_timeout'))); $this->Save(); $this->getServerHistory()->markAsTerminated($reason); if (isset($this->farmId)) { Scalr::FireEvent($this->farmId, new BeforeHostTerminateEvent($this, $forcefully)); } }
/** * Gets an test User instance * * @return \Scalr_Account_user Returns user instance */ protected function getUser() { if (!isset($this->user)) { if (empty($this->_testUserId)) { $this->_testUserId = \Scalr::config('scalr.phpunit.userid'); } $this->user = \Scalr_Account_User::init(); $this->user->loadById($this->_testUserId); } return $this->user; }
/** * @param $hash * @param $password */ public function xUpdatePasswordAction($hash, $password) { $user = Scalr_Account_User::init()->loadBySetting(Scalr_Account::SETTING_OWNER_PWD_RESET_HASH, $hash); if ($user && $password) { $user->updatePassword($password); $user->loginattempts = 0; $user->save(); $user->setSetting(Scalr_Account::SETTING_OWNER_PWD_RESET_HASH, ""); //Scalr_Session::create($user->getAccountId(), $user->getId(), $user->getType()); $this->response->success("Password has been reset. Please log in."); } else { $this->response->failure("Incorrect confirmation link"); } }
/** * Check if farm is locked * * @param $throwException * @return bool * @throws Exception */ public function isLocked($throwException = true) { if ($this->GetSetting(Entity\FarmSetting::LOCK)) { $message = $this->GetSetting(Entity\FarmSetting::LOCK_COMMENT); try { $userName = Scalr_Account_User::init()->loadById($this->getSetting(Entity\FarmSetting::LOCK_BY))->getEmail(); } catch (Exception $e) { $userName = $this->getSetting(Entity\FarmSetting::LOCK_BY); } if ($message) { $message = sprintf(' with comment: \'%s\'', $message); } if ($throwException) { throw new Exception(sprintf('Farm was locked by %s%s. Please unlock it first.', $userName, $message)); } else { return sprintf('Farm was locked by %s%s.', $userName, $message); } } return false; }
/** * Launches server * * @param \ServerCreateInfo $ServerCreateInfo optional The server create info * @param \DBServer $DBServer optional The DBServer object * @param bool $delayed optional * @param string $reason optional * @param \Scalr_Account_User|int $user optional The Scalr_Account_User object or its unique identifier * @return DBServer|null Returns the DBServer object on cussess or null otherwise */ public static function LaunchServer(ServerCreateInfo $ServerCreateInfo = null, DBServer $DBServer = null, $delayed = false, $reason = "", $user = null) { $db = self::getDb(); //Ensures handling identifier of the user instead of the object if ($user !== null && !$user instanceof \Scalr_Account_User) { try { $user = Scalr_Account_User::init()->loadById(intval($user)); } catch (\Exception $e) { } } if (!$DBServer && $ServerCreateInfo) { $ServerCreateInfo->SetProperties(array(SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::ONE_TIME)); $DBServer = DBServer::Create($ServerCreateInfo, false, true); } elseif (!$DBServer && !$ServerCreateInfo) { // incorrect arguments Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Cannot create server")); return null; } if ($user instanceof \Scalr_Account_User) { $DBServer->SetProperties(array(SERVER_PROPERTIES::LAUNCHED_BY_ID => $user->id, SERVER_PROPERTIES::LAUNCHED_BY_EMAIL => $user->getEmail())); } if ($delayed) { $DBServer->status = SERVER_STATUS::PENDING_LAUNCH; $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_REASON, $reason); $DBServer->Save(); return $DBServer; } if ($ServerCreateInfo && $ServerCreateInfo->roleId) { $dbRole = DBRole::loadById($ServerCreateInfo->roleId); if ($dbRole->generation == 1) { $DBServer->status = SERVER_STATUS::PENDING_LAUNCH; $DBServer->Save(); $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, "ami-scripts servers no longer supported"); return $DBServer; } } try { $account = Scalr_Account::init()->loadById($DBServer->clientId); $account->validateLimit(Scalr_Limits::ACCOUNT_SERVERS, 1); PlatformFactory::NewPlatform($DBServer->platform)->LaunchServer($DBServer); $DBServer->status = SERVER_STATUS::PENDING; $DBServer->Save(); try { if (!$reason) { $reason = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON); } $DBServer->getServerHistory()->markAsLaunched($reason); } catch (Exception $e) { Logger::getLogger('SERVER_HISTORY')->error(sprintf("Cannot update servers history: {$e->getMessage()}")); } } catch (Exception $e) { Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBServer->farmId, sprintf("Cannot launch server on '%s' platform: %s", $DBServer->platform, $e->getMessage()))); $DBServer->status = SERVER_STATUS::PENDING_LAUNCH; $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, $e->getMessage()); $DBServer->Save(); } if ($DBServer->status == SERVER_STATUS::PENDING) { Scalr::FireEvent($DBServer->farmId, new BeforeInstanceLaunchEvent($DBServer)); $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, ""); } return $DBServer; }
/** * Adds user to the team * * @param int $userId The identifier of the user * @param string $permissions This parameter has been deprecated since new ACL. * @throws Exception */ public function addUser($userId, $permissions = null) { $user = Scalr_Account_User::init(); $user->loadById($userId); if ($user->getAccountId() == $this->accountId) { $this->removeUser($userId); $this->db->Execute("\n INSERT INTO `account_team_users` (team_id, user_id, permissions)\n VALUES (?, ?, ?)\n ", array($this->id, $userId, $permissions)); } else { throw new Exception(sprintf('The specified user "%d" doesn\'t belong to account "%d".', $userId, $this->accountId)); } }
/** * @param string $hash * @param RawData $password */ public function xUpdatePasswordAction($hash, RawData $password) { if ($hash && ($user = Scalr_Account_User::init()->loadBySetting(Scalr_Account::SETTING_OWNER_PWD_RESET_HASH, $hash)) && $password) { $validator = new Validator(); $validator->validate($password, "password", Validator::PASSWORD, $user->isAccountAdmin() || $user->isAccountOwner() ? ['admin'] : []); if ($validator->isValid($this->response)) { $user->updatePassword($password); $user->loginattempts = 0; $user->save(); $user->setSetting(Scalr_Account::SETTING_OWNER_PWD_RESET_HASH, ""); $this->response->data(['email' => $user->getEmail(), 'message' => 'Password has been reset. Please log in.']); } } else { $this->response->failure("Incorrect confirmation link"); } }
/** * Marks server as to be terminated. * * @param integer|array $reason The reason possibly with the format parameters. * @param bool $forcefully optional Method: forcefully (true) | gracefully (false) * @param Scalr_Account_User|int $user optional The user object or its unique identifier */ public function terminate($reason, $forcefully = null, $user = null) { if (in_array($this->status, array(SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TERMINATED))) { return; } $forcefully = $forcefully === null ? true : (bool) $forcefully; //Ensures handling identifier of the user instead of the object if ($user !== null && !$user instanceof \Scalr_Account_User) { try { $user = Scalr_Account_User::init()->loadById(intval($user)); } catch (\Exception $e) { } } $fnGetReason = function ($reasonId) { $args = func_get_args(); $args[0] = DBServer::getTerminateReason($reasonId); return [call_user_func_array('sprintf', $args), $reasonId]; }; list($reason, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason); //Set who does terminate the server if ($user instanceof \Scalr_Account_User) { $this->SetProperties(array(\SERVER_PROPERTIES::TERMINATED_BY_ID => $user->id, \SERVER_PROPERTIES::TERMINATED_BY_EMAIL => $user->getEmail())); } $this->SetProperties([SERVER_PROPERTIES::REBOOTING => 0]); $this->update(['status' => SERVER_STATUS::PENDING_TERMINATE, 'dateShutdownScheduled' => date("Y-m-d H:i:s", $forcefully ? time() : strtotime(Scalr::config('scalr.system.server_terminate_timeout')))]); $this->getServerHistory()->markAsTerminated($reason, $reasonId); if (isset($this->farmId)) { Scalr::FireEvent($this->farmId, new BeforeHostTerminateEvent($this, false)); // If instance was terminated outside scalr, we need manually fire HostDown if ($reasonId == self::TERMINATE_REASON_CRASHED) { Scalr::FireEvent($this->farmId, new HostDownEvent($this, false)); } } }
//@TODO: optimize $path = trim(str_replace("?{$_SERVER['QUERY_STRING']}", "", $_SERVER['REQUEST_URI']), '/'); @session_start(); try { require "src/prepend.inc.php"; $keyId = $_SERVER['HTTP_X_SCALR_AUTH_KEY']; $token = $_SERVER['HTTP_X_SCALR_AUTH_TOKEN']; $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();
$envId = $env->id; $user = $account->createUser($email, $password, Scalr_Account_User::TYPE_ACCOUNT_OWNER); $user->fullname = $name; $user->save(); $clientSettings[CLIENT_SETTINGS::RSS_LOGIN] = $email; $clientSettings[CLIENT_SETTINGS::RSS_PASSWORD] = $crypto->sault(10); foreach ($clientSettings as $k => $v) { $account->setSetting($k, $v); } try { $db->Execute("INSERT INTO default_records SELECT null, '{$account->id}', type, ttl, priority, value, name FROM default_records WHERE clientid='0'"); } catch (Exception $e) { $err['db'] = $e->getMessage(); } } else { $user = Scalr_Account_User::init()->loadByEmail($email); if (!$user) { throw new Exception("User Not Found"); } $account = $user->getAccount(); $env = $user->getDefaultEnvironment(); $envId = $env->id; } try { $retval = array('success' => true, 'account' => array('id' => $account->id, 'userId' => $user->id, 'password' => $password, 'envId' => $env->id, 'api_access_key' => $user->getSetting(Scalr_Account_User::SETTING_API_ACCESS_KEY), 'api_secret_key' => $user->getSetting(Scalr_Account_User::SETTING_API_SECRET_KEY))); $updateEnv = false; if (!$_REQUEST['update']) { //CONFIGURE OPENSTACK: $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::KEYSTONE_URL] = $_REQUEST['openstack_keystone_url']; $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::USERNAME] = $_REQUEST['openstack_username']; $pars[SERVER_PLATFORMS::ECS . "." . OpenstackPlatformModule::PASSWORD] = $_REQUEST['openstack_password'];
/** * @test * @depends testXRemove */ public function testTeamOwnerUserHasBeenAdjustedWithAccountAdminType() { $user = \Scalr_Account_User::init(); $user->loadById($this->getUser()->getId()); $this->assertTrue($user->isAccountAdmin() || $user->isAccountOwner()); }
public function xRemoveAction() { $user = Scalr_Account_User::init(); $user->loadById($this->getParam('userId')); if ($user->getAccountId() == $this->user->getAccountId() && $user->getType() == Scalr_Account_User::TYPE_TEAM_USER && !$user->isTeamOwner()) { if ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER || $this->user->isTeamOwner()) { $user->delete(); $this->response->success('User successfully removed'); return; } } throw new Scalr_Exception_InsufficientPermissions(); }
public function xRemoveUserAction() { $team = $this->getTeam(); if ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER || $this->user->isTeamOwner($team->id)) { $user = Scalr_Account_User::init(); $user->loadById($this->getParam('userId')); $this->user->getPermissions()->validate($user); if ($this->user->getType() != Scalr_Account_User::TYPE_ACCOUNT_OWNER) { if ($team->isTeamOwner($user->id)) { throw new Scalr_Exception_InsufficientPermissions(); } } $team->removeUser($user->id); $this->response->success('User successfully removed from team'); } else { throw new Scalr_Exception_InsufficientPermissions(); } }
public function xRemoveAction() { $user = Scalr_Account_User::init(); $user->loadById($this->getParam('userId')); if ($user->getAccountId() == $this->user->getAccountId()) { if ($this->user->canManageAcl() || $this->user->isTeamOwner()) { $user->delete(); $this->response->success('User has been successfully removed.'); return; } } throw new Scalr_Exception_InsufficientPermissions(); }
/** * Launches server * * @param \ServerCreateInfo $ServerCreateInfo optional The server create info * @param \DBServer $DBServer optional The DBServer object * @param bool $delayed optional * @param integer|array $reason optional * @param \Scalr_Account_User|int $user optional The Scalr_Account_User object or its unique identifier * @return DBServer|null Returns the DBServer object on cussess or null otherwise */ public static function LaunchServer(ServerCreateInfo $ServerCreateInfo = null, DBServer $DBServer = null, $delayed = false, $reason = 0, $user = null) { $db = self::getDb(); $farm = null; //Ensures handling identifier of the user instead of the object if ($user !== null && !$user instanceof \Scalr_Account_User) { try { $user = Scalr_Account_User::init()->loadById(intval($user)); } catch (\Exception $e) { } } if (!$DBServer && $ServerCreateInfo) { $ServerCreateInfo->SetProperties(array(SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::ONE_TIME)); $DBServer = DBServer::Create($ServerCreateInfo, false, true); } elseif (!$DBServer && !$ServerCreateInfo) { // incorrect arguments Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Cannot create server")); return null; } $propsToSet = array(); if ($user instanceof \Scalr_Account_User) { $propsToSet[SERVER_PROPERTIES::LAUNCHED_BY_ID] = $user->id; $propsToSet[SERVER_PROPERTIES::LAUNCHED_BY_EMAIL] = $user->getEmail(); } try { if ($DBServer->farmId && ($farm = $DBServer->GetFarmObject()) instanceof DBFarm) { $propsToSet[SERVER_PROPERTIES::FARM_CREATED_BY_ID] = $farm->createdByUserId; $propsToSet[SERVER_PROPERTIES::FARM_CREATED_BY_EMAIL] = $farm->createdByUserEmail; $propsToSet[SERVER_PROPERTIES::FARM_PROJECT_ID] = $farm->GetSetting(DBFarm::SETTING_PROJECT_ID); } if ($DBServer->envId && ($environment = $DBServer->GetEnvironmentObject()) instanceof Scalr_Environment) { $propsToSet[SERVER_PROPERTIES::ENV_CC_ID] = $environment->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID); } } catch (Exception $e) { Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Could not load related object for recently created server %s. It says: %s", $DBServer->serverId, $e->getMessage())); } if (!empty($propsToSet)) { $DBServer->SetProperties($propsToSet); } $fnGetReason = function ($reasonId) { $args = func_get_args(); $args[0] = DBServer::getLaunchReason($reasonId); return [call_user_func_array('sprintf', $args), $reasonId]; }; if ($delayed) { $DBServer->status = SERVER_STATUS::PENDING_LAUNCH; list($reasonMsg, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason); $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_REASON => $reasonMsg, SERVER_PROPERTIES::LAUNCH_REASON_ID => $reasonId]); $DBServer->Save(); return $DBServer; } if ($ServerCreateInfo && $ServerCreateInfo->roleId) { $dbRole = DBRole::loadById($ServerCreateInfo->roleId); if ($dbRole->generation == 1) { $DBServer->status = SERVER_STATUS::PENDING_LAUNCH; $DBServer->Save(); $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, "ami-scripts servers no longer supported"); return $DBServer; } } try { $account = Scalr_Account::init()->loadById($DBServer->clientId); $account->validateLimit(Scalr_Limits::ACCOUNT_SERVERS, 1); PlatformFactory::NewPlatform($DBServer->platform)->LaunchServer($DBServer); $DBServer->status = SERVER_STATUS::PENDING; $DBServer->Save(); try { if ($reason) { list($reasonMsg, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason); } else { $reasonMsg = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON); $reasonId = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON_ID); } $DBServer->getServerHistory()->markAsLaunched($reasonMsg, $reasonId); $DBServer->updateTimelog('ts_launched'); } catch (Exception $e) { Logger::getLogger('SERVER_HISTORY')->error(sprintf("Cannot update servers history: {$e->getMessage()}")); } } catch (Exception $e) { Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBServer->farmId, sprintf("Cannot launch server on '%s' platform: %s", $DBServer->platform, $e->getMessage()))); $existingLaunchError = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ERROR); $DBServer->status = SERVER_STATUS::PENDING_LAUNCH; $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, $e->getMessage()); $DBServer->Save(); if ($DBServer->farmId && !$existingLaunchError) { Scalr::FireEvent($DBServer->farmId, new InstanceLaunchFailedEvent($DBServer, $e->getMessage())); } } if ($DBServer->status == SERVER_STATUS::PENDING) { Scalr::FireEvent($DBServer->farmId, new BeforeInstanceLaunchEvent($DBServer)); $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, ""); } return $DBServer; }