/** * Gets the User Entity for the current request * * @return User|null Returns the User entity for the current Request */ public function getUser() { if (empty($this->_user) && $this->user->getId()) { $this->_user = User::findPk($this->user->getId()); } return $this->_user; }
/** * Modify sql query to limit access by only allowable farms * * @param string $query * @param array $args * @param string $prefix optional Prefix for table farms in sql query * @param string $perm optional * @return array */ public function prepareFarmSqlQuery($query, $args, $prefix = '', $perm = null) { $prefix = $prefix ? "{$prefix}." : ''; if (!$this->isAllowed(Acl::RESOURCE_FARMS, $perm)) { $q = []; if ($this->isAllowed(Acl::RESOURCE_TEAM_FARMS, $perm)) { $t = array_map(function ($t) { return $t['id']; }, $this->user->getTeams()); if (count($t)) { $q[] = "{$prefix}team_id IN(" . join(',', $t) . ")"; } } if ($this->isAllowed(Acl::RESOURCE_OWN_FARMS, $perm)) { $q[] = "{$prefix}created_by_id = ?"; $args[] = $this->user->getId(); } if (count($q)) { $query .= ' AND (' . join(' OR ', $q) . ')'; } else { $query .= ' AND false'; // no permissions } } return [$query, $args]; }
/** * Initializes a new farm * * TODO: Rewrite this terrible code. * * @param string $name The name of the farm * @param Scalr_Account_User $user The user * @param int $envId The identifier of the environment * @return DBFarm */ public static function create($name, Scalr_Account_User $user, $envId) { $account = $user->getAccount(); $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1); $dbFarm = new self(); $dbFarm->Status = FARM_STATUS::TERMINATED; $dbFarm->ClientID = $account->id; $dbFarm->EnvID = $envId; $dbFarm->createdByUserId = $user->getId(); $dbFarm->createdByUserEmail = $user->getEmail(); $dbFarm->changedByUserId = $user->getId(); $dbFarm->changedTime = microtime(); $dbFarm->Name = $name; $dbFarm->RolesLaunchOrder = 0; $dbFarm->Comments = ""; $dbFarm->save(); $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40)); return $dbFarm; }
/** * Generate conditions for sql query to limit access by only allowable farms. * Table `farms` should have alias `f`. * * @param string $permissionId optional * @return string */ public function getFarmSqlQuery($permissionId = null) { if (!$this->isAllowed(Acl::RESOURCE_FARMS, $permissionId)) { $q = []; if ($this->isAllowed(Acl::RESOURCE_TEAM_FARMS, $permissionId)) { $q[] = Farm::getUserTeamOwnershipSql($this->user->id); } if ($this->isAllowed(Acl::RESOURCE_OWN_FARMS, $permissionId)) { $q[] = "f.created_by_id = '{$this->user->getId()}'"; } if (count($q)) { $sql = '(' . join(' OR ', $q) . ')'; } else { $sql = '0'; // no permissions } } else { $sql = '1'; // all farms in env } return $sql; }
/** * Migrates an Image to another Cloud Location * * @param string $cloudLocation The cloud location * @param \Scalr_Account_User|\Scalr\Model\Entity\Account\User $user The user object * @return Image * @throws Exception * @throws NotEnabledPlatformException * @throws DomainException */ public function migrateEc2Location($cloudLocation, $user) { if (!$this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2)) { throw new NotEnabledPlatformException("You can migrate image between regions only on EC2 cloud"); } if ($this->cloudLocation == $cloudLocation) { throw new DomainException('Destination region is the same as source one'); } $snap = $this->getEnvironment()->aws($this->cloudLocation)->ec2->image->describe($this->id); if ($snap->count() == 0) { throw new Exception("Image haven't been found on cloud."); } if ($snap->get(0)->toArray()['imageState'] != 'available') { throw new Exception('Image is not in "available" status on cloud and cannot be copied.'); } $this->checkImage(); // re-check properties $aws = $this->getEnvironment()->aws($cloudLocation); $newImageId = $aws->ec2->image->copy($this->cloudLocation, $this->id, $this->name, "Image was copied by Scalr from image: {$this->name}, cloudLocation: {$this->cloudLocation}, id: {$this->id}", null, $cloudLocation); $newImage = new Image(); $newImage->platform = $this->platform; $newImage->cloudLocation = $cloudLocation; $newImage->id = $newImageId; $newImage->name = $this->name; $newImage->architecture = $this->architecture; $newImage->size = $this->size; $newImage->accountId = $this->accountId; $newImage->envId = $this->envId; $newImage->osId = $this->osId; $newImage->source = Image::SOURCE_MANUAL; $newImage->type = $this->type; $newImage->agentVersion = $this->agentVersion; $newImage->createdById = $user->getId(); $newImage->createdByEmail = $user->getEmail(); $newImage->status = Image::STATUS_ACTIVE; $newImage->isScalarized = $this->isScalarized; $newImage->hasCloudInit = $this->hasCloudInit; $newImage->save(); $newImage->setSoftware($this->getSoftware()); return $newImage; }
public function callActionMethod($method) { if ($this->request->getRequestType() == Scalr_UI_Request::REQUEST_TYPE_API) { $apiMethodCheck = false; if (method_exists($this, 'getApiDefinitions')) { $api = $this::getApiDefinitions(); $m = str_replace('Action', '', $method); if (in_array($m, $api)) { $apiMethodCheck = true; } } if (!$apiMethodCheck) { throw new Scalr_UI_Exception_NotFound(); } } /* * Debug action section * Controller::Action => array of filter's params (accountId, userId) or true */ $debug = false; $debugMode = false; $key = get_class($this) . '::' . $method; if ($debug && array_key_exists($key, $debug)) { $value = $debug[$key]; if (is_array($value) && $this->user) { if (isset($value['accountId'])) { if (is_array($value['accountId']) && in_array($this->user->getAccountId(), $value['accountId'])) { $debugMode = true; } if (is_numeric($value['accountId']) && $value['accountId'] == $this->user->getAccountId()) { $debugMode = true; } } if (isset($value['userId'])) { if (is_array($value['userId']) && in_array($this->user->getId(), $value['userId'])) { $debugMode = true; } if (is_numeric($value['userId']) && $value['userId'] == $this->user->getId()) { $debugMode = true; } } } else { $debugMode = true; } } if ($debugMode) { $this->response->debugLog('Server', $_SERVER); $this->response->debugLog('Request', $_REQUEST); $this->response->debugLog('Session', Scalr_Session::getInstance()); } $this->{$method}(); if ($debugMode) { if ($this->response->jsResponseFlag) { $this->response->debugLog('JS Response', $this->response->jsResponse); } try { $message = ''; foreach ($this->response->serverDebugLog as $value) { $message .= $value['key'] . ":\n" . $value['value'] . "\n\n"; } $this->db->Execute('INSERT INTO ui_debug_log (ipaddress, url, report, env_id, account_id, user_id) VALUES(?, ?, ?, ?, ?, ?)', array($this->request->getClientIp(), $key, $message, $this->getEnvironment() ? $this->getEnvironmentId() : 0, $this->user ? $this->user->getAccountId() : 0, $this->user ? $this->user->getId() : 0)); } catch (Exception $e) { } } }
/** * Checks whether the user is allowed to edit specified user * * @param \Scalr_Account_User $user The user to edit * @return boolean Returns true if the user is allowed to edit specified user */ public function canEditUser($user) { return !$this->isTeamUser() && $user->getAccountId() == $this->getAccountId() && ($this->getId() == $user->getId() || $this->isAccountOwner() || $this->isAccountSuperAdmin() && !$user->isAccountOwner() || $this->isAccountAdmin() && !$user->isAccountOwner() && !$user->isAccountSuperAdmin()); }
/** * @param string $newRoleName * @param Scalr_Account_User $user * @param int $envId * @return int * @throws Exception */ public function cloneRole($newRoleName, $user, $envId) { $this->db->BeginTrans(); $accountId = $user->getAccountId(); try { $this->db->Execute("INSERT INTO roles SET\n name = ?,\n origin = ?,\n client_id = ?,\n env_id = ?,\n cat_id = ?,\n description = ?,\n behaviors = ?,\n generation = ?,\n os_id = ?,\n dtadded = NOW(),\n added_by_userid = ?,\n added_by_email = ?\n ", array($newRoleName, $accountId ? ROLE_TYPE::CUSTOM : ROLE_TYPE::SHARED, empty($accountId) ? null : intval($accountId), empty($envId) ? null : intval($envId), $this->catId, $this->description, $this->behaviorsRaw, 2, $this->osId, $user->getId(), $user->getEmail())); $newRoleId = $this->db->Insert_Id(); //Set behaviors foreach ($this->getBehaviors() as $behavior) { $this->db->Execute("INSERT IGNORE INTO role_behaviors SET role_id = ?, behavior = ?", array($newRoleId, $behavior)); } // Set images $rsr7 = $this->db->Execute("SELECT * FROM role_images WHERE role_id = ?", array($this->id)); while ($r7 = $rsr7->FetchRow()) { $this->db->Execute("INSERT INTO role_images SET\n `role_id` = ?,\n `cloud_location` = ?,\n `image_id` = ?,\n `platform` = ?\n ", array($newRoleId, $r7['cloud_location'], $r7['image_id'], $r7['platform'])); } $props = $this->db->Execute("SELECT * FROM role_properties WHERE role_id=?", array($this->id)); while ($p1 = $props->FetchRow()) { $this->db->Execute("\n INSERT INTO role_properties\n SET `role_id` = ?,\n `name`\t= ?,\n `value`\t= ?\n ON DUPLICATE KEY UPDATE\n `value` = ?\n ", array($newRoleId, $p1['name'], $p1['value'], $p1['value'])); } //Set global variables $variables = new Scalr_Scripting_GlobalVariables($this->clientId, $this->envId, ScopeInterface::SCOPE_ROLE); $variables->setValues($variables->getValues($this->id), $newRoleId); //Set scripts $rsr8 = $this->db->Execute("SELECT * FROM role_scripts WHERE role_id = ?", array($this->id)); while ($r8 = $rsr8->FetchRow()) { $this->db->Execute("INSERT INTO role_scripts SET\n role_id = ?,\n event_name = ?,\n target = ?,\n script_id = ?,\n version = ?,\n timeout = ?,\n issync = ?,\n params = ?,\n order_index = ?,\n script_type = ?,\n script_path = ?,\n hash = ?\n ", array($newRoleId, $r8['event_name'], $r8['target'], $r8['script_id'], $r8['version'], $r8['timeout'], $r8['issync'], $r8['params'], $r8['order_index'], $r8['script_type'], $r8['script_path'], CryptoTool::sault(12))); } //Set environments only for account-scope roles if (!empty($accountId) && empty($envId)) { $rsr9 = $this->db->Execute("SELECT * FROM role_environments WHERE role_id = ?", array($this->id)); while ($r9 = $rsr9->FetchRow()) { $this->db->Execute("INSERT INTO role_environments SET\n role_id = ?,\n env_id = ?\n ", array($newRoleId, $r9['env_id'])); } } } catch (Exception $e) { $this->db->RollbackTrans(); throw $e; } $this->db->CommitTrans(); if (!empty($newRoleId)) { $newRole = self::loadById($newRoleId); $newRole->syncAnalyticsTags(); } return $newRoleId; }
public function xLoginAsAction() { if ($this->getParam('accountId')) { $account = new Scalr_Account(); $account->loadById($this->getParam('accountId')); $user = $account->getOwner(); } else { $user = new Scalr_Account_User(); $user->loadById($this->getParam('userId')); } if ($user->status != User::STATUS_ACTIVE) { throw new Exception('User account has been deactivated. You cannot login into it.'); } Scalr_Session::create($user->getId(), $this->user->getId()); try { $envId = $this->getEnvironmentId(true) ?: $user->getDefaultEnvironment()->id; } catch (Exception $e) { $envId = null; } $this->auditLog("user.auth.login", $user, $envId, $this->request->getRemoteAddr(), $this->user->getId()); $this->response->success(); }
public function xLoginAsAction() { if ($this->getParam('accountId')) { $account = new Scalr_Account(); $account->loadById($this->getParam('accountId')); $user = $account->getOwner(); } else { $user = new Scalr_Account_User(); $user->loadById($this->getParam('userId')); } Scalr_Session::create($user->getId(), true); $this->response->success(); }
/** * Gets account roles superposition by specified ID of environment * * @param \Scalr_Account_User|int $user * The user's object or ID of the user * * @param int $envId * The ID of the client's environment * * @param int $accountId * The ID of the client's account * * @return \Scalr\Acl\Role\AccountRoleSuperposition Returns the list of the roles of account level by specified environment */ public function getUserRolesByEnvironment($user, $envId, $accountId) { $ret = new \Scalr\Acl\Role\AccountRoleSuperposition([]); if ($user instanceof \Scalr_Account_User) { $userId = $user->getId(); $ret->setUser($user); } else { $userId = $user; $ret->setUser($userId); } //The teams in which user has ACL role $teamsUserHasAcl = array(); //Selects User's ACLs $res = $this->db->Execute("\n SELECT atu.`team_id`, ar.*\n FROM `acl_account_roles` ar\n JOIN `account_team_user_acls` ua ON ua.`account_role_id` = ar.`account_role_id`\n JOIN `account_team_users` atu ON atu.`id` = ua.`account_team_user_id`\n JOIN `account_team_envs` te ON te.`team_id` = atu.`team_id`\n JOIN `account_teams` at ON at.id = atu.`team_id`\n WHERE atu.`user_id` = ? AND te.`env_id` = ? AND ar.`account_id` = ?\n GROUP BY at.`id`, ar.`account_role_id`\n ", array($userId, $envId, $accountId)); while ($rec = $res->FetchRow()) { $teamsUserHasAcl[$rec['team_id']] = $rec['team_id']; $role = $this->getAccountRoleByRow($rec); $role->setTeamRole(false); $ret[$role->getRoleId()] = $role; } //Selects Team's ACLs where user enters without defined ACL $rs = $this->db->Execute("\n SELECT ar.*\n FROM `account_teams` at\n JOIN `account_team_users` tu ON at.`id` = tu.`team_id`\n JOIN `acl_account_roles` ar ON ar.`account_role_id` = at.`account_role_id` AND ar.`account_id` = at.`account_id`\n JOIN `account_team_envs` te ON te.`team_id` = tu.`team_id`\n WHERE tu.user_id = ? AND te.`env_id` = ? AND at.account_id = ?\n AND at.`account_role_id` IS NOT NULL\n " . (!empty($teamsUserHasAcl) ? "AND at.id NOT IN('" . join("','", array_values($teamsUserHasAcl)) . "')" : "") . "\n ", array($userId, $envId, $accountId)); while ($rec = $rs->FetchRow()) { if (!isset($ret[$rec['account_role_id']])) { $role = $this->getAccountRoleByRow($rec); $role->setTeamRole(true); $ret[$role->getRoleId()] = $role; } } return $ret; }
public function callActionMethod($method) { if ($this->request->getRequestType() == Scalr_UI_Request::REQUEST_TYPE_API) { $apiMethodCheck = false; if (method_exists($this, 'getApiDefinitions')) { $api = $this::getApiDefinitions(); $m = str_replace('Action', '', $method); if (in_array($m, $api)) { $apiMethodCheck = true; } } if (!$apiMethodCheck) { throw new Scalr_UI_Exception_NotFound(); } } /* * Debug action section * Controller::Action => array of filter's params (accountId, userId) or true */ $debug = false; $debugMode = false; $key = get_class($this) . '::' . $method; if ($debug && array_key_exists($key, $debug)) { $value = $debug[$key]; if (is_array($value) && $this->user) { if (isset($value['accountId'])) { if (is_array($value['accountId']) && in_array($this->user->getAccountId(), $value['accountId'])) { $debugMode = true; } if (is_numeric($value['accountId']) && $value['accountId'] == $this->user->getAccountId()) { $debugMode = true; } } if (isset($value['userId'])) { if (is_array($value['userId']) && in_array($this->user->getId(), $value['userId'])) { $debugMode = true; } if (is_numeric($value['userId']) && $value['userId'] == $this->user->getId()) { $debugMode = true; } } } else { $debugMode = true; } } if ($debugMode) { $this->response->debugLog('Server', $_SERVER); $this->response->debugLog('Request', $_REQUEST); $this->response->debugLog('Session', Scalr_Session::getInstance()); } $reflection = new ReflectionMethod($this, $method); if ($reflection->getNumberOfParameters()) { $params = array(); $comment = $reflection->getDocComment(); $matches = array(); $types = array(); if (preg_match_all('/^\\s+\\*\\s+@param\\s+(.*)\\s+\\$([A-Za-z0-9_]+)*.*$/m', $comment, $matches)) { for ($i = 0; $i < count($matches[0]); $i++) { $matches[1][$i] = strtolower(trim($matches[1][$i])); if (in_array($matches[1][$i], array('bool', 'boolean', 'int', 'integer', 'float', 'string', 'array'))) { $types[trim($matches[2][$i])] = $matches[1][$i]; } } } // TODO: else: make some warning to log, otherwise we don't know when type-casting is not working foreach ($reflection->getParameters() as $parameter) { $className = $parameter->getClass() ? $parameter->getClass()->name : NULL; $value = $this->request->getRequestParam($parameter->name); $hasValue = $this->request->hasParam($parameter->name); if ($className) { if (is_subclass_of($className, 'Scalr\\UI\\Request\\ObjectInitializingInterface')) { /* @var ObjectInitializingInterface $className */ $params[] = $className::initFromRequest($className == 'Scalr\\UI\\Request\\FileUploadData' ? $this->request->getFileName($parameter->name) : $value); } else { throw new Scalr\Exception\Http\BadRequestException(sprintf('%s is invalid class in argument', $className)); } } else { $type = $types[$parameter->name] ? $types[$parameter->name] : 'string'; if ($hasValue) { if (in_array($type, ['bool', 'boolean'])) { if (is_numeric($value)) { $value = !empty($value); } else { if (is_string($value)) { $value = $value !== '' && strtolower($value) !== 'false'; } else { $value = (bool) $value; } } } else { if ($type == 'array') { // do not strip value settype($value, $type); } else { $value = $this->request->stripValue($value); settype($value, $type); } } } else { if ($parameter->isDefaultValueAvailable()) { $value = $parameter->getDefaultValue(); } else { throw new Exception(sprintf('Missing required argument: %s', $parameter->name)); } } $params[] = $value; } } call_user_func_array(array($this, $method), $params); } else { $this->{$method}(); } if ($debugMode) { if ($this->response->jsResponseFlag) { $this->response->debugLog('JS Response', $this->response->jsResponse); } try { $message = ''; foreach ($this->response->serverDebugLog as $value) { $message .= $value['key'] . ":\n" . $value['value'] . "\n\n"; } $this->db->Execute('INSERT INTO ui_debug_log (ipaddress, url, report, env_id, account_id, user_id) VALUES(?, ?, ?, ?, ?, ?)', array($this->request->getClientIp(), $key, $message, $this->getEnvironment() ? $this->getEnvironmentId() : 0, $this->user ? $this->user->getAccountId() : 0, $this->user ? $this->user->getId() : 0)); } catch (Exception $e) { } } }
/** * @param Scalr_Account_User $user * @param bool $keepSession */ private function loginUserCreate($user, $keepSession) { $user->updateLastLogin(); Scalr_Session::create($user->getId()); if (Scalr::config('scalr.auth_mode') == 'ldap') { $user->applyLdapGroups($this->ldapGroups); } else { if ($keepSession) { Scalr_Session::keepSession(); } } $this->response->data(array('userId' => $user->getId(), 'specialToken' => Scalr_Session::getInstance()->getToken())); }
/** * @param Scalr_Account_User $user */ private function loginUserCreate($user) { $user->updateLastLogin(); Scalr_Session::create($user->getId()); if (Scalr::config('scalr.auth_mode') == 'ldap') { $user->applyLdapGroups($this->ldapGroups); } else { if ($this->getParam('scalrKeepSession') == 'on') { Scalr_Session::keepSession(); } } $this->response->data(array('userId' => $user->getId())); }
/** * @param $name * @param \Scalr_Account_User $user * @return Script */ public function fork($name, \Scalr_Account_User $user) { $script = new self(); $script->name = $name; $script->description = $this->description; $script->os = $this->os; $script->isSync = $this->isSync; $script->timeout = $this->timeout; $script->accountId = $user->getAccountId() ? $user->getAccountId() : NULL; $script->envId = $this->envId; $script->createdById = $user->getId(); $script->createdByEmail = $user->getEmail(); $script->save(); $version = new ScriptVersion(); $version->scriptId = $script->id; $version->changedById = $user->getId(); $version->changedByEmail = $user->getEmail(); $version->content = $this->getLatestVersion()->content; $version->version = 1; $version->save(); return $script; }
/** * Migrates an Image to another Cloud Location * * @param string $cloudLocation The cloud location * @param \Scalr_Account_User|\Scalr\Model\Entity\Account\User $user The user object * @return Image * @throws NotEnabledPlatformException * @throws DomainException */ public function migrateEc2Location($cloudLocation, $user) { if (!$this->getEnvironment()->isPlatformEnabled(SERVER_PLATFORMS::EC2)) { throw new NotEnabledPlatformException("You can migrate image between regions only on EC2 cloud"); } if ($this->cloudLocation == $cloudLocation) { throw new DomainException('Destination region is the same as source one'); } $this->checkImage(); // re-check properties $aws = $this->getEnvironment()->aws($cloudLocation); $newImageId = $aws->ec2->image->copy($this->cloudLocation, $this->id, $this->name, "Image was copied by Scalr from image: {$this->name}, cloudLocation: {$this->cloudLocation}, id: {$this->id}", null, $cloudLocation); $newImage = new Image(); $newImage->platform = $this->platform; $newImage->cloudLocation = $cloudLocation; $newImage->id = $newImageId; $newImage->name = $this->name; $newImage->architecture = $this->architecture; $newImage->size = $this->size; $newImage->envId = $this->envId; $newImage->osId = $this->osId; $newImage->source = Image::SOURCE_MANUAL; $newImage->type = $this->type; $newImage->agentVersion = $this->agentVersion; $newImage->createdById = $user->getId(); $newImage->createdByEmail = $user->getEmail(); $newImage->status = Image::STATUS_ACTIVE; $newImage->save(); $newImage->setSoftware($this->getSoftware()); return $newImage; }