Added autoconfig on Init + fixed bugs

This commit is contained in:
Rick Falkvinge
2014-12-29 03:13:12 +01:00
parent a9dfd57dcd
commit ae6b4bf29a
5 changed files with 203 additions and 52 deletions
+20 -3
View File
@@ -8,7 +8,7 @@ namespace Swarmops.Database
{
// These functions are bloody dangerous, mmmkay?
public void ExecuteAdminCommand (string sqlSequence)
public void ExecuteAdminCommand(string sql)
{
// TODO: Verify that we're in admin mode
@@ -16,14 +16,31 @@ namespace Swarmops.Database
{
connection.Open();
DbCommand command = GetDbCommand (sqlSequence, connection);
DbCommand command = GetDbCommand(sql, connection);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
}
public int ExecuteAdminCommandScalar (string sqlSequence)
public void ExecuteAdminCommands(string[] sqlSequence)
{
// TODO: Verify that we're in admin mode
using (DbConnection connection = GetMySqlDbConnection())
{
connection.Open();
foreach (string sql in sqlSequence)
{
DbCommand command = GetDbCommand (sql, connection);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
}
}
public int ExecuteAdminCommandScalar(string sqlSequence)
{
// TODO: Verify that we're in admin mode
+1 -1
View File
@@ -159,7 +159,7 @@ namespace Swarmops.Logic.Structure
cityIdsUsedLookup[city.CityId] = false; // force non-use of invalid city
}
if (cityIdsUsedLookup[city.CityId])
if ((cityIdsUsedLookup.ContainsKey(city.CityId) && cityIdsUsedLookup[city.CityId]) || country.PostalCodeLength == 0)
{
int newGeographyId = geographyIdTranslation[city.GeographyId];
+102 -46
View File
@@ -10,6 +10,7 @@
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript" src="/Scripts/jquery.leanModal.min.js" ></script>
<script language="javascript" type="text/javascript" src="/Scripts/jquery.smartWizard-2.0.min.js"></script>
<script language="javascript" type="text/javascript" src="/Scripts/jquery.json.min.js"></script>
<!-- fonts -->
<link href='https://fonts.googleapis.com/css?family=Permanent+Marker' rel='stylesheet' type='text/css' />
@@ -139,8 +140,9 @@
// Yes, config is writable. Hide "unwritable" div, show "writable" div, all is nice
$('#DivDatabaseUnwritable').css('display', 'none');
$('#DivDatabaseWritable').css('display', 'inline');
$('#<%=this.TextCredentialsReadDatabase.ClientID %>').focus();
$('#DivDatabaseRootConfig').css('display', 'inline');
setTimeout('$("#TextMysqlServerHost").focus();', 250);
//$('#<%=this.TextCredentialsReadDatabase.ClientID %>').focus();
} else {
// Config is NOT writable. Keep the error on-screen and keep re-checking every two seconds.
@@ -155,9 +157,17 @@
else if (stepNumber == 2) {
isValid = true; // assume true, make false as we go
textBoxes = ["<%=this.TextCredentialsReadDatabase.ClientID %>", "<%=this.TextCredentialsReadServer.ClientID %>", "<%=this.TextCredentialsReadUser.ClientID %>", "<%=this.TextCredentialsReadPassword.ClientID %>",
"<%=this.TextCredentialsWriteDatabase.ClientID %>", "<%=this.TextCredentialsWriteServer.ClientID %>", "<%=this.TextCredentialsWriteUser.ClientID %>", "<%=this.TextCredentialsWritePassword.ClientID %>",
"<%=this.TextCredentialsAdminDatabase.ClientID %>", "<%=this.TextCredentialsAdminServer.ClientID %>", "<%=this.TextCredentialsAdminUser.ClientID %>", "<%=this.TextCredentialsAdminPassword.ClientID %>"];
textBoxes = [];
if (autoConfigMode) {
textBoxes = ["TextMysqlServerHost", "TextMysqlRootPassword"];
} else {
textBoxes = [
"<%=this.TextCredentialsReadDatabase.ClientID %>", "<%=this.TextCredentialsReadServer.ClientID %>", "<%=this.TextCredentialsReadUser.ClientID %>", "<%=this.TextCredentialsReadPassword.ClientID %>",
"<%=this.TextCredentialsWriteDatabase.ClientID %>", "<%=this.TextCredentialsWriteServer.ClientID %>", "<%=this.TextCredentialsWriteUser.ClientID %>", "<%=this.TextCredentialsWritePassword.ClientID %>",
"<%=this.TextCredentialsAdminDatabase.ClientID %>", "<%=this.TextCredentialsAdminServer.ClientID %>", "<%=this.TextCredentialsAdminUser.ClientID %>", "<%=this.TextCredentialsAdminPassword.ClientID %>"
];
}
for (loop = 0; loop < textBoxes.length; loop++) {
fieldContents = $('#' + textBoxes[loop]).val();
@@ -174,42 +184,73 @@
if (isValid) {
DisableNext(); // block Next during synchro call - it may take a while
// also, won't get re-enabled no matter the outcome
$.ajax({
type: "POST",
url: "/Pages/v5/Init/Default.aspx/FirstCredentialsTest",
data: "{" +
"'readDatabase':'" + $('#<%=this.TextCredentialsReadDatabase.ClientID %>').val() + "',"+
"'readServer':'" + $('#<%=this.TextCredentialsReadServer.ClientID %>').val() + "',"+
"'readUser':'" + $('#<%=this.TextCredentialsReadUser.ClientID %>').val() + "',"+
"'readPassword':'" + $('#<%=this.TextCredentialsReadPassword.ClientID %>').val() + "',"+
"'writeDatabase':'" + $('#<%=this.TextCredentialsWriteDatabase.ClientID %>').val() + "',"+
"'writeServer':'" + $('#<%=this.TextCredentialsWriteServer.ClientID %>').val() + "',"+
"'writeUser':'" + $('#<%=this.TextCredentialsWriteUser.ClientID %>').val() + "',"+
"'writePassword':'" + $('#<%=this.TextCredentialsWritePassword.ClientID %>').val() + "',"+
"'adminDatabase':'" + $('#<%=this.TextCredentialsAdminDatabase.ClientID %>').val() + "',"+
"'adminServer':'" + $('#<%=this.TextCredentialsAdminServer.ClientID %>').val() + "',"+
"'adminUser':'" + $('#<%=this.TextCredentialsAdminUser.ClientID %>').val() + "',"+
"'adminPassword':'" + $('#<%=this.TextCredentialsAdminPassword.ClientID %>').val() + "',"+
"'serverName':'" + hostName + "'," +
"'ipAddress':'" + hostAddress +"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // blocks until function returns - race conditions otherwise
success: function (msg) {
if (msg.d.AllPermissionsOk != true) {
// also, won't get re-enabled no matter the outcome
// We have a permissions problem. Block further progress and display the problem.
updatePermissionsAnalysisDisplay(msg.d);
$('#DivDatabaseWritable').fadeOut(400, 'swing', function() { $('#DivDatabasePermissionProblem').fadeIn(200); });
setTimeout('recheckDatabasePermissionsAnalysis();', 5000); // 5s until first re-check
isValid = false;
} else {
// re-enable Next only on exit of step 3
var jsonData = {};
jsonData.serverName = hostName;
jsonData.ipAddress = hostAddress;
if (autoConfigMode) {
jsonData.mysqlHostName = $('#TextMysqlServerHost').val();
jsonData.rootPassword = $('#TextMysqlRootPassword').val();
$.ajax({
type: "POST",
url: "/Pages/v5/Init/Default.aspx/CreateDatabaseFromRoot",
data: $.toJSON(jsonData),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // blocks until function returns - race conditions otherwise
success: function (msg) {
if (msg.d != true) {
// Credentials problem.
$('#TextMysqlRootPassword, #TextMysqlServerHost').css('background-image', "url('/Images/Icons/iconshock-cross-12px.png')").css('background-position', 'right center').css('background-repeat', 'no-repeat');
EnableNext();
isValid = false;
} else {
// re-enable Next only on exit of step 3
}
}
}
});
}
});
}
else
{
jsonData.readDatabase = $('#<%=this.TextCredentialsReadDatabase.ClientID %>').val();
jsonData.readServer = $('#<%=this.TextCredentialsReadServer.ClientID %>').val();
jsonData.readUser = $('#<%=this.TextCredentialsReadUser.ClientID %>').val();
jsonData.readPassword = $('#<%=this.TextCredentialsReadPassword.ClientID %>').val();
jsonData.writeDatabase = $('#<%=this.TextCredentialsWriteDatabase.ClientID %>').val();
jsonData.writeServer = $('#<%=this.TextCredentialsWriteServer.ClientID %>').val();
jsonData.writeUser = $('#<%=this.TextCredentialsWriteUser.ClientID %>').val();
jsonData.writePassword = $('#<%=this.TextCredentialsWritePassword.ClientID %>').val();
jsonData.adminDatabase = $('#<%=this.TextCredentialsAdminDatabase.ClientID %>').val();
jsonData.adminServer = $('#<%=this.TextCredentialsAdminServer.ClientID %>').val();
jsonData.adminUser = $('#<%=this.TextCredentialsAdminUser.ClientID %>').val();
jsonData.adminPassword = $('#<%=this.TextCredentialsAdminPassword.ClientID %>').val();
$.ajax({
type: "POST",
url: "/Pages/v5/Init/Default.aspx/FirstCredentialsTest",
data: $.toJSON(jsonData),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // blocks until function returns - race conditions otherwise
success: function(msg) {
if (msg.d.AllPermissionsOk != true) {
// We have a permissions problem. Block further progress and display the problem.
updatePermissionsAnalysisDisplay(msg.d);
$('#DivDatabaseManualConfig').fadeOut(400, 'swing', function() { $('#DivDatabasePermissionProblem').fadeIn(200); });
setTimeout('recheckDatabasePermissionsAnalysis();', 5000); // 5s until first re-check
isValid = false;
} else {
// re-enable Next only on exit of step 3
}
}
});
}
}
if (isValid) {
@@ -311,7 +352,7 @@
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#DivDatabasePermissionProblem').fadeOut(200, 'swing', function () { $('#DivDatabaseWritable').fadeIn(200); EnableNext(); });
$('#DivDatabasePermissionProblem').fadeOut(200, 'swing', function () { $('#DivDatabaseManualConfig').fadeIn(200); EnableNext(); });
}
});
}
@@ -328,10 +369,10 @@
success: function (msg) {
if (msg.d == true) {
// Yes, config is writable. Hide "unwritable" div, show "writable" div, all is nice
// Yes, config is writable. Hide "unwritable" div, show "config" div, all is nice
$('#DivDatabaseUnwritable').css('display', 'none');
$('#DivDatabaseWritable').fadeIn('slow');
setTimeout('$("#<%=this.TextCredentialsReadDatabase.ClientID %>").focus();', 250);
$('#DivDatabaseManualConfig').fadeIn('slow');
setTimeout('$("#TextMysqlServerHost").focus();', 250);
EnableNext();
} else {
// Config is NOT writable. Keep the error on-screen and keep re-checking every two seconds.
@@ -470,8 +511,16 @@
}
});
}
}
function goManualCredentials() {
autoConfigMode = false;
$('#DivDatabaseRootConfig').css('display', 'none');
$('#DivDatabaseManualConfig').fadeIn('slow');
setTimeout('$("#<%=this.TextCredentialsReadDatabase.ClientID %>").focus();', 250);
}
var autoConfigMode = true;
</script>
@@ -582,8 +631,15 @@
</tr>
</table>
</div>
<div id="DivDatabaseWritable" style="display:none">
<h2>Connect to database</h2>
<div id="DivDatabaseRootConfig" style="display:none">
<h2>Create the database and users</h2>
<p>The Swarmops install sequence can set up the database and users for you, if you provide a root password to the MySQL database server.</p>
<p>(If you don't trust the Swarmops install to do that, that's fine, go to <a href="javascript:goManualCredentials();">manual account credentials</a>.)</p>
<div class="entryLabelsAdmin" style="width:250px">Hostname of MySQL database server<br/>Root password for that MySQL server<br/>&nbsp;</div>
<div class="entryFieldsAdmin"><input type="text" id="TextMysqlServerHost" value="localhost"/>&nbsp;<br/><input type="password" id="TextMysqlRootPassword"/>&nbsp;</div>
</div>
<div id="DivDatabaseManualConfig" style="display:none">
<h2>Connect to existing database</h2>
<p>Before you fill this in, you will need to have created a database on a MySQL server that this web server can access, and set up user accounts that can access it. For security reasons, we <strong>require</strong> having three separate accounts - one for reading (SELECT permissions only), one for writing (SELECT and EXECUTE), and one for admin. All three accounts also need SELECT permissions on the mysql database.</p>
<div class="entryLabelsAdmin" style="width:120px">
+79 -1
View File
@@ -170,6 +170,74 @@ public partial class Pages_v5_Init_Default : Page
}
[WebMethod]
public static bool CreateDatabaseFromRoot (string mysqlHostName, string rootPassword, string serverName, string ipAddress)
{
if (!(VerifyHostName(serverName) && VerifyHostAddress(ipAddress)))
{
if (!Debugger.IsAttached)
{
return true; // Probable hack attempt - fail silently
}
}
try
{
string random = Authentication.CreateRandomPassword(5);
SwarmDb.Credentials rootCredentials = new SwarmDb.Credentials("mysql", new SwarmDb.ServerSet(mysqlHostName), "root", rootPassword);
string readPass = GenerateLongPassword();
string writePass = GenerateLongPassword();
string adminPass = GenerateLongPassword();
string[] initInstructions =
DbCreateScript.Replace ("[random]", random)
.Replace ("[readpass]", readPass)
.Replace ("[writepass]", writePass)
.Replace ("[adminpass]", adminPass).Split ('#');
SwarmDb.GetTestDatabase (rootCredentials).ExecuteAdminCommands (initInstructions);
PermissionsAnalysis permissionsResult = FirstCredentialsTest (
"Swarmops-" + random, mysqlHostName, "Swarmops-R-" + random, readPass,
"Swarmops-" + random, mysqlHostName, "Swarmops-W-" + random, writePass,
"Swarmops-" + random, mysqlHostName, "Swarmops-A-" + random, adminPass,
serverName, ipAddress);
if (!permissionsResult.AllPermissionsOk)
{
throw new InvalidOperationException("waaaaaah");
}
return true;
}
catch (Exception)
{
return false;
}
}
const string DbCreateScript =
"CREATE DATABASE `Swarmops-[random]`#" +
"CREATE USER `Swarmops-R-[random]` IDENTIFIED BY '[readpass]'#" +
"CREATE USER `Swarmops-W-[random]` IDENTIFIED BY '[writepass]'#" +
"CREATE USER `Swarmops-A-[random]` IDENTIFIED BY '[adminpass]'#" +
"GRANT SELECT ON mysql.proc TO `Swarmops-W-[random]`#" +
"GRANT SELECT ON mysql.proc TO `Swarmops-A-[random]`#" +
"USE `Swarmops-[random]`#" +
"GRANT ALL ON `Swarmops-[random]`.* TO `Swarmops-A-[random]`#" +
"GRANT SELECT ON `Swarmops-[random]`.* TO `Swarmops-W-[random]`#" +
"GRANT EXECUTE ON `Swarmops-[random]`.* TO `Swarmops-W-[random]`#" +
"GRANT SELECT ON `Swarmops-[random]`.* TO `Swarmops-R-[random]`#" +
"FLUSH PRIVILEGES";
static private string GenerateLongPassword()
{
return Guid.NewGuid().ToString ("N") + Guid.NewGuid().ToString ("N");
}
[WebMethod]
public static PermissionsAnalysis FirstCredentialsTest
@@ -427,10 +495,11 @@ public partial class Pages_v5_Init_Default : Page
{
// Get the geography layout
_initMessage = "Initializing geography for " + countryCode + "... ";
_initMessage = "Initializing geography for country " + countryCode + "... ";
Thread.Sleep (100);
GeographyUpdate.PrimeCountry (countryCode);
GuidCache.Set ("DbInitProgress", string.Empty);
countryCount++;
@@ -446,6 +515,8 @@ public partial class Pages_v5_Init_Default : Page
Persistence.Key["SwarmopsInstallationId"] = Guid.NewGuid().ToString();
_initMessage = "Initializing currencies...";
// Create initial currencies (European et al)
Currency.Create ("EUR", "Euros", "€");
@@ -459,6 +530,10 @@ public partial class Pages_v5_Init_Default : Page
Currency.Create ("GBP", "Pounds Sterling", "£");
Currency.Create ("BTC", "Bitcoin", "฿");
// Fetch the first set of exchange rates, completing the currency collection
ExchangeRateSnapshot.Create();
// Create the sandbox
Organization.Create (0, "Sandbox", "Sandbox", "Sandbox", "swarmops.com", "Ops",
@@ -645,8 +720,11 @@ public partial class Pages_v5_Init_Default : Page
FormsAuthentication.RedirectFromLoginPage ("1,1", true);
Response.Redirect ("/", true);
}
}
public class PermissionsAnalysis
{
public bool AllPermissionsOk { get; set; }
+1 -1
View File
@@ -28,7 +28,7 @@ namespace Swarmops.Pages.Security
if (!SwarmDb.Configuration.IsConfigured())
{
Response.Redirect ("/Init/", true);
Response.Redirect ("/Pages/v5/Init/", true);
return;
}