Ejemplo n.º 1
0
Archivo: Os.php Proyecto: scalr/scalr
 /**
  * @param string $id
  * @param string $status
  * @param string $name
  * @param string $family
  * @param string $generation
  * @param string $version
  * @throws Exception
  */
 public function xSaveAction($id, $status, $name, $family, $generation, $version = '')
 {
     $os = Os::findPk($id);
     if (!$os) {
         $os = new Os();
         $os->isSystem = 0;
         $os->id = $id;
     }
     $validator = new Validator();
     $validator->validate($id, 'id', Validator::NOEMPTY);
     $validator->validate($name, 'name', Validator::NOEMPTY);
     $validator->validate($family, 'family', Validator::NOEMPTY);
     $validator->validate($generation, 'generation', Validator::NOEMPTY);
     //check by name, family, generation,version
     $criteria = [];
     $criteria[] = ['name' => $name];
     $criteria[] = ['family' => $family];
     $criteria[] = ['generation' => $generation];
     $criteria[] = ['version' => $version];
     if ($os->id) {
         $criteria[] = ['id' => ['$ne' => $os->id]];
     }
     if (Os::findOne($criteria)) {
         $validator->addError('name', 'Operating system with such name, family, generation and version already exists');
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     $os->status = $status;
     if ($os->isSystem != 1) {
         $os->name = $name;
         $os->family = $family;
         $os->generation = $generation;
         $os->version = $version;
     }
     $os->save();
     $result = get_object_vars($os);
     $result['used'] = $os->getUsed();
     $this->response->data(['os' => $os]);
     $this->response->success('Operating system successfully saved');
 }
Ejemplo n.º 2
0
 /**
  * @param string $url
  * @param string $endpointId
  * @throws Exception
  */
 public function xSaveAction($url, $endpointId = null)
 {
     if (!$endpointId) {
         $endpoint = new WebhookEndpoint();
         $endpoint->setScope($this->request->getScope(), $this->user->getAccountId(), $this->getEnvironmentId(true));
         $endpoint->securityKey = Scalr::GenerateRandomKey(64);
     } else {
         $endpoint = WebhookEndpoint::findPk($endpointId);
         if (!$this->canEditEndpoint($endpoint)) {
             throw new Scalr_Exception_Core('Insufficient permissions to edit endpoint at this scope');
         }
     }
     $validator = new Validator();
     $validator->validate($url, 'url', Validator::URL);
     //check url unique within current level
     $criteria = [];
     $criteria[] = ['url' => $url];
     if ($endpoint->endpointId) {
         $criteria[] = ['endpointId' => ['$ne' => $endpoint->endpointId]];
     }
     switch ($this->request->getScope()) {
         case WebhookEndpoint::SCOPE_ENVIRONMENT:
             $criteria[] = ['level' => WebhookEndpoint::LEVEL_ENVIRONMENT];
             $criteria[] = ['envId' => $endpoint->envId];
             $criteria[] = ['accountId' => $endpoint->accountId];
             break;
         case WebhookEndpoint::SCOPE_ACCOUNT:
             $criteria[] = ['level' => WebhookEndpoint::LEVEL_ACCOUNT];
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => $endpoint->accountId];
             break;
         case WebhookEndpoint::SCOPE_SCALR:
             $criteria[] = ['level' => WebhookEndpoint::LEVEL_SCALR];
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => null];
             break;
     }
     if (WebhookEndpoint::findOne($criteria)) {
         $validator->addError('url', 'Endpoint url must be unique within current scope');
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     if ($endpoint->url != $url) {
         $endpoint->isValid = false;
         $endpoint->url = $url;
     }
     ////temporarily disable url validation per Igor`s request(see also webhooks/endpoints/view.js)
     $endpoint->isValid = true;
     $endpoint->save();
     $this->response->success('Endpoint successfully saved');
     $this->response->data(array('endpoint' => array('endpointId' => $endpoint->endpointId, 'url' => $endpoint->url, 'isValid' => $endpoint->isValid, 'validationToken' => $endpoint->validationToken, 'securityKey' => $endpoint->securityKey, 'scope' => $endpoint->getScope())));
 }
Ejemplo n.º 3
0
Archivo: Acl.php Proyecto: mheydt/scalr
 /**
  * Saves ACL
  *
  * @param string   $id
  * @param string   $name
  * @param int      $baseRoleId
  * @param string   $color
  * @param JsonData $resources
  * @throws InvalidArgumentException
  */
 public function xSaveAction($id, $name, $baseRoleId, $color, JsonData $resources)
 {
     $validator = new Validator();
     $validator->validate($name, 'name', Validator::NOEMPTY);
     if (!$validator->isValid($this->response)) {
         return;
     }
     $acl = \Scalr::getContainer()->acl;
     $r = [];
     foreach ($resources as $v) {
         $r[$v['id']] = $v;
     }
     try {
         $id = $acl->setAccountRole($this->request->getUser()->getAccountId(), $baseRoleId, $name, hexdec($color), $r, $id);
     } catch (\Exception $e) {
         if ($e instanceof \Scalr\Acl\Exception\AclException) {
             return $this->response->failure($e->getMessage());
         } else {
             throw $e;
         }
     }
     $this->response->data(['role' => $acl->getAccountRoleComputed($id)]);
     $this->response->success('ACL successfully saved');
 }
Ejemplo n.º 4
0
 /**
  * @param int $id
  * @param string $url
  * @param string $username
  * @param string $authKey
  * @param string $vUsername
  * @param string $vAuthKey
  * @throws Exception
  */
 public function xSaveAction($id, $url, $username, $authKey, $vUsername, $vAuthKey)
 {
     if (!$this->canManageServers()) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
     if (!$id) {
         $server = new ChefServer();
         $server->setScope($this->request->getScope(), $this->user->getAccountId(), $this->getEnvironmentId(true));
     } else {
         $server = ChefServer::findPk($id);
         if (!$this->canEditServer($server)) {
             throw new Scalr_Exception_Core('Insufficient permissions to edit chef server at this scope');
         }
     }
     $validator = new Validator();
     $validator->validate($url, 'url', Validator::NOEMPTY);
     //check url unique within current scope
     $criteria = [];
     $criteria[] = ['url' => $url];
     if ($server->id) {
         $criteria[] = ['id' => ['$ne' => $server->id]];
     }
     switch ($this->request->getScope()) {
         case ChefServer::SCOPE_ENVIRONMENT:
             $criteria[] = ['level' => ChefServer::LEVEL_ENVIRONMENT];
             $criteria[] = ['envId' => $server->envId];
             $criteria[] = ['accountId' => $server->accountId];
             break;
         case ChefServer::SCOPE_ACCOUNT:
             $criteria[] = ['level' => ChefServer::LEVEL_ACCOUNT];
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => $server->accountId];
             break;
         case ChefServer::SCOPE_SCALR:
             $criteria[] = ['level' => ChefServer::LEVEL_SCALR];
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => null];
             break;
     }
     if (ChefServer::findOne($criteria)) {
         $validator->addError('url', 'Url must be unique within current scope');
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     $authKey = str_replace("\r\n", "\n", $authKey);
     $vAuthKey = str_replace("\r\n", "\n", $vAuthKey);
     $server->url = $url;
     $server->username = $username;
     $server->vUsername = $vUsername;
     $server->authKey = $this->getCrypto()->encrypt($authKey);
     $server->vAuthKey = $this->getCrypto()->encrypt($vAuthKey);
     $chef = Scalr_Service_Chef_Client::getChef($server->url, $server->username, $authKey);
     $response = $chef->listCookbooks();
     $chef2 = Scalr_Service_Chef_Client::getChef($server->url, $server->vUsername, $vAuthKey);
     $clientName = 'scalr-temp-client-' . rand(10000, 99999);
     $response = $chef2->createClient($clientName);
     $response2 = $chef->removeClient($clientName);
     $server->save();
     $this->response->data(array('server' => $this->getServerData($server)));
     $this->response->success('Chef server successfully saved');
 }
Ejemplo n.º 5
0
 /**
  * @param string $webhookId
  * @param string $name
  * @param JsonData $endpoints
  * @param JsonData $events
  * @param JsonData $farms
  * @param int $timeout
  * @param int $attempts
  * @param boolean $skipPrivateGv
  * @param string $postData
  * @throws Exception
  */
 public function xSaveAction($webhookId, $name, JsonData $endpoints, JsonData $events, JsonData $farms, $timeout = 3, $attempts = 3, $skipPrivateGv = 0, $postData = '')
 {
     if (!$webhookId) {
         $webhook = new WebhookConfig();
         $webhook->setScope($this->request->getScope(), $this->user->getAccountId(), $this->getEnvironmentId(true));
     } else {
         $webhook = WebhookConfig::findPk($webhookId);
         if (!$this->canManageWebhook($webhook)) {
             throw new Scalr_Exception_Core('Insufficient permissions to edit webhook');
         }
     }
     $validator = new Validator();
     $validator->validate($name, 'name', Validator::NOEMPTY);
     if (!$validator->isValid($this->response)) {
         return;
     }
     $webhook->name = $name;
     $webhook->postData = $postData;
     $webhook->skipPrivateGv = $skipPrivateGv;
     $webhook->timeout = $timeout;
     $webhook->attempts = $attempts;
     $webhook->save();
     //save endpoints
     $endpoints = (array) $endpoints;
     foreach (WebhookConfigEndpoint::findByWebhookId($webhook->webhookId) as $webhookConfigEndpoint) {
         $index = array_search($webhookConfigEndpoint->endpointId, $endpoints);
         if ($index === false) {
             $webhookConfigEndpoint->delete();
         } else {
             unset($endpoints[$index]);
         }
     }
     if (!empty($endpoints)) {
         $criteria = [];
         $criteria[] = ['endpointId' => ['$in' => $endpoints]];
         switch ($this->request->getScope()) {
             case WebhookConfig::SCOPE_ENVIRONMENT:
                 $criteria[] = ['$or' => [['$and' => [['accountId' => $this->user->getAccountId()], ['envId' => $this->getEnvironmentId()], ['level' => WebhookConfig::LEVEL_ENVIRONMENT]]], ['$and' => [['accountId' => $this->user->getAccountId()], ['envId' => null], ['level' => WebhookConfig::LEVEL_ACCOUNT]]], ['$and' => [['accountId' => null], ['envId' => null], ['level' => WebhookConfig::LEVEL_SCALR]]]]];
                 break;
             case WebhookConfig::SCOPE_ACCOUNT:
                 $criteria[] = ['$or' => [['$and' => [['accountId' => $this->user->getAccountId()], ['envId' => null], ['level' => WebhookConfig::LEVEL_ACCOUNT]]], ['$and' => [['accountId' => null], ['envId' => null], ['level' => WebhookConfig::LEVEL_SCALR]]]]];
                 break;
             case WebhookConfig::SCOPE_SCALR:
                 $criteria[] = ['level' => WebhookConfig::LEVEL_SCALR];
                 $criteria[] = ['envId' => null];
                 $criteria[] = ['accountId' => null];
                 break;
         }
         foreach (WebhookEndpoint::find($criteria) as $endpoint) {
             $configEndpoint = new WebhookConfigEndpoint();
             $configEndpoint->webhookId = $webhook->webhookId;
             $configEndpoint->setEndpoint($endpoint);
             $configEndpoint->save();
         }
     }
     //save events
     $allEvents = $this->getEventsList();
     $events = (array) $events;
     foreach (WebhookConfigEvent::findByWebhookId($webhook->webhookId) as $event) {
         $index = array_search($event->eventType, $events);
         if ($index === false) {
             if (isset($allEvents[$event->eventType])) {
                 //20486-rebundlecomplete-emails - we shouldn't remove some events(RebundleComplete...)
                 $event->delete();
             }
         } else {
             unset($events[$index]);
         }
     }
     foreach ($events as $event) {
         /*if (!isset(EVENT_TYPE::getScriptingEvents()[$event])) {
               continue;
           }*/
         $configEvent = new WebhookConfigEvent();
         $configEvent->webhookId = $webhook->webhookId;
         $configEvent->eventType = $event;
         $configEvent->save();
     }
     //save farms
     $farms = (array) $farms;
     if (empty($farms)) {
         $farms = [0];
     }
     foreach (WebhookConfigFarm::findByWebhookId($webhook->webhookId) as $farm) {
         $index = array_search($farm->farmId, $farms);
         if ($index === false) {
             $farm->delete();
         } else {
             unset($farms[$index]);
         }
     }
     foreach ($farms as $farmId) {
         $configFarm = new WebhookConfigFarm();
         $configFarm->webhookId = $webhook->webhookId;
         $configFarm->farmId = $farmId;
         $configFarm->save();
     }
     $endpoints = [];
     foreach ($webhook->getEndpoints() as $endpoint) {
         $endpoints[] = $endpoint->endpointId;
     }
     $events = [];
     foreach ($webhook->getEvents() as $event) {
         $events[] = $event->eventType;
     }
     $farms = [];
     foreach ($webhook->getFarms() as $farm) {
         if ($farm->farmId) {
             $farms[] = $farm->farmId;
         }
     }
     $this->response->success('Webhook successfully saved');
     $this->response->data(array('webhook' => array('webhookId' => $webhook->webhookId, 'name' => $webhook->name, 'postData' => $webhook->postData, 'timeout' => $webhook->timeout, 'attempts' => $webhook->attempts, 'skipPrivateGv' => $webhook->skipPrivateGv, 'endpoints' => $endpoints, 'events' => $events, 'farms' => $farms, 'scope' => $webhook->getScope())));
 }
Ejemplo n.º 6
0
 /**
  * xSaveAction
  *
  * @param string $ccId
  * @param string $projectId
  * @param string $name
  * @param string $description
  * @param string $billingCode
  * @param string $leadEmail
  * @param int $shared
  * @param int $accountId optional
  * @param bool $checkAccountAccessToCc optional
  * @param bool $grantAccountAccessToCc optional
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xSaveAction($ccId, $projectId, $name, $description, $billingCode, $leadEmail, $shared, $accountId = null, $checkAccountAccessToCc = true, $grantAccountAccessToCc = false)
 {
     $validator = new Validator();
     $validator->validate($name, 'name', Validator::NOEMPTY);
     if ($projectId) {
         $project = $this->getContainer()->analytics->projects->get($projectId);
         if (!$project) {
             throw new Scalr_UI_Exception_NotFound();
         }
     } else {
         $project = new ProjectEntity();
         $project->createdById = $this->user->id;
         $project->createdByEmail = $this->user->getEmail();
         $cc = $this->getContainer()->analytics->ccs->get($ccId);
         if (!$cc) {
             $validator->addError('ccId', 'Cost center ID should be set');
         }
         $project->ccId = $ccId;
     }
     if ($shared == ProjectEntity::SHARED_WITHIN_ACCOUNT) {
         $project->shared = ProjectEntity::SHARED_WITHIN_ACCOUNT;
         $project->accountId = $accountId;
     } elseif ($shared == ProjectEntity::SHARED_WITHIN_CC) {
         $project->shared = ProjectEntity::SHARED_WITHIN_CC;
         $project->accountId = null;
     } else {
         throw new Scalr_UI_Exception_NotFound();
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     if ($project->shared == ProjectEntity::SHARED_WITHIN_ACCOUNT) {
         if (!AccountCostCenterEntity::findOne([['accountId' => $project->accountId], ['ccId' => $ccId]])) {
             if ($checkAccountAccessToCc) {
                 $this->response->data(['ccIsNotAllowedToAccount' => true]);
                 $this->response->failure();
                 return;
             } elseif ($grantAccountAccessToCc) {
                 //give account access to cc
                 $accountCcEntity = new AccountCostCenterEntity($project->accountId, $ccId);
                 $accountCcEntity->save();
             }
         }
     }
     $project->name = $name;
     $this->db->BeginTrans();
     try {
         $project->save();
         //NOTE please take into account the presence of the usage->createHostedScalrAccountCostCenter() method
         $project->saveProperty(ProjectPropertyEntity::NAME_BILLING_CODE, $billingCode);
         $project->saveProperty(ProjectPropertyEntity::NAME_DESCRIPTION, $description);
         $project->saveProperty(ProjectPropertyEntity::NAME_LEAD_EMAIL, $leadEmail);
         $this->db->CommitTrans();
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw $e;
     }
     $this->response->data(['project' => $this->getProjectData($project)]);
     $this->response->success('Project has been successfully saved');
 }
Ejemplo n.º 7
0
 /**
  * @param  int     $accountId
  * @param  RawData $password
  * @param  RawData $currentPassword
  * @throws Exception
  */
 public function xSaveOwnerPasswordAction($accountId, RawData $password, RawData $currentPassword)
 {
     $account = new Scalr_Account();
     $account->loadById($accountId);
     $password = (string) $password;
     $validator = new Validator();
     $validator->addErrorIf(!$this->user->checkPassword($currentPassword), "currentPassword", "Invalid password");
     $validator->validate($password, "password", Validator::PASSWORD, ['admin']);
     if ($validator->isValid($this->response)) {
         $user = $account->getOwner();
         $user->updatePassword($password);
         $user->save();
         // Send notification E-mail
         $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_admin_notification.eml', array('{{fullname}}' => $user->fullname ? $user->fullname : $user->getEmail(), '{{administratorFullName}}' => $this->user->fullname ? $this->user->fullname : $this->user->getEmail()), $user->getEmail(), $user->fullname);
         $this->response->success('Password successfully updated');
     }
 }
Ejemplo n.º 8
0
 /**
  * @param int $id
  * @param string $name
  * @param string $description
  * @param int $isSync
  * @param bool $allowScriptParameters
  * @param int $envId optional
  * @param int $timeout optional
  * @param int $version
  * @param RawData $content
  * @param string $tags
  * @param string $uploadType optional
  * @param string $uploadUrl optional
  * @param FileUploadData $uploadFile optional
  * @param bool $checkScriptParameters optional
  * @throws Scalr_UI_Exception_NotFound
  * @throws Scalr_Exception_InsufficientPermissions
  * @throws Exception
  */
 public function xSaveAction($id, $name, $description, $isSync = 0, $allowScriptParameters = false, $envId = NULL, $timeout = NULL, $version, RawData $content, $tags, $uploadType = NULL, $uploadUrl = NULL, FileUploadData $uploadFile = NULL, $checkScriptParameters = false)
 {
     $this->request->restrictAccess('SCRIPTS', 'MANAGE');
     $validator = new Validator();
     $validator->validate($name, 'name', Validator::NOEMPTY);
     if ($uploadType && $uploadType == 'URL') {
         $validator->validate($uploadUrl, 'uploadUrl', Validator::URL);
         if (!$validator->isValid($this->response)) {
             return;
         }
     }
     if ($uploadType) {
         $content = false;
         if ($uploadType == 'URL') {
             $content = @file_get_contents($uploadUrl);
             $validator->validate($content, 'uploadUrl', Validator::NOEMPTY, [], 'Invalid source');
         } else {
             if ($uploadType == 'File') {
                 $content = $uploadFile;
                 $validator->validate($content, 'uploadFile', Validator::NOEMPTY, [], 'Invalid source');
             } else {
                 $validator->addError('uploadType', 'Invalid source for script');
             }
         }
     }
     $envId = $this->getEnvironmentId(true);
     $content = str_replace("\r\n", "\n", $content);
     $tagsResult = [];
     foreach (explode(',', $tags) as $t) {
         $t = trim($t);
         if ($t) {
             if (!preg_match('/^[a-zA-Z0-9-]{3,10}$/', $t)) {
                 $validator->addError('tags', sprintf('Invalid name for tag: %s', $t));
             }
             $tagsResult[] = $t;
         }
     }
     $tags = $tagsResult;
     $criteria = [];
     $criteria[] = ['name' => $name];
     if ($id) {
         $criteria[] = ['id' => ['$ne' => $id]];
     }
     switch ($this->request->getScope()) {
         case Script::SCOPE_ENVIRONMENT:
             $criteria[] = ['envId' => $envId];
             $criteria[] = ['accountId' => $this->user->getAccountId()];
             break;
         case Script::SCOPE_ACCOUNT:
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => $this->user->getAccountId()];
             break;
         case Script::SCOPE_SCALR:
             $criteria[] = ['envId' => null];
             $criteria[] = ['accountId' => null];
             break;
     }
     if (Script::findOne($criteria)) {
         $validator->addError('name', 'Script name must be unique within current scope');
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     /* @var $script Script */
     if ($id) {
         $script = Script::findPk($id);
         if (!$script) {
             throw new Scalr_UI_Exception_NotFound();
         }
         $script->checkPermission($this->user, $envId);
         if (!$script->accountId && $this->user->getType() != Scalr_Account_User::TYPE_SCALR_ADMIN) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
         if (!$script->envId && $this->request->getScope() == ScopeInterface::SCOPE_ENVIRONMENT) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
     } else {
         $script = new Script();
         $script->accountId = $this->user->getAccountId() ?: NULL;
         $script->createdById = $this->user->getId();
         $script->createdByEmail = $this->user->getEmail();
         $script->envId = $envId;
         $version = 1;
     }
     //check variables in script content
     if (!$id && $checkScriptParameters && !$allowScriptParameters) {
         $scriptHasParameters = Script::hasVariables($content);
         if (!$scriptHasParameters) {
             /* @var $scriptVersion ScriptVersion */
             foreach ($script->getVersions() as $scriptVersion) {
                 if ($scriptVersion->version != $version) {
                     $scriptHasParameters = Script::hasVariables($scriptVersion->content);
                     if ($scriptHasParameters) {
                         break;
                     }
                 }
             }
         }
         if ($scriptHasParameters) {
             $this->response->data(['showScriptParametersConfirmation' => true]);
             $this->response->failure();
             return;
         }
     }
     $script->name = $name;
     $script->description = $description;
     $script->timeout = $timeout ? $timeout : NULL;
     $script->isSync = $isSync == 1 ? 1 : 0;
     $script->allowScriptParameters = $allowScriptParameters ? 1 : 0;
     $script->os = !strncmp($content, '#!cmd', strlen('#!cmd')) || !strncmp($content, '#!powershell', strlen('#!powershell')) ? Script::OS_WINDOWS : Script::OS_LINUX;
     $script->save();
     $scriptVersion = NULL;
     if ($version) {
         $scriptVersion = $script->getVersion($version);
     }
     if (!$scriptVersion && $script->getLatestVersion()->content !== $content) {
         $scriptVersion = new ScriptVersion();
         $scriptVersion->scriptId = $script->id;
         $scriptVersion->version = $script->getLatestVersion()->version + 1;
     }
     if ($scriptVersion) {
         $scriptVersion->changedById = $this->user->getId();
         $scriptVersion->changedByEmail = $this->user->getEmail();
         $scriptVersion->content = $content;
         $scriptVersion->save();
     }
     if ($this->user->getAccountId()) {
         Tag::setTags($tags, $this->user->getAccountId(), Tag::RESOURCE_SCRIPT, $script->id);
     }
     $this->response->success('Script successfully saved');
     $this->response->data(['script' => array_merge($this->getScript($script), $this->getScriptInfo($script))]);
 }
Ejemplo n.º 9
0
 /**
  * xSaveAction
  *
  * @param string $projectId
  * @param string $name
  * @param string $description
  * @param string $billingCode
  * @param string $leadEmail
  * @param string $ccId optional
  * @throws \InvalidArgumentException
  * @throws Scalr_Exception_InsufficientPermissions
  * @throws Scalr_UI_Exception_NotFound
  */
 public function xSaveAction($projectId, $name, $description, $billingCode, $leadEmail, $ccId = null)
 {
     $this->request->restrictAccess(Acl::RESOURCE_ANALYTICS_ACCOUNT, Acl::PERM_ANALYTICS_ACCOUNT_MANAGE_PROJECTS);
     $validator = new Validator();
     $validator->validate($name, 'name', Validator::NOEMPTY);
     if (!$validator->isValid($this->response)) {
         return;
     }
     if ($projectId) {
         $project = $this->getContainer()->analytics->projects->get($projectId);
         if (!$project) {
             throw new Scalr_UI_Exception_NotFound();
         } elseif ($project->shared != ProjectEntity::SHARED_WITHIN_ACCOUNT || $project->accountId != $this->user->getAccountId()) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
     } else {
         $project = new ProjectEntity();
         if ($this->request->getScope() == 'environment') {
             $project->ccId = $this->getEnvironment()->getPlatformConfigValue(\Scalr_Environment::SETTING_CC_ID);
         } else {
             $project->ccId = $ccId;
         }
         $cc = $this->getContainer()->analytics->ccs->get($project->ccId);
         if (!empty($cc)) {
             if ($cc->getProperty(CostCentrePropertyEntity::NAME_LOCKED) == 1) {
                 throw new Scalr_Exception_InsufficientPermissions();
             }
             $email = $cc->getProperty(CostCentrePropertyEntity::NAME_LEAD_EMAIL);
             $emailData = ['projectName' => $name, 'ccName' => $cc->name];
         } else {
             throw new Scalr_UI_Exception_NotFound();
         }
         $project->shared = ProjectEntity::SHARED_WITHIN_ACCOUNT;
         $project->accountId = $this->user->getAccountId();
         $project->createdById = $this->user->id;
         $project->createdByEmail = $this->user->getEmail();
     }
     $project->name = $name;
     $this->db->BeginTrans();
     try {
         $project->save();
         //NOTE please take into account the presence of the usage->createHostedScalrAccountCostCenter() method
         $project->saveProperty(ProjectPropertyEntity::NAME_BILLING_CODE, $billingCode);
         $project->saveProperty(ProjectPropertyEntity::NAME_DESCRIPTION, $description);
         $project->saveProperty(ProjectPropertyEntity::NAME_LEAD_EMAIL, $leadEmail);
         $this->db->CommitTrans();
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw $e;
     }
     if (!$projectId && !empty($email)) {
         \Scalr::getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/analytics_on_project_add.eml.php', $emailData, $email);
     }
     $this->response->data(['project' => $this->getProjectData($project)]);
     $this->response->success('Project has been successfully saved');
 }
Ejemplo n.º 10
0
 /**
  * @param $password
  * @param $cpassword
  * @param $securityIpWhitelist
  */
 public function xSecuritySaveAction($password, $cpassword, $securityIpWhitelist)
 {
     $validator = new Validator();
     $validator->validate($password, 'password', Validator::NOEMPTY);
     $validator->validate($cpassword, 'cpassword', Validator::NOEMPTY);
     $validator->addErrorIf($password && $cpassword && $password != $cpassword, ['password', 'cpassword'], 'Two passwords are not equal');
     $subnets = array();
     $securityIpWhitelist = trim($securityIpWhitelist);
     if ($securityIpWhitelist) {
         $whitelist = explode(',', $securityIpWhitelist);
         foreach ($whitelist as $mask) {
             $sub = Scalr_Util_Network::convertMaskToSubnet($mask);
             if ($sub) {
                 $subnets[] = $sub;
             } else {
                 $validator->addError('securityIpWhitelist', sprintf('Not valid mask: %s', $mask));
             }
         }
     }
     if (count($subnets) && !Scalr_Util_Network::isIpInSubnets($this->request->getRemoteAddr(), $subnets)) {
         $validator->addError('securityIpWhitelist', 'New IP access whitelist doesn\'t correspond your current IP address');
     }
     if ($validator->isValid($this->response)) {
         $updateSession = false;
         if ($password != '******') {
             $this->user->updatePassword($password);
             $updateSession = true;
         }
         $this->user->setVar(Scalr_Account_User::VAR_SECURITY_IP_WHITELIST, count($subnets) ? serialize($subnets) : '');
         $this->user->save();
         if ($updateSession) {
             Scalr_Session::create($this->user->getId());
         }
         $this->response->success('Security settings successfully updated');
     }
 }
Ejemplo n.º 11
0
 /**
  * Add or update announcement message
  *
  * @param  string  $msg   Announcement's text
  * @param  string  $title Announcement's title
  * @param  int     $id    optional Announcement's ID
  * @throws Exception
  * @throws Scalr_Exception_Core
  * @throws Scalr_Exception_InsufficientPermissions
  * @throws \Scalr\Exception\ModelException
  */
 public function xSaveAction($msg, $title, $id = null)
 {
     $this->request->restrictAccess(Acl::RESOURCE_ANNOUNCEMENTS);
     /* @var $announcement Scalr\Model\Entity\Announcement */
     if (empty($id)) {
         $announcement = new Announcement();
         /* @var $user Scalr\Model\Entity\Account\User */
         $user = $this->getUser();
         $announcement->accountId = $user->accountId ?: null;
         $announcement->createdById = $user->id;
         $announcement->createdByEmail = $user->email;
         $announcement->added = new \DateTime();
     } else {
         $announcement = Announcement::findPk($id);
         if (!$announcement) {
             throw new Exception('Announcement was not found');
         }
         $this->request->checkPermissions($announcement, true);
     }
     $validator = new Validator();
     $validator->validate($msg, 'msg', $validator::NOEMPTY);
     $validator->validate($title, 'title', $validator::NOEMPTY);
     $validator->addErrorIf(strlen($title) > 100, 'title', 'Maximum length for this field is 100');
     if (!$validator->isValid($this->response)) {
         return;
     }
     $announcement->title = $title;
     $announcement->msg = $msg;
     $announcement->save();
     $this->response->data(['announcement' => $this->prepareDataForList($announcement)]);
     $this->response->success("Announcement saved");
 }
Ejemplo n.º 12
0
 /**
  * @param RawData $password
  * @param RawData $cpassword
  * @param $securityIpWhitelist
  * @param RawData $currentPassword optional
  */
 public function xSecuritySaveAction(RawData $password, RawData $cpassword, $securityIpWhitelist, RawData $currentPassword = null)
 {
     $validator = new Validator();
     if ($password != '******') {
         $validator->addErrorIf(!$this->user->checkPassword($currentPassword), ['currentPassword'], 'Invalid password');
     }
     $validator->validate($password, 'password', Validator::NOEMPTY);
     $validator->validate($cpassword, 'cpassword', Validator::NOEMPTY);
     $validator->addErrorIf($password && $cpassword && $password != $cpassword, ['password', 'cpassword'], 'Two passwords are not equal');
     $subnets = array();
     $securityIpWhitelist = trim($securityIpWhitelist);
     if ($securityIpWhitelist) {
         $whitelist = explode(',', $securityIpWhitelist);
         foreach ($whitelist as $mask) {
             $sub = Scalr_Util_Network::convertMaskToSubnet($mask);
             if ($sub) {
                 $subnets[] = $sub;
             } else {
                 $validator->addError('securityIpWhitelist', sprintf('Not valid mask: %s', $mask));
             }
         }
     }
     if (count($subnets) && !Scalr_Util_Network::isIpInSubnets($this->request->getRemoteAddr(), $subnets)) {
         $validator->addError('securityIpWhitelist', 'New IP access whitelist doesn\'t correspond your current IP address');
     }
     if ($validator->isValid($this->response)) {
         $updateSession = false;
         if ($password != '******') {
             $this->user->updatePassword($password);
             $updateSession = true;
             // Send notification E-mail
             $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_notification.eml', array('{{fullname}}' => $this->user->fullname ? $this->user->fullname : $this->user->getEmail()), $this->user->getEmail(), $this->user->fullname);
         }
         $this->user->setVar(Scalr_Account_User::VAR_SECURITY_IP_WHITELIST, count($subnets) ? serialize($subnets) : '');
         $this->user->save();
         if ($updateSession) {
             Scalr_Session::create($this->user->getId());
             $this->response->data(['specialToken' => Scalr_Session::getInstance()->getToken()]);
         }
         $this->response->success('Security settings successfully updated');
     }
 }
Ejemplo n.º 13
0
 /**
  * @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");
     }
 }
Ejemplo n.º 14
0
 /**
  * @param int $id
  * @param string $name
  * @param string $description
  * @param int $isSync
  * @param int $envId optional
  * @param int $timeout optional
  * @param int $version
  * @param RawData $content
  * @param string $tags
  * @param string $uploadType optional
  * @param string $uploadUrl optional
  * @param FileUploadData $uploadFile optional
  * @throws Scalr_UI_Exception_NotFound
  * @throws Scalr_Exception_InsufficientPermissions
  * @throws Exception
  */
 public function xSaveAction($id, $name, $description, $isSync = 0, $envId = 2, $timeout = NULL, $version, RawData $content, $tags, $uploadType = NULL, $uploadUrl = NULL, FileUploadData $uploadFile = NULL)
 {
     $this->request->restrictAccess(Acl::RESOURCE_ADMINISTRATION_SCRIPTS, Acl::PERM_ADMINISTRATION_SCRIPTS_MANAGE);
     $validator = new Validator();
     $validator->validate($name, 'name', Validator::NOEMPTY);
     if ($uploadType) {
         $content = false;
         if ($uploadType == 'URL') {
             $content = @file_get_contents($uploadUrl);
             $validator->validate($content, 'uploadUrl', Validator::NOEMPTY, [], 'Invalid source');
         } else {
             if ($uploadType == 'File') {
                 $content = $uploadFile;
                 $validator->validate($content, 'uploadFile', Validator::NOEMPTY, [], 'Invalid source');
             } else {
                 $validator->addError('uploadType', 'Invalid source for script');
             }
         }
     }
     $content = str_replace("\r\n", "\n", $content);
     $tagsResult = [];
     foreach (explode(',', $tags) as $t) {
         $t = trim($t);
         if ($t) {
             if (!preg_match('/^[a-zA-Z0-9-]{3,10}$/', $t)) {
                 $validator->addError('tags', sprintf('Invalid name for tag: %s', $t));
             }
             $tagsResult[] = $t;
         }
     }
     $tags = $tagsResult;
     if (!$validator->isValid($this->response)) {
         return;
     }
     /* @var Script $script */
     if ($id) {
         $script = Script::findPk($id);
         if (!$script) {
             throw new Scalr_UI_Exception_NotFound();
         }
         $script->checkPermission($this->user, $this->getEnvironmentId(true));
         if (!$script->accountId && $this->user->getType() != Scalr_Account_User::TYPE_SCALR_ADMIN) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
     } else {
         $script = new Script();
         $script->accountId = $this->user->getAccountId() ? $this->user->getAccountId() : NULL;
         $script->createdById = $this->user->getId();
         $script->createdByEmail = $this->user->getEmail();
         $version = 1;
     }
     if ($this->user->isScalrAdmin()) {
         $envId = NULL;
     } else {
         if (!in_array($envId, array_map(function ($e) {
             return $e['id'];
         }, $this->user->getEnvironments()))) {
             $envId = NULL;
         }
     }
     $script->name = $name;
     $script->description = $description;
     $script->timeout = $timeout ? $timeout : NULL;
     $script->isSync = $isSync == 1 ? 1 : 0;
     $script->envId = $envId;
     $script->os = !strncmp($content, '#!cmd', strlen('#!cmd')) || !strncmp($content, '#!powershell', strlen('#!powershell')) ? Script::OS_WINDOWS : Script::OS_LINUX;
     $script->save();
     $scriptVersion = NULL;
     if ($version) {
         $scriptVersion = $script->getVersion($version);
     }
     if (!$scriptVersion && $script->getLatestVersion()->content !== $content) {
         $scriptVersion = new ScriptVersion();
         $scriptVersion->scriptId = $script->id;
         $scriptVersion->version = $script->getLatestVersion()->version + 1;
     }
     if ($scriptVersion) {
         $scriptVersion->changedById = $this->user->getId();
         $scriptVersion->changedByEmail = $this->user->getEmail();
         $scriptVersion->content = $content;
         $scriptVersion->save();
     }
     if ($this->user->getAccountId()) {
         Tag::setTags($tags, $this->user->getAccountId(), Tag::RESOURCE_SCRIPT, $script->id);
     }
     $this->response->success('Script successfully saved');
 }
Ejemplo n.º 15
0
 /**
  * @param int     $id
  * @param string  $email
  * @param string  $type
  * @param RawData $password
  * @param string  $status
  * @param string  $fullname
  * @param string  $comments
  * @param RawData $currentPassword optional
  * @throws Scalr_Exception_Core
  * @throws Scalr_Exception_InsufficientPermissions
  */
 public function xSaveAction($id = 0, $email, $type, RawData $password, $status, $fullname, $comments, RawData $currentPassword = null)
 {
     $user = Scalr_Account_User::init();
     $validator = new Validator();
     $isNewUser = empty($id);
     $isExistingPasswordChanged = false;
     $password = (string) $password;
     if (!$isNewUser && $password && !$this->user->checkPassword($currentPassword, false)) {
         $this->response->data(['errors' => ['currentPassword' => 'Invalid password']]);
         $this->response->failure();
         return;
     }
     if ($password || $isNewUser) {
         $validator->validate($password, 'password', Validator::PASSWORD, ['admin']);
     }
     $validator->validate($email, 'email', Validator::NOEMPTY);
     if ($type == User::TYPE_FIN_ADMIN) {
         $validator->validate($email, 'email', Validator::EMAIL);
     }
     if ($isNewUser) {
         $validator->addErrorIf($this->db->GetOne("SELECT EXISTS(SELECT 1 FROM `account_users` WHERE email = ?)", [$email]), 'email', 'This email is already in use.');
     }
     $validator->addErrorIf(!in_array($type, [User::TYPE_SCALR_ADMIN, User::TYPE_FIN_ADMIN]), 'type', 'Type is not valid');
     $validator->addErrorIf(!in_array($status, [User::STATUS_ACTIVE, User::STATUS_INACTIVE]), 'type', 'Status is not valid');
     if (!$validator->isValid($this->response)) {
         return;
     }
     if (!$isNewUser) {
         $user->loadById($id);
         if ($user->getEmail() == 'admin' && $user->getId() != $this->user->getId()) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
         if ($user->getEmail() != 'admin') {
             $user->updateEmail($email);
         }
     } else {
         $user->create($email, $this->user->getAccountId());
         $user->type = $type;
     }
     if ($password) {
         $user->updatePassword($password);
         if (!$isNewUser) {
             $isExistingPasswordChanged = true;
         }
     }
     if ($user->getEmail() != 'admin') {
         $user->status = $status;
         $user->type = $type;
         $user->fullname = $fullname;
         $user->comments = $comments;
     }
     $user->save();
     // Send notification E-mail
     if ($isExistingPasswordChanged) {
         $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_admin_notification.eml', array('{{fullname}}' => $user->fullname ? $user->fullname : $user->getEmail(), '{{administratorFullName}}' => $this->user->fullname ? $this->user->fullname : $this->user->getEmail()), $user->getEmail(), $user->fullname);
     } else {
         if ($isNewUser) {
             $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/user_new_admin_notification.eml', array('{{fullname}}' => $user->fullname ? $user->fullname : $user->getEmail(), '{{subject}}' => $user->type == Scalr_Account_User::TYPE_FIN_ADMIN ? 'Financial Admin for Scalr Cost Analytics' : 'Admin for Scalr', '{{user_type}}' => $user->type == Scalr_Account_User::TYPE_FIN_ADMIN ? 'a Financial Admin' : 'an Admin', '{{link}}' => Scalr::config('scalr.endpoint.scheme') . "://" . Scalr::config('scalr.endpoint.host')), $user->getEmail(), $user->fullname);
         }
     }
     $this->response->success('User successfully saved');
 }
Ejemplo n.º 16
0
 /**
  * @param int $accountId
  * @param RawData $password
  * @param RawData $cpassword
  * @param RawData $currentPassword
  * @throws Exception
  */
 public function xSaveOwnerPasswordAction($accountId, $password, $cpassword, $currentPassword)
 {
     $account = new Scalr_Account();
     $account->loadById($accountId);
     $validator = new Validator();
     $validator->addErrorIf(!$this->user->checkPassword($currentPassword), ['currentPassword'], 'Invalid password');
     $validator->validate($password, 'password', Validator::NOEMPTY);
     $validator->validate($cpassword, 'cpassword', Validator::NOEMPTY);
     $validator->addErrorIf($password && $cpassword && $password != $cpassword, ['password', 'cpassword'], 'Two passwords are not equal');
     if ($validator->isValid($this->response)) {
         $user = $account->getOwner();
         $user->updatePassword($password);
         $user->save();
         // Send notification E-mail
         $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_admin_notification.eml', array('{{fullname}}' => $user->fullname ? $user->fullname : $user->getEmail(), '{{administratorFullName}}' => $this->user->fullname ? $this->user->fullname : $this->user->getEmail()), $user->getEmail(), $user->fullname);
         $this->response->success('Password successfully updated');
     }
 }