Generates password that includes at least one symbols from each set:
l - lower case characters
u - upper case characters
d - digits
s - special characters
public static GenerateSecurePassword ( integer $length = 16, array $sets = null, array $enabledSets = null ) : string | ||
$length | integer | optional Password length |
$sets | array | optional User (re-)defined characters sets |
$enabledSets | array | optional Names of enabled sets, if null — all sets are enabled |
return | string | Returns generated password |
public function testMinimumComplexity() { $sets = ['l' => str_split('abcdefghjkmnpqrstuvwxyz'), 'u' => str_split('ABCDEFGHJKMNPQRSTUVWXYZ'), 'd' => str_split('1234567890'), 's' => str_split('!@#$%&*?')]; for ($i = 0; $i < static::TEST_SETS_COUNT; $i++) { $password = str_split(\Scalr::GenerateSecurePassword(static::PASSWORD_LENGTH)); foreach ($sets as $setName => $set) { $this->assertNotEmpty(array_intersect($password, $set), "Password doesn't contain any characters from the group '{$setName}'"); } } }
/** * @test * @depends testXGetListAction */ public function testXSaveAcion() { if (!$this->getUser()->canManageAcl()) { $this->markTestSkipped('Specified test user is not allowed to manage users.'); } $username = self::getTestName(self::USER_FULLNAME); $userEmail = self::_getCreatedUserEmail(); $response = $this->internalRequest('/account/users/xSave', array('email' => $userEmail, 'fullname' => $username, 'password' => \Scalr::GenerateSecurePassword(8))); $this->assertTrue(isset($response['success']) && $response['success'], 'Cannot create user'); $this->assertTrue(isset($response['user']['id'])); $this->assertEquals($userEmail, $response['user']['email']); self::$_createdUserId = $response['user']['id']; $this->removeUser(self::$_createdUserId); self::$_createdUserId = null; }
/** * {@inheritdoc} * @see \Scalr\Modules\PlatformModuleInterface::LaunchServer() */ public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { $environment = $DBServer->GetEnvironmentObject(); $governance = new \Scalr_Governance($DBServer->envId); $azure = $environment->azure(); $subscriptionId = $environment->keychain(SERVER_PLATFORMS::AZURE)->properties[CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID]; if (!$launchOptions) { $dbFarmRole = $DBServer->GetFarmRoleObject(); $DBRole = $dbFarmRole->GetRoleObject(); $launchOptions = new \Scalr_Server_LaunchOptions(); $launchOptions->cloudLocation = $dbFarmRole->CloudLocation; $launchOptions->serverType = $dbFarmRole->GetSetting(FarmRoleSetting::INSTANCE_TYPE); $launchOptions->availZone = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_AVAIL_SET); $launchOptions->imageId = $DBRole->__getNewRoleObject()->getImage(\SERVER_PLATFORMS::AZURE, "")->imageId; $isWindows = $DBRole->getOs()->family == 'windows'; // Set User Data $u_data = ""; foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } $launchOptions->userData = trim($u_data, ";"); $launchOptions->azureResourceGroup = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_RESOURCE_GROUP); $launchOptions->azureStorageAccount = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_STORAGE_ACCOUNT); //Create NIC try { $ipConfigProperties = new IpConfigurationProperties(["id" => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s", $subscriptionId, $launchOptions->azureResourceGroup, $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_VIRTUAL_NETWORK), $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_SUBNET))], "Dynamic"); $publicIpName = null; if ($governance->isEnabled(\SERVER_PLATFORMS::AZURE, \Scalr_Governance::AZURE_NETWORK)) { $usePublicIp = $governance->getValue(\SERVER_PLATFORMS::AZURE, \Scalr_Governance::AZURE_NETWORK, 'use_public_ips'); } if (!isset($usePublicIp)) { $usePublicIp = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_USE_PUBLIC_IPS); } if ($usePublicIp) { //Create Public IP object $publicIpName = "scalr-{$DBServer->serverId}"; $createPublicIpAddressRequest = new CreatePublicIpAddress($launchOptions->cloudLocation, new PublicIpAddressProperties('Dynamic')); $ipCreateResult = $azure->network->publicIPAddress->create($subscriptionId, $launchOptions->azureResourceGroup, $publicIpName, $createPublicIpAddressRequest); } if ($publicIpName) { $ipConfigProperties->publicIPAddress = ["id" => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s", $subscriptionId, $launchOptions->azureResourceGroup, $publicIpName)]; } $nicProperties = new InterfaceProperties([new InterfaceIpConfigurationsData('public1', $ipConfigProperties)]); //Security group $sg = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_SECURITY_GROUPS_LIST); if ($sg) { $sgName = json_decode($sg); if ($sgName) { $sgroup = new SecurityGroupData(); $sgroup->id = sprintf('/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s', $subscriptionId, $launchOptions->azureResourceGroup, $sgName[0]); $nicProperties->setNetworkSecurityGroup($sgroup); } } $createNicData = new CreateInterface($launchOptions->cloudLocation, $nicProperties); $nicResponse = $azure->network->interface->create($subscriptionId, $launchOptions->azureResourceGroup, "scalr-{$DBServer->serverId}", $createNicData); } catch (\Exception $e) { throw new \Exception("Scalr is unable to create NetworkInterface: {$e->getMessage()}"); } $launchOptions->azureNicName = "scalr-{$DBServer->serverId}"; $launchOptions->azurePublicIpName = $publicIpName; } // Configure OS Profile // Make sure that password always have 1 special character. $adminPassword = \Scalr::GenerateSecurePassword(16, ['D' => '.']); $osProfile = new OsProfile('scalr', $adminPassword); $osProfile->computerName = \Scalr::GenerateUID(true); $osProfile->customData = base64_encode(trim($launchOptions->userData)); // Configure Network Profile $networkProfile = ["networkInterfaces" => [["id" => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/networkInterfaces/%s", $subscriptionId, $launchOptions->azureResourceGroup, $launchOptions->azureNicName)]]]; // Configure Storage Profile $osDiskName = "scalr-{$DBServer->serverId}"; $vhd = ['uri' => sprintf("https://%s.blob.core.windows.net/vhds/%s.vhd", $launchOptions->azureStorageAccount, $osDiskName)]; $storageProfile = new StorageProfile(new OsDisk($osDiskName, $vhd, 'FromImage')); if (preg_match("/^([^\\/]+)\\/([^\\/]+)\\/([^\\/]+)\\/([^\\/]+)(\\/(1))?\$/", rtrim($launchOptions->imageId, '/'), $imageChunks)) { $publisher = $imageChunks[1]; $offer = $imageChunks[2]; $sku = $imageChunks[3]; $version = $imageChunks[4]; $isMarketPlaceImage = isset($imageChunks[5]) ? true : false; if ($isMarketPlaceImage) { $plan = new PlanProperties($sku, $publisher, $offer); } $storageProfile->setImageReference(['publisher' => $publisher, 'offer' => $offer, 'sku' => $sku, 'version' => $version]); } else { throw new \Exception("Image definition '{$launchOptions->imageId}' is not supported"); } $vmProps = new VirtualMachineProperties(["vmSize" => $launchOptions->serverType], $networkProfile, $storageProfile, $osProfile); // Set availability set if configured. if ($launchOptions->availZone) { $vmProps->availabilitySet = ['id' => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/availabilitySets/%s", $subscriptionId, $launchOptions->azureResourceGroup, $launchOptions->availZone)]; } $vmData = new CreateVirtualMachine($DBServer->serverId, $launchOptions->cloudLocation, $vmProps); $vmData->tags = $DBServer->getAzureTags(); if (isset($plan)) { $vmData->setPlan($plan); } $azure->compute->virtualMachine->create($subscriptionId, $launchOptions->azureResourceGroup, $vmData); $DBServer->setOsType($isWindows ? 'windows' : 'linux'); $instanceTypeInfo = $this->getInstanceType($launchOptions->serverType, $environment, $launchOptions->cloudLocation); /* @var $instanceTypeInfo CloudInstanceType */ $DBServer->SetProperties([\AZURE_SERVER_PROPERTIES::SERVER_NAME => $DBServer->serverId, \AZURE_SERVER_PROPERTIES::ADMIN_PASSWORD => $adminPassword, \AZURE_SERVER_PROPERTIES::RESOURCE_GROUP => $launchOptions->azureResourceGroup, \AZURE_SERVER_PROPERTIES::CLOUD_LOCATION => $launchOptions->cloudLocation, \AZURE_SERVER_PROPERTIES::AVAIL_SET => $launchOptions->availZone, \AZURE_SERVER_PROPERTIES::NETWORK_INTERFACE => $launchOptions->azureNicName, \AZURE_SERVER_PROPERTIES::PUBLIC_IP_NAME => $launchOptions->azurePublicIpName, \SERVER_PROPERTIES::INFO_INSTANCE_VCPUS => $instanceTypeInfo ? $instanceTypeInfo->vcpus : null]); $params = ['type' => $launchOptions->serverType]; if ($instanceTypeInfo) { $params['instanceTypeName'] = $instanceTypeInfo->name; } $DBServer->imageId = $launchOptions->imageId; $DBServer->update($params); $DBServer->cloudLocation = $launchOptions->cloudLocation; $DBServer->cloudLocationZone = $launchOptions->availZone; // we set server history here $DBServer->getServerHistory()->update(['cloudServerId' => $DBServer->serverId]); return $DBServer; }
/** * @param string $name * @param string $org * @param string $email * @param RawData $password * @param string $agreeTerms * @param string $newBilling * @param string $country * @param string $phone * @param string $lastname * @param string $firstname * @param string $v * @param string $numServers */ public function xCreateAccountAction($name = '', $org = '', $email = '', RawData $password = null, $agreeTerms = '', $newBilling = '', $country = '', $phone = '', $lastname = '', $firstname = '', $v = '', $numServers = '', $beta = 0) { if (!\Scalr::config('scalr.billing.enabled')) { header("HTTP/1.0 403 Forbidden"); exit; } $validator = new Validator(); if ($v == 2) { $validator->validate($firstname, "firstname", Validator::NOEMPTY, [], "First name is required"); $validator->validate($lastname, "lastname", Validator::NOEMPTY, [], "Last name is required"); $name = $firstname . " " . $lastname; } else { $validator->validate($name, "name", Validator::NOEMPTY, [], "Account name is required"); } if ($password == '') { $password = \Scalr::GenerateSecurePassword(User::PASSWORD_ADMIN_LENGTH); } $validator->validate($email, "email", Validator::EMAIL); $validator->validate($password, "password", Validator::PASSWORD, ['admin']); $validator->addErrorIf($this->db->GetOne("SELECT EXISTS(SELECT * FROM account_users WHERE email = ?)", [$email]), "email", "E-mail already exists in the database"); $validator->validate($agreeTerms, "agreeTerms", Validator::NOEMPTY, [], "You haven't accepted terms and conditions"); $errors = $validator->getErrors(true); if (empty($errors)) { $account = Scalr_Account::init(); $account->name = $org ? $org : $name; $account->status = Scalr_Account::STATUS_ACTIVE; $account->save(); $user = $account->createUser($email, $password, Scalr_Account_User::TYPE_ACCOUNT_OWNER); $user->fullname = $name; $user->save(); if ($this->getContainer()->analytics->enabled) { $analytics = $this->getContainer()->analytics; //Default Cost Center should be assigned $cc = $analytics->ccs->get($analytics->usage->autoCostCentre()); //Assigns account with Cost Center $accountCcEntity = new AccountCostCenterEntity($account->id, $cc->ccId); $accountCcEntity->save(); } //Creates Environment. It will be associated with the Cost Center itself. $account->createEnvironment("Environment 1"); $account->initializeAcl(); if ($v == 2) { $user->setSetting('website.phone', $phone); $user->setSetting('website.country', $country); $user->setSetting('website.num_servers', $numServers); } /** * Limits */ $url = Scalr::config('scalr.endpoint.scheme') . "://" . Scalr::config('scalr.endpoint.host'); try { $billing = new Scalr_Billing(); $billing->loadByAccount($account); $billing->createSubscription(Scalr_Billing::PAY_AS_YOU_GO, "", "", "", ""); } catch (Exception $e) { $account->delete(); header("Location: {$url}/order/?error={$e->getMessage()}"); exit; } if ($_COOKIE['__utmz']) { $gaParser = new Scalr_Service_GoogleAnalytics_Parser(); $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_CONTENT] = $gaParser->campaignContent; $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_MEDIUM] = $gaParser->campaignMedium; $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_NAME] = $gaParser->campaignName; $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_SOURCE] = $gaParser->campaignSource; $clientSettings[CLIENT_SETTINGS::GA_CAMPAIGN_TERM] = $gaParser->campaignTerm; $clientSettings[CLIENT_SETTINGS::GA_FIRST_VISIT] = $gaParser->firstVisit; $clientSettings[CLIENT_SETTINGS::GA_PREVIOUS_VISIT] = $gaParser->previousVisit; $clientSettings[CLIENT_SETTINGS::GA_TIMES_VISITED] = $gaParser->timesVisited; } if (!empty($clientSettings)) { foreach ($clientSettings as $k => $v) { $account->setSetting($k, $v); } } try { $this->db->Execute("\n INSERT INTO default_records\n SELECT null, '{$account->id}', rtype, ttl, rpriority, rvalue, rkey\n FROM default_records\n WHERE clientid='0'\n "); } catch (Exception $e) { } $clientinfo = array('fullname' => $name, 'firstname' => $firstname ? $firstname : $name, 'email' => $email, 'password' => $password); //Sends welcome email $this->getContainer()->mailer->setFrom('*****@*****.**', 'Scalr')->setHtml()->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/welcome.html.php', array('firstName' => htmlspecialchars($clientinfo['firstname']), 'password' => htmlspecialchars($clientinfo['password']), "siteUrl" => htmlspecialchars($url), "wikiUrl" => htmlspecialchars(\Scalr::config('scalr.ui.wiki_url')), "supportUrl" => htmlspecialchars(\Scalr::config('scalr.ui.support_url')), "isUrl" => preg_match('/^http(s?):\\/\\//i', \Scalr::config('scalr.ui.support_url'))), $email); $user->getAccount()->setSetting(Scalr_Account::SETTING_IS_TRIAL, 1); //AutoLogin $user->updateLastLogin(); Scalr_Session::create($user->getId()); Scalr_Session::keepSession(); if ($beta != 1) { $this->response->setRedirect("{$url}/thanks.html"); } else { $this->response->data(array('accountId' => $user->getAccountId())); } } else { if ($beta == 1) { header("HTTP/1.0 400 Bad request"); print json_encode($errors); exit; } else { $error = array_values($errors)[0]; $this->response->setRedirect("{$url}/order/?error={$error}"); } } }
public function xSaveAction() { $this->request->defineParams(array('teams' => array('type' => 'json'), 'action', 'password' => array('type' => 'string', 'rawValue' => true), 'currentPassword' => array('type' => 'string', 'rawValue' => true))); $newUser = $existingPasswordChanged = $sendResetLink = false; $user = Scalr_Account_User::init(); $validator = new Validator(); $id = (int) $this->getParam('id'); if ($id) { $user->loadById($id); } else { if ($this->getContainer()->config->get('scalr.auth_mode') == 'ldap') { throw new Exception("Adding new users is not supported with LDAP user management"); } $newUser = true; } if ($this->getContainer()->config->get('scalr.auth_mode') != 'ldap') { $email = $this->getParam('email'); if (($isEmailValid = $validator->validateEmail($email)) !== true) { throw new Scalr_Exception_Core($isEmailValid); } $password = $this->getParam('password'); if (empty($password) && ($this->request->hasParam('password') || $newUser)) { if ($user->id == $this->user->id) { $this->response->data(['errors' => ['password' => 'You cannot reset password for yourself']]); $this->response->failure(); return; } $password = Scalr::GenerateSecurePassword($user->isAccountAdmin() || $user->isAccountOwner() ? User::PASSWORD_ADMIN_LENGTH : User::PASSWORD_USER_LENGTH); $sendResetLink = true; } else { if ($this->request->hasParam('password') && ($isPasswordValid = $validator->validatePassword($password, $user->isAccountAdmin() || $user->isAccountOwner() ? ['admin'] : [])) !== true) { $this->response->data(['errors' => ['password' => $isPasswordValid]]); $this->response->failure(); return; } if (!empty($password)) { $existingPasswordChanged = true; } } if (!$newUser && ($sendResetLink || $existingPasswordChanged) && $this->request->hasParam('password') && !$this->user->checkPassword($this->getParam('currentPassword'), false)) { $this->response->data(['errors' => ['currentPassword' => 'Invalid password']]); $this->response->failure(); return; } if ($id) { if (!$this->user->canEditUser($user)) { throw new Scalr_Exception_InsufficientPermissions(); } $user->updateEmail($email); } else { $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_USERS, 1); $user->type = Scalr_Account_User::TYPE_TEAM_USER; $user->create($email, $this->user->getAccountId()); } if (!empty($password)) { $user->updatePassword($password); } } if ($user->getId() != $this->user->getId() && in_array($this->getParam('status'), array(Scalr_Account_User::STATUS_ACTIVE, Scalr_Account_User::STATUS_INACTIVE))) { $user->status = $this->getParam('status'); } if (!$user->isAccountOwner()) { if ($this->getParam('isAccountAdmin')) { if ($this->user->isAccountOwner()) { $user->type = $this->getParam('isAccountSuperAdmin') ? Scalr_Account_User::TYPE_ACCOUNT_SUPER_ADMIN : Scalr_Account_User::TYPE_ACCOUNT_ADMIN; } else { if ($this->user->isAccountAdmin() && $user->type != Scalr_Account_User::TYPE_ACCOUNT_SUPER_ADMIN) { $user->type = Scalr_Account_User::TYPE_ACCOUNT_ADMIN; } } } else { $user->type = Scalr_Account_User::TYPE_TEAM_USER; } } $user->fullname = $this->getParam('fullname'); $user->comments = $this->getParam('comments'); $user->save(); if (!empty($password)) { $user->setSetting(Scalr_Account::SETTING_OWNER_PWD_RESET_HASH, ""); } $user->setAclRoles($this->getParam('teams')); if ($this->getParam('enableApi')) { $keys = Scalr::GenerateAPIKeys(); $user->setSetting(Scalr_Account_User::SETTING_API_ENABLED, true); $user->setSetting(Scalr_Account_User::SETTING_API_ACCESS_KEY, $keys['id']); $user->setSetting(Scalr_Account_User::SETTING_API_SECRET_KEY, $keys['key']); } $creatorName = $this->user->fullname; if (empty($creatorName)) { $creatorName = $this->user->isAccountOwner() ? 'Account owner' : ($this->user->isAccountAdmin() ? 'Account admin' : 'Team user'); } if ($newUser) { try { $clientinfo = array('fullname' => $user->fullname, 'firstname' => $user->fullname, 'email' => $user->getEmail(), 'password' => $password); $url = Scalr::config('scalr.endpoint.scheme') . "://" . Scalr::config('scalr.endpoint.host'); $res = $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/referral.eml.php', array("creatorName" => $creatorName, "clientFirstname" => $clientinfo['firstname'], "email" => $clientinfo['email'], "password" => $clientinfo['password'], "siteUrl" => $url, "wikiUrl" => \Scalr::config('scalr.ui.wiki_url'), "supportUrl" => \Scalr::config('scalr.ui.support_url'), "isUrl" => preg_match('/^http(s?):\\/\\//i', \Scalr::config('scalr.ui.support_url'))), $user->getEmail()); } catch (Exception $e) { } } elseif ($sendResetLink) { try { $hash = $this->getCrypto()->sault(10); $url = Scalr::config('scalr.endpoint.scheme') . "://" . Scalr::config('scalr.endpoint.host'); $user->setSetting(Scalr_Account::SETTING_OWNER_PWD_RESET_HASH, $hash); $clientinfo = array('email' => $user->getEmail(), 'fullname' => $user->fullname); $res = $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/user_account_confirm.eml', array("{{fullname}}" => $clientinfo['fullname'], "{{pwd_link}}" => "{$url}/?resetPasswordHash={$hash}"), $clientinfo['email'], $clientinfo['fullname']); } catch (Exception $e) { } } else { if ($existingPasswordChanged) { // Send notification E-mail $this->getContainer()->mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/password_change_notification.eml', array('{{fullname}}' => $user->fullname ? $user->fullname : $user->getEmail()), $user->getEmail(), $user->fullname); } } $userTeams = array(); $troles = $this->getContainer()->acl->getUserRoleIdsByTeam($user->id, array_map(create_function('$v', 'return $v["id"];'), $user->getTeams()), $user->getAccountId()); foreach ($troles as $teamId => $roles) { $userTeams[$teamId] = array('roles' => $roles); } $data = ['user' => $user->getUserInfo(), 'teams' => $userTeams]; if ($existingPasswordChanged && $user->getId() == $this->user->getId()) { Scalr_Session::create($this->user->getId()); $data['specialToken'] = Scalr_Session::getInstance()->getToken(); } $this->response->data($data); $this->response->success('User successfully saved'); }