public static string SaveAsset(object[] oAsset) { // check the # of elements in the array if (oAsset.Length != 19) { return("Incorrect number of Asset Properties:" + oAsset.Length.ToString()); } string sAssetID = oAsset[0].ToString(); string sAssetName = oAsset[1].ToString().Replace("'", "''"); string sDbName = oAsset[2].ToString().Replace("'", "''"); string sPort = oAsset[3].ToString(); string sConnectionType = oAsset[4].ToString(); string sIsConnection = "0"; // oAsset[5].ToString(); string sAddress = oAsset[5].ToString().Replace("'", "''"); // mode is edit or add string sMode = oAsset[6].ToString(); string sCredentialID = oAsset[7].ToString(); string sCredUsername = oAsset[8].ToString().Replace("'", "''"); string sCredPassword = oAsset[9].ToString().Replace("'", "''"); string sShared = oAsset[10].ToString(); string sCredentialName = oAsset[11].ToString().Replace("'", "''"); string sCredentialDescr = oAsset[12].ToString().Replace("'", "''"); string sDomain = oAsset[13].ToString().Replace("'", "''"); string sCredentialType = oAsset[14].ToString(); string sAssetStatus = oAsset[15].ToString(); string sPrivilegedPassword = oAsset[16].ToString(); string sTagArray = oAsset[17].ToString(); string sConnString = oAsset[18].ToString().Replace("'", "''"); // for logging string sOriginalAssetName = ""; string sOriginalPort = ""; string sOriginalDbName = ""; string sOriginalAddress = ""; string sOriginalConnectionType = ""; string sOriginalUserName = ""; string sOriginalConnString = ""; string sOriginalCredentialID = ""; string sOriginalAssetStatus = ""; dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); string sSql = null; string sErr = null; //if we are editing get the original values //this is getting original values for logging purposes if (sMode == "edit") { DataRow dr = null; sSql = "select a.asset_name, a.asset_status, a.port, a.db_name, a.address, a.db_name, a.connection_type, a.conn_string, ac.username, a.credential_id," + " case when a.is_connection_system = '1' then 'Yes' else 'No' end as is_connection_system " + " from asset a " + " left outer join asset_credential ac on ac.credential_id = a.credential_id " + " where a.asset_id = '" + sAssetID + "'"; if (!dc.sqlGetDataRow(ref dr, sSql, ref sErr)) { throw new Exception(sErr); } else { if (dr != null) { sOriginalAssetName = dr["asset_name"].ToString(); sOriginalPort = (object.ReferenceEquals(dr["port"], DBNull.Value) ? "" : dr["port"].ToString()); sOriginalDbName = (object.ReferenceEquals(dr["db_name"], DBNull.Value) ? "" : dr["db_name"].ToString()); sOriginalAddress = (object.ReferenceEquals(dr["address"], DBNull.Value) ? "" : dr["address"].ToString()); sOriginalConnectionType = (object.ReferenceEquals(dr["connection_type"], DBNull.Value) ? "" : dr["connection_type"].ToString()); sOriginalUserName = (object.ReferenceEquals(dr["username"], DBNull.Value) ? "" : dr["username"].ToString()); sOriginalConnString = (object.ReferenceEquals(dr["conn_string"], DBNull.Value) ? "" : dr["conn_string"].ToString()); sOriginalCredentialID = (object.ReferenceEquals(dr["credential_id"], DBNull.Value) ? "" : dr["credential_id"].ToString()); sOriginalAssetStatus = dr["asset_status"].ToString(); } } } //NOTE NOTE NOTE! //the following is a catch 22. //if we're adding a new asset, we will need to figure out the credential first so we can save the credential id on the asset //but if it's a new local credential, it gets the asset id as it's name. //so......... //if it's a new asset, go ahead and get the new guid for it here so the credential add will work. if (sMode == "add") { sAssetID = ui.NewGUID(); } //and move on... // there are three CredentialType's // 1) 'selected' = user selected a different credential, just save the credential_id // 2) 'new' = user created a new shared or local credential // 3) 'existing' = same credential, just update the username,description ad password string sPriviledgedPasswordUpdate = null; if (sCredentialType == "new") { if (sPrivilegedPassword.Length == 0) { sPriviledgedPasswordUpdate = "NULL"; } else { sPriviledgedPasswordUpdate = "'" + dc.EnCrypt(sPrivilegedPassword) + "'"; } //if it's a local credential, the credential_name is the asset_id. //if it's shared, there will be a name. if (sShared == "1") { sCredentialName = sAssetID; //whack and add - easiest way to avoid conflicts sSql = "delete from asset_credential where credential_name = '" + sCredentialName + "' and shared_or_local = '1'"; if (!dc.sqlExecuteUpdate(sSql, ref sErr)) { throw new Exception(sErr); } } //now we're clear to add sCredentialID = "'" + ui.NewGUID() + "'"; sSql = "insert into asset_credential " + "(credential_id,credential_name,username,password,domain,shared_or_local,shared_cred_desc,privileged_password) " + "values (" + sCredentialID + ",'" + sCredentialName + "','" + sCredUsername + "','" + dc.EnCrypt(sCredPassword) + "','" + sDomain + "','" + sShared + "','" + sCredentialDescr + "'," + sPriviledgedPasswordUpdate + ")"; if (!dc.sqlExecuteUpdate(sSql, ref sErr)) { if (sErr == "key_violation") { throw new Exception("A Credential with that name already exists. Please select another name."); } else { throw new Exception(sErr); } } // add security log ui.WriteObjectAddLog(Globals.acObjectTypes.Credential, sCredentialID, sCredentialName, ""); } else if (sCredentialType == "existing") { sCredentialID = "'" + sCredentialID + "'"; // bugzilla 1126 if the password has not changed leave it as is. string sPasswordUpdate = null; if (sCredPassword == "($%#d@x!&") { // password has not been touched sPasswordUpdate = ""; } else { // updated password sPasswordUpdate = ",password = '******'"; } // bugzilla 1260 // same for privileged_password if (sPrivilegedPassword == "($%#d@x!&") { // password has not been touched sPriviledgedPasswordUpdate = ""; } else { // updated password // bugzilla 1352 priviledged password can be blank, so if it is, set it to null if (sPrivilegedPassword.Length == 0) { sPriviledgedPasswordUpdate = ",privileged_password = null"; } else { sPriviledgedPasswordUpdate = ",privileged_password = '******'"; } } sSql = "update asset_credential " + "set username = '******'" + sPasswordUpdate + sPriviledgedPasswordUpdate + ",domain = '" + sDomain + "'," + "shared_or_local = '" + sShared + "',shared_cred_desc = '" + sCredentialDescr + "'" + "where credential_id = " + sCredentialID; if (!dc.sqlExecuteUpdate(sSql, ref sErr)) { throw new Exception(sErr); } // add security log ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + "Changed credential", sOriginalUserName, sCredUsername); } else { // user selected a shared credential // remove the local credential if one exists if (sOriginalCredentialID.Length > 0) { sSql = "delete from asset_credential where credential_id = '" + sOriginalCredentialID + "' and shared_or_local = '1'"; if (!dc.sqlExecuteUpdate(sSql, ref sErr)) { throw new Exception(sErr); } // add security log ui.WriteObjectDeleteLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''"), "Credential deleted" + sOriginalCredentialID + " " + sOriginalUserName); } sCredentialID = "'" + sCredentialID + "'"; } // checks that cant be done on the client side // is the name unique? string sInuse = ""; if (sMode == "edit") { sSql = "select asset_id from asset where asset_name = '" + sAssetName.Trim() + "' and asset_id <> '" + sAssetID + "' limit 1"; } else { sSql = "select asset_id from asset where asset_name = '" + sAssetName.Trim() + "' limit 1"; } if (!dc.sqlGetSingleString(ref sInuse, sSql, ref sErr)) { throw new Exception(sErr); } else if (!string.IsNullOrEmpty(sInuse)) { return("Asset Name '" + sAssetName + "' already in use, choose another." + sAssetID); } try { dataAccess.acTransaction oTrans = new dataAccess.acTransaction(ref sErr); if (sMode == "edit") { sSql = "update asset set asset_name = '" + sAssetName + "'," + " asset_status = '" + sAssetStatus + "'," + " address = '" + sAddress + "'" + "," + " conn_string = '" + sConnString + "'" + "," + " db_name = '" + sDbName + "'," + " port = " + (sPort == "" ? "NULL" : "'" + sPort + "'") + "," + " connection_type = '" + sConnectionType + "'," + " is_connection_system = '" + (sIsConnection == "Yes" ? 1 : 0) + "'," + " credential_id = " + sCredentialID + " where asset_id = '" + sAssetID + "'"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } } else { sSql = "insert into asset (asset_id,asset_name,asset_status,address,conn_string,db_name,port,connection_type,is_connection_system,credential_id)" + " values (" + "'" + sAssetID + "'," + "'" + sAssetName + "'," + "'" + sAssetStatus + "'," + "'" + sAddress + "'," + "'" + sConnString + "'," + "'" + sDbName + "'," + (sPort == "" ? "NULL" : "'" + sPort + "'") + "," + "'" + sConnectionType + "'," + "'0'," + sCredentialID + ")"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } } #region "tags" // remove the existing tags sSql = "delete from object_tags where object_id = '" + sAssetID + "'"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } // add user groups, if there are any if (sTagArray.Length > 0) { ArrayList aTags = new ArrayList(sTagArray.Split(',')); foreach (string sTagName in aTags) { sSql = "insert object_tags (object_id, object_type, tag_name)" + " values ('" + sAssetID + "', 2, '" + sTagName + "')"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } } } #endregion oTrans.Commit(); } catch (Exception ex) { throw new Exception(ex.Message); } //-------------------------------------------------------------------------------------------------- // NOTE! too many if edit... probably need to just make 2 functions, update asset, and create asset //-------------------------------------------------------------------------------------------------- // add security log // since this is not handled as a page postback, theres no "Viewstate" settings // so 2 options either we keep an original setting for each value in hid values, or just get them from the db as part of the // update above, since we are already passing in 15 or so fields, lets just get the values at the start and reference them here if (sMode == "edit") { string sOrigCredUsername = GetCredentialNameFromID(sOriginalCredentialID.Replace("'", "")).ToString(); string sCurrentCredUsername = GetCredentialNameFromID(sCredentialID.Replace("'", "")).ToString(); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Name", sOriginalAssetName, sAssetName); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Address", sOriginalAddress, sAddress); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Port", sOriginalPort, sPort); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " DB Name", sOriginalDbName, sDbName); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Connection Type", sOriginalConnectionType, sConnectionType); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Credential", sOrigCredUsername, sCurrentCredUsername); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Status", sOriginalAssetStatus, sAssetStatus); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " ConnString", sOriginalConnString, sConnString); } else { ui.WriteObjectAddLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''"), "Asset Created"); } // no errors to here, so return an empty string return(""); }
public static string SaveCredential(object[] oAsset) { // we are passing in 16 elements, if we have 16 go if (oAsset.Length != 8) return "Incorrect list of attributes:" + oAsset.Length.ToString(); string sCredentialID = oAsset[0].ToString(); string sCredentialName = oAsset[1].ToString().Replace("'", "''"); string sUserName = oAsset[2].ToString().Replace("'", "''"); string sCredentialDesc = oAsset[3].ToString().Replace("'", "''"); string sPassword = oAsset[4].ToString(); string sDomain = oAsset[5].ToString(); string sMode = oAsset[6].ToString(); string sPrivilegedPassword = oAsset[7].ToString(); // for logging string sOriginalUserName = null; dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); string sSql = null; string sErr = null; //if we are editing get the original values if (sMode == "edit") { sSql = "select username from asset_credential " + "where credential_id = '" + sCredentialID + "'"; if (!dc.sqlGetSingleString(ref sOriginalUserName, sSql, ref sErr)) { throw new Exception(sErr); } } try { dataAccess.acTransaction oTrans = new dataAccess.acTransaction(ref sErr); // update the user fields. if (sMode == "edit") { // only update the passwword if it has changed string sNewPassword = ""; if (sPassword != "($%#d@x!&") { sNewPassword = "******" + dc.EnCrypt(sPassword) + "'"; } // bugzilla 1260 // same for privileged_password string sPriviledgedPasswordUpdate = null; if (sPrivilegedPassword == "($%#d@x!&") { // password has not been touched sPriviledgedPasswordUpdate = ""; } else { // updated password sPriviledgedPasswordUpdate = ",privileged_password = '******'"; } sSql = "update asset_credential set" + " credential_name = '" + sCredentialName + "'," + " username = '******'," + " domain = '" + sDomain.Replace("'", "''") + "'," + " shared_cred_desc = '" + sCredentialDesc + "'" + sNewPassword + sPriviledgedPasswordUpdate + " where credential_id = '" + sCredentialID + "'"; } else { // if the priviledged password is empty just set it to null string sPrivilegedPasswordUpdate = "NULL"; if (sPrivilegedPassword.Length != 0) { sPrivilegedPasswordUpdate = "'" + dc.EnCrypt(sPrivilegedPassword) + "'"; }; sSql = "insert into asset_credential (credential_id, credential_name, username, password, domain, shared_cred_desc, shared_or_local, privileged_password)" + " values (" + "'" + ui.NewGUID() + "'," + "'" + sCredentialName.Replace("'", "''") + "'," + "'" + sUserName.Replace("'", "''") + "'," + "'" + dc.EnCrypt(sPassword) + "'," + "'" + sDomain.Replace("'", "''") + "'," + "'" + sCredentialDesc.Replace("'", "''") + "'," + "'0'," + sPrivilegedPasswordUpdate + ")"; } oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { if (sErr == "key_violation") throw new Exception("A Credential with that name already exists. Please select another name."); else throw new Exception(sErr); } oTrans.Commit(); } catch (Exception ex) { throw new Exception(ex.Message); } // add security log // since this is not handled as a page postback, theres no "Viewstate" settings // so 2 options either we keep an original setting for each value in hid values, or just get them from the db as part of the // update above, since we are already passing in 15 or so fields, lets just get the values at the start and reference them here if (sMode == "edit") { ui.WriteObjectChangeLog(Globals.acObjectTypes.Credential, sCredentialID, sUserName.Replace("'", "''"), sOriginalUserName, sUserName.Replace("'", "''")); } else { ui.WriteObjectAddLog(Globals.acObjectTypes.Credential, sCredentialID, sUserName.Replace("'", "''"), "Credential Created"); } // no errors to here, so return an empty string return ""; }
public void wmSaveActionParameterXML(string sActionID, string sActionDefaultsXML) { dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); taskMethods tm = new taskMethods(); try { string sUserID = ui.GetSessionUserID(); if (ui.IsGUID(sActionID) && ui.IsGUID(sUserID)) { string sErr = ""; string sSQL = ""; //we encoded this in javascript before the ajax call. //the safest way to unencode it is to use the same javascript lib. //(sometimes the javascript and .net libs don't translate exactly, google it.) sActionDefaultsXML = ui.unpackJSON(sActionDefaultsXML); //we gotta peek into the XML and encrypt any newly keyed values PrepareAndEncryptParameterXML(ref sActionDefaultsXML); //so, like when we read it, we gotta spin and compare, and build an XML that only represents *changes* //to the defaults on the task. //what is the task associated with this action? sSQL = "select t.task_id" + " from ecotemplate_action ea" + " join task t on ea.original_task_id = t.original_task_id" + " and t.default_version = 1" + " where ea.action_id = '" + sActionID + "'"; string sTaskID = ""; if (!dc.sqlGetSingleString(ref sTaskID, sSQL, ref sErr)) throw new Exception(sErr); if (!ui.IsGUID(sTaskID)) throw new Exception("Unable to find Task ID for Action."); string sOverrideXML = ""; XDocument xTPDoc = new XDocument(); XDocument xADDoc = new XDocument(); //get the parameter XML from the TASK string sTaskParamXML = tm.wmGetParameterXML("task", sTaskID, ""); if (!string.IsNullOrEmpty(sTaskParamXML)) { xTPDoc = XDocument.Parse(sTaskParamXML); if (xTPDoc == null) throw new Exception("Task Parameter XML data is invalid."); XElement xTPParams = xTPDoc.XPathSelectElement("/parameters"); if (xTPParams == null) throw new Exception("Task Parameter XML data does not contain 'parameters' root node."); } //we had the ACTION defaults handed to us if (!string.IsNullOrEmpty(sActionDefaultsXML)) { xADDoc = XDocument.Parse(sActionDefaultsXML); if (xADDoc == null) throw new Exception("Action Defaults XML data is invalid."); XElement xADParams = xADDoc.XPathSelectElement("/parameters"); if (xADParams == null) throw new Exception("Action Defaults XML data does not contain 'parameters' root node."); } //spin the nodes in the ACTION xml, then dig in to the task XML and UPDATE the value if found. //(if the node no longer exists, delete the node from the action XML) //and action "values" take precedence over task values. //this does a regular loop because we can't remove from an IEnumerable int x = xADDoc.XPathSelectElements("//parameter").Count(); for (int i = (x-1); i>=0; i--) { XElement xDefault = xADDoc.XPathSelectElements("//parameter").ElementAt(i); //look it up in the task param xml XElement xADName = xDefault.XPathSelectElement("name"); string sADName = (xADName == null ? "" : xADName.Value); XElement xADValues = xDefault.XPathSelectElement("values"); //string sValues = (xValues == null ? "" : xValues.ToString()); //now we have the name of the parameter, go find it in the TASK param XML XElement xTaskParam = xTPDoc.XPathSelectElement("//parameter/name[. = '" + sADName + "']/.."); //NOTE! the /.. gets the parent of the name node! //if it doesn't exist in the task params, remove it from this document if (xTaskParam == null) { xDefault.Remove(); continue; } //and the "values" collection will be the 'next' node XElement xTaskParamValues = xTaskParam.XPathSelectElement("values"); //so... it might be //a) just an oev (original encrypted value) so de-base64 it //b) a value flagged for encryption //note we don't care about dirty unencrypted values... they'll compare down below just fine. //is it encrypted? bool bEncrypted = false; if (xTaskParam.Attribute("encrypt") != null) bEncrypted = dc.IsTrue(xTaskParam.Attribute("encrypt").Value); if (bEncrypted) { foreach (XElement xVal in xADValues.XPathSelectElements("value")) { if (xVal.HasAttributes) { //a) is it an oev? unpackJSON it (that's just an obfuscation wrapper) if (xVal.Attribute("oev") != null) { if (dc.IsTrue(xVal.Attribute("oev").Value)) { xVal.Value = ui.unpackJSON(xVal.Value); xVal.SetAttributeValue("oev", null); } } //b) is it do_encrypt? (remove the attribute to keep the db clutter down) if (xVal.Attribute("do_encrypt") != null) { xVal.Value = dc.EnCrypt(xVal.Value); xVal.SetAttributeValue("do_encrypt", null); } } } } //now that the encryption is sorted out, // if the combined values of the parameter happens to match what's on the task // we just remove it. //we're doing combined because of lists (the whole list must match for it to be a dupe) //it's easy to look at all the values in a node with the node.Value property. //but we'll have to manually concatenate all the oev attributes string sTaskVals = ""; string sDefVals = ""; if (bEncrypted) { // the task document already has the oev obfuscated foreach (XAttribute xa in xTaskParamValues.Elements("value").Attributes("oev")) { sTaskVals += xa.Value; } //but the XML we just got from the client doesn't... it's in the value. foreach (XElement xe in xADValues.Elements("value")) { sDefVals += ui.packJSON(xe.Value); } if (sTaskVals.Equals(sDefVals)) { xDefault.Remove(); continue; } } else { if (xTaskParamValues.Value.Equals(xADValues.Value)) { xDefault.Remove(); continue; } } } //done sOverrideXML = xADDoc.ToString(SaveOptions.DisableFormatting); //FINALLY, we have an XML that represents only the differences we wanna save. sSQL = "update ecotemplate_action set" + " parameter_defaults = '" + sOverrideXML + "'" + " where action_id = '" + sActionID + "'"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) throw new Exception("Unable to update Eco Template Action [" + sActionID + "]." + sErr); ui.WriteObjectChangeLog(Globals.acObjectTypes.EcoTemplate, sActionID, sActionID, "Action default parameters updated: [" + sOverrideXML + "]"); } else { throw new Exception("Unable to update Eco Template Action. Missing or invalid Action ID."); } } catch (Exception ex) { throw ex; } return; }
public void wmUpdateRegistryValue(string sObjectID, string sXPath, string sValue, string sEncrypt) { dataAccess dc = new dataAccess(); FunctionTemplates.HTMLTemplates ft = new FunctionTemplates.HTMLTemplates(); //fail on missing values if (string.IsNullOrEmpty(sXPath)) throw new Exception("Missing XPath to update."); //masked means update an attribute AND encrypt the value sEncrypt = (dc.IsTrue(sEncrypt) ? "true" : "false"); sValue = (dc.IsTrue(sEncrypt) ? dc.EnCrypt(sValue) : sValue); //update if (sObjectID == "global") sObjectID = "1"; ft.SetNodeValueinXMLColumn("object_registry", "registry_xml", "object_id = '" + sObjectID + "'", sXPath, sValue); ft.SetNodeAttributeinXMLColumn("object_registry", "registry_xml", "object_id = '" + sObjectID + "'", sXPath, "encrypt", sEncrypt); return; }
public static string SaveUserEdits(object[] oUser) { string sChangeDetail = "User Details updated."; // verify the right number of properties if (oUser.Length != 10) { return("Incorrect number of User Properties."); } string sEditUserID = oUser[0].ToString(); string sLoginID = oUser[1].ToString(); string sFullName = oUser[2].ToString(); string sAuthType = oUser[3].ToString(); string sUserPassword = oUser[4].ToString(); string sForcePasswordChange = oUser[5].ToString(); string sUserRole = oUser[6].ToString(); string sEmail = oUser[7].ToString(); string sStatus = oUser[8].ToString(); string sGroupArray = oUser[9].ToString(); dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); string sSql = null; string sErr = null; // checks that cant be done on the client side // is the name unique? string sInuse = ""; if (!dc.sqlGetSingleString(ref sInuse, "select user_id from users where username = '******' and user_id <> '" + sEditUserID + "' limit 1", ref sErr)) { throw new Exception(sErr); } else { if (!string.IsNullOrEmpty(sInuse)) { return("Login ID '" + sLoginID + "' is unavailable, please choose another."); } } // CHANGE Per conference call 5-11-09 we are using a random 9 char mask // if the password has not changed this will be the same 9 chars string sPasswordUpdate = null; bool boolPasswordChanged = false; if (sUserPassword == "($%#d@x!&") { // password has not been touched sPasswordUpdate = ","; boolPasswordChanged = false; } else { // password changed sChangeDetail += " Password changed."; if (sAuthType == "local") { // bugzilla 1347 // check the user password history setting, and make sure the password was not used in the past x passwords if (dc.PasswordInHistory(dc.EnCrypt(sUserPassword.Trim()), sEditUserID, ref sErr)) { return("Passwords can not be reused, please choose another password"); } ; if (sErr != null) { return(sErr); } ; if (!dc.PasswordIsComplex(sUserPassword.Trim(), ref sErr)) { return(sErr); } else { sPasswordUpdate = ",user_password = '******',"; boolPasswordChanged = true; } } else if (sAuthType == "ldap") { sPasswordUpdate = ",user_password = NULL,"; } else { return("Unknown Authentication type."); } } try { dataAccess.acTransaction oTrans = new dataAccess.acTransaction(ref sErr); // update the user fields. sSql = "update users set" + " full_name = '" + sFullName + "'," + " username = '******'" + sPasswordUpdate + " force_change = '" + sForcePasswordChange + "'," + " authentication_type = '" + sAuthType + "'," + " email = '" + sEmail + "'," + " failed_login_attempts = '0'," + " status = '" + sStatus + "'," + " user_role = '" + sUserRole + "'" + " where user_id = '" + sEditUserID + "'"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } if (boolPasswordChanged) { // add Password history if it changed sSql = "insert user_password_history (user_id, change_time,password) values ('" + sEditUserID + "',now(),'" + dc.EnCrypt(sUserPassword.Trim()) + "')"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } } #region "tags" // remove the existing tags sSql = "delete from object_tags where object_id = '" + sEditUserID + "'"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } // add user groups, if there are any if (sGroupArray.Length > 0) { ArrayList aGroups = new ArrayList(sGroupArray.Split(',')); foreach (string sGroupName in aGroups) { sSql = "insert object_tags (object_id, object_type, tag_name)" + " values ('" + sEditUserID + "', 1, '" + sGroupName + "')"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } } } #endregion oTrans.Commit(); } catch (Exception ex) { throw new Exception(ex.Message); } // add security log ui.WriteObjectChangeLog(Globals.acObjectTypes.User, sEditUserID, sFullName.Trim().Replace("'", "''"), sChangeDetail); // no errors to here, so return an empty string return(""); }
//this one is used by several functions... //it looks in the XML for anything to encrypt or rearrange //because we can't do everything on the client. public void PrepareAndEncryptParameterXML(ref string sParameterXML) { dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); if (!string.IsNullOrEmpty(sParameterXML)) { XDocument xDoc = XDocument.Parse(sParameterXML); if (xDoc == null) throw new Exception("Parameter XML data is invalid."); XElement xParams = xDoc.XPathSelectElement("/parameters"); if (xParams == null) throw new Exception("Parameter XML data does not contain 'parameters' root node."); //now, all we're doing here is: // a) encrypting any new values // b) moving any oev values from an attribute to a value // a) encrypt new values foreach (XElement xToEncrypt in xDoc.XPathSelectElements("//parameter/values/value[@do_encrypt='true']")) { xToEncrypt.Value = dc.EnCrypt(xToEncrypt.Value); xToEncrypt.SetAttributeValue("do_encrypt", null); } //b) unbase64 any oev's and move them to values foreach (XElement xToEncrypt in xDoc.XPathSelectElements("//parameter/values/value[@oev='true']")) { xToEncrypt.Value = ui.unpackJSON(xToEncrypt.Value); xToEncrypt.SetAttributeValue("oev", null); } sParameterXML = xDoc.ToString(SaveOptions.DisableFormatting); } }
public void btnSave_Click(object sender, System.EventArgs e) { // decide what We are updating, its ok to update email everytime, but the password and security answer may not have changed. // validation for password match if (txtPassword.Text != txtPasswordConfirm.Text) { ui.RaiseError(Page, "Passwords do not match", true, ""); return; } sSQL = "update users set email = '" + txtEmail.Text.Replace("'", "''") + "'"; string sPasswordFiller = "($%#d@x!&"; if (lblAuthenticationType.Text == "local") { //------------------------------------------------------------------------------------------------------- // these settings are only applicable if the user is local //only update password if it has been changed. sSQL += ",security_question = '" + dc.EnCrypt(txtSecurityQuestion.Text.Replace("'", "''")) + "'"; if (txtPassword.Text != sPasswordFiller) { // bugzilla 1347 // check the user password history setting, and make sure the password was not used in the past x passwords if (dc.PasswordInHistory(dc.EnCrypt(txtPassword.Text), ui.GetSessionUserID(), ref sErr)) { ui.RaiseError(Page, "Passwords can not be reused, choose another password", true, ""); return; } ; if (sErr != "") { ui.RaiseError(Page, sErr, true, ""); return; } ; // make sure the password is valid if (!dc.PasswordIsComplex(txtPassword.Text, ref sErr)) { ui.RaiseError(Page, sErr, true, ""); return; } sSQL += ",user_password='******'"; } // only update the security answer if it has changed if (txtSecurityAnswer.Text != hidSecurityAnswer.Value) { sSQL += ",security_answer='" + dc.EnCrypt(txtSecurityAnswer.Text) + "'"; } //------------------------------------------------------------------------------------------------------- } sSQL += " where user_id = '" + ui.GetSessionUserID() + "'"; try { if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { ui.RaiseError(Page, "Update failed: " + sErr, true, ""); } //logging, what else should we log? I guess the fact that the user changed the password would be enough? ui.WriteObjectChangeLog(acObjectTypes.User, "User Preferences", "Email", hidEmail.Value, txtEmail.Text); // what else should we log? I guess the fact that the user changed the password would be enough? if (txtPassword.Text != sPasswordFiller) { ui.WriteObjectChangeLog(acObjectTypes.User, ui.GetSessionUserID(), "Password", "User updated password via User Preferences"); // add the password update to the history sSQL = "insert user_password_history (user_id, change_time,password) values ('" + ui.GetSessionUserID() + "',now(),'" + dc.EnCrypt(txtPassword.Text) + "')"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { ui.RaiseError(Page, "User updated, could not add password history: " + sErr, true, ""); } } } catch { ui.RaiseError(Page, "Update failed: " + sErr, true, ""); } txtSecurityAnswer.Attributes.Add("value", txtSecurityAnswer.Text); ui.RaiseInfo(Page, "Preferences updated.", ""); // to make everything look right redirect to raw //Response.Redirect(Request.RawUrl); }
public static string SaveAccount(string sMode, string sAccountID, string sAccountName, string sAccountNumber, string sProvider, string sLoginID, string sLoginPassword, string sLoginPasswordConfirm, string sIsDefault, string sAutoManageSecurity) { // for logging string sOriginalName = ""; dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); string sSql = ""; string sErr = ""; //if we are editing get the original values if (sMode == "edit") { } try { dataAccess.acTransaction oTrans = new dataAccess.acTransaction(ref sErr); // update the user fields. if (sMode == "edit") { sSql = "select account_name from cloud_account " + "where account_id = '" + sAccountID + "'"; if (!dc.sqlGetSingleString(ref sOriginalName, sSql, ref sErr)) throw new Exception("Error getting original account name:" + sErr); // only update the passwword if it has changed string sNewPassword = ""; if (sLoginPassword != "($%#d@x!&") { sNewPassword = "******" + dc.EnCrypt(sLoginPassword) + "'"; } sSql = "update cloud_account set" + " account_name = '" + sAccountName + "'," + " account_number = '" + sAccountNumber + "'," + " provider = '" + sProvider + "'," + " is_default = '" + sIsDefault + "'," + " auto_manage_security = '" + sAutoManageSecurity + "'," + " login_id = '" + sLoginID + "'" + sNewPassword + " where account_id = '" + sAccountID + "'"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) throw new Exception("Error updating account: " + sErr); ui.WriteObjectChangeLog(Globals.acObjectTypes.CloudAccount, sAccountID, sAccountName, sOriginalName, sAccountName);} else { //now, for some reason we were having issues with the initial startup of apache //not able to perform the very first database hit. //this line serves as an inital db hit, but we aren't trapping it or showing the error dc.TestDBConnection(ref sErr); //if there are no rows yet, make this one the default even if the box isn't checked. if (sIsDefault == "0") { int iExists = -1; sSql = "select count(*) as cnt from cloud_account"; if (!dc.sqlGetSingleInteger(ref iExists, sSql, ref sErr)) { System.Threading.Thread.Sleep(300); if (!dc.sqlGetSingleInteger(ref iExists, sSql, ref sErr)) { System.Threading.Thread.Sleep(300); if (!dc.sqlGetSingleInteger(ref iExists, sSql, ref sErr)) throw new Exception("Unable to count Cloud Accounts: " + sErr); } } if (iExists == 0) sIsDefault = "1"; } sAccountID = ui.NewGUID(); sSql = "insert into cloud_account (account_id, account_name, account_number, provider, is_default, login_id, login_password, auto_manage_security)" + " values ('" + sAccountID + "'," + "'" + sAccountName + "'," + "'" + sAccountNumber + "'," + "'" + sProvider + "'," + "'" + sIsDefault + "'," + "'" + sLoginID + "'," + "'" + dc.EnCrypt(sLoginPassword) + "'," + "'" + sAutoManageSecurity + "')"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) throw new Exception("Error creating account: " + sErr); ui.WriteObjectAddLog(Globals.acObjectTypes.CloudAccount, sAccountID, sAccountName, "Account Created"); } //if "default" was selected, unset all the others if (dc.IsTrue(sIsDefault)) { oTrans.Command.CommandText = "update cloud_account set is_default = 0 where account_id <> '" + sAccountID + "'"; if (!oTrans.ExecUpdate(ref sErr)) throw new Exception("Error updating defaults: " + sErr); } oTrans.Commit(); //refresh the cloud account list in the session if (!ui.PutCloudAccountsInSession(ref sErr)) throw new Exception("Error refreshing accounts in session: " + sErr); } catch (Exception ex) { throw new Exception("Error: General Exception: " + ex.Message); } // no errors to here, so return an empty string return "{'account_id':'" + sAccountID + "', 'account_name':'" + sAccountName + "', 'provider':'" + sProvider + "'}"; }
public static string SaveNotifications(object[] oAsset) { dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); acUI.AppGlobals ag = new acUI.AppGlobals(); string sErr = ""; string sMessengerOnOff = oAsset[0].ToString(); string sPollLoop = oAsset[1].ToString(); string sRetryDelay = oAsset[2].ToString(); string sRetryMaxAttempts = oAsset[3].ToString(); string sSMTPServerAddress = oAsset[4].ToString().Replace("'", "''"); string sSMTPUserAccount = oAsset[5].ToString().Replace("'", "''"); string sSMTPUserPassword = oAsset[6].ToString(); string sSMTPServerPort = oAsset[7].ToString(); string sFromEmail = oAsset[8].ToString().Replace("'", "''"); string sFromName = oAsset[9].ToString().Replace("'", "''"); string sAdminEmail = oAsset[10].ToString().Replace("'", "''"); // get the current settings for the logging string sOrigMessengerOnOff = ""; string sOrigPollLoop = ""; string sOrigRetryDelay = ""; string sOrigRetryMaxAttempts = ""; string sOrigSMTPServerAddress = ""; string sOrigSMTPUserAccount = ""; string sOrigSMTPServerPort = ""; string sOrigFromEmail = ""; string sOrigFromName = ""; string sOrigAdminEmail = ""; string sSQL = "select mode_off_on, loop_delay_sec, retry_delay_min, retry_max_attempts," + " smtp_server_addr, smtp_server_user, smtp_server_password, smtp_server_port, from_email, from_name, admin_email" + " from messenger_settings" + " where id = 1"; DataTable dt = new DataTable(); if (!dc.sqlGetDataTable(ref dt, sSQL, ref sErr)) { return("Unable to continue. " + sErr); } if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; sOrigMessengerOnOff = dr["mode_off_on"].ToString(); sOrigPollLoop = dr["loop_delay_sec"].ToString(); sOrigRetryDelay = dr["retry_delay_min"].ToString(); sOrigRetryMaxAttempts = dr["retry_max_attempts"].ToString(); sOrigSMTPServerAddress = dr["smtp_server_addr"].ToString(); sOrigSMTPUserAccount = dr["smtp_server_user"].ToString(); sOrigSMTPServerPort = dr["smtp_server_port"].ToString(); sOrigFromEmail = dr["from_email"].ToString(); sOrigFromName = dr["from_name"].ToString(); sOrigAdminEmail = dr["admin_email"].ToString(); } sSQL = "update messenger_settings set mode_off_on='{0}', loop_delay_sec={1}, retry_delay_min={2}, retry_max_attempts={3}, smtp_server_addr='{4}', smtp_server_user='******', smtp_server_port={6}, from_email='{7}', from_name='{8}', admin_email='{9}'"; //only update password if it has been changed. string sPasswordFiller = "($%#d@x!&"; if (sSMTPUserPassword != sPasswordFiller) { sSQL += ",smtp_server_password='******'"; } sSQL = string.Format(sSQL, sMessengerOnOff, sPollLoop, sRetryDelay, sRetryMaxAttempts, sSMTPServerAddress, sSMTPUserAccount, sSMTPServerPort, sFromEmail, sFromName, sAdminEmail, dc.EnCrypt(sSMTPUserPassword)); if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { return("Update failed: " + sErr); } else { //logging var sLogObject = "Manage Notifications"; ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "Messenger On / Off", sOrigMessengerOnOff, sMessengerOnOff); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "Poll Loop", sOrigPollLoop, sPollLoop); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "Retry Delay", sOrigRetryDelay, sRetryDelay); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "Retry Max Attempts", sOrigRetryMaxAttempts, sRetryMaxAttempts); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "SMTP Server Address", sOrigSMTPServerAddress, sSMTPServerAddress); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "SMTP User Account", sOrigSMTPUserAccount, sSMTPUserAccount); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "SMTP Server Port", sOrigSMTPServerPort, sSMTPServerPort); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "From Email", sOrigFromEmail, sFromEmail); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "From Name", sOrigFromName, sFromName); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "From Name", sOrigAdminEmail, sAdminEmail); // send a notification to the user that made the change if (sMessengerOnOff == "on") { // get the users email, if they do not have an email tell them no message was created. string sUsersEmail = null; string sUserID = ui.GetSessionUserID(); sSQL = "select email from users where user_id = '" + sUserID + "'"; if (!dc.sqlGetSingleString(ref sUsersEmail, sSQL, ref sErr)) { return("Unable to create test email: " + sErr); } string sUserName = ""; sUserName = ui.GetSessionUserFullName(); if (string.IsNullOrEmpty(sUsersEmail) || sUsersEmail.Length < 5) { // all good, no email so notify user return("Notification settings updated.\n\nNo email on file for user " + sUserName + " - unable to send a test message"); } else { // create a test email ui.SendEmailMessage(sUsersEmail, ag.APP_COMPANYNAME + " Account Management", ag.APP_COMPANYNAME + " Messenger configuration change.", "<html><head></head><body><p>" + sUserName + ",</p><p>This is a test mail to confirm the smtp server that you have configured.</p><p>Do not reply to this message, and feel free to delete it.</p><p>Regards,\n\n" + ag.APP_COMPANYNAME + " Administration team.</p></body></html>", ref sErr); if (sErr != "") { return("Update completed. Unable to create test message: " + sErr); } } return("Notification settings updated. A test email will be sent to " + sUsersEmail + "."); } else { return("Notification settings updated."); } } }
private bool GetDetails(string sTaskInstance, ref string sErr) { try { string sSQL = "select ti.task_instance, ti.task_id, '' as asset_id, ti.task_status, ti.submitted_by_instance, " + " ti.submitted_dt, ti.started_dt, ti.completed_dt, ti.ce_node, ti.pid, ti.debug_level," + " t.task_name, t.version, '' as asset_name, u.full_name," + " ar.app_instance, ar.platform, ar.hostname," + " t.concurrent_instances, t.queue_depth," + " ti.ecosystem_id, d.ecosystem_name, ti.account_id, ca.account_name" + " from tv_task_instance ti" + " join task t on ti.task_id = t.task_id" + " left outer join users u on ti.submitted_by = u.user_id" + " left outer join tv_application_registry ar on ti.ce_node = ar.id" + " left outer join cloud_account ca on ti.account_id = ca.account_id" + " left outer join ecosystem d on ti.ecosystem_id = d.ecosystem_id" + " where task_instance = " + sTaskInstance; DataRow dr = null; if (!dc.sqlGetDataRow(ref dr, sSQL, ref sErr)) { return(false); } if (dr != null) { int iConcurrent = 0; int.TryParse(dr["concurrent_instances"].ToString(), out iConcurrent); int iQueueDepth = 0; int.TryParse(dr["queue_depth"].ToString(), out iQueueDepth); hidTaskID.Value = dr["task_id"].ToString(); hidAssetID.Value = dr["asset_id"].Equals(System.DBNull.Value) ? "" : dr["asset_id"].ToString(); hidDebugLevel.Value = dr["debug_level"].Equals(System.DBNull.Value) ? "" : dr["debug_level"].ToString(); lblTaskInstance.Text = dr["task_instance"].ToString(); lblTaskName.Text = dr["task_name"].ToString() + " - Version " + dr["version"].ToString(); lblStatus.Text = dr["task_status"].ToString(); lblAssetName.Text = (dr["asset_name"].Equals(System.DBNull.Value) ? "N/A" : dr["asset_name"].ToString()); lblSubmittedDT.Text = (dr["submitted_dt"].Equals(System.DBNull.Value) ? "" : dr["submitted_dt"].ToString()); lblStartedDT.Text = (dr["started_dt"].Equals(System.DBNull.Value) ? "" : dr["started_dt"].ToString()); lblCompletedDT.Text = (dr["completed_dt"].Equals(System.DBNull.Value) ? "" : dr["completed_dt"].ToString()); lblCENode.Text = (dr["ce_node"].Equals(System.DBNull.Value) ? "" : dr["app_instance"].ToString() + " (" + dr["platform"].ToString() + ")"); lblPID.Text = (dr["pid"].Equals(System.DBNull.Value) ? "" : dr["pid"].ToString()); if (lblPID.Text != "") { string sEncID = dc.EnCrypt(ui.GetSessionUserID()); //can't build the link until we know what port we need. sSQL = "select port from logserver_settings where id = 1"; string sPort = ""; dc.sqlGetSingleString(ref sPort, sSQL, ref sErr); if (string.IsNullOrEmpty(sPort)) { sPort = "4000"; } hidCELogFile.Value = "http://" + dr["hostname"].ToString() + ":" + sPort + "/getlog?logtype=ce&q=" + sEncID + "&logfile=" + sTaskInstance + ".log"; } hidSubmittedByInstance.Value = dr["submitted_by_instance"].Equals(System.DBNull.Value) ? "" : dr["submitted_by_instance"].ToString(); lblSubmittedByInstance.Text = (dr["submitted_by_instance"].Equals(System.DBNull.Value) ? "N/A" : dr["submitted_by_instance"].ToString()); if (hidSubmittedByInstance.Value != "") { lblSubmittedByInstance.CssClass = "link"; } hidEcosystemID.Value = dr["ecosystem_id"].Equals(System.DBNull.Value) ? "" : dr["ecosystem_id"].ToString(); lblEcosystemName.Text = dr["ecosystem_name"].Equals(System.DBNull.Value) ? "" : dr["ecosystem_name"].ToString(); hidAccountID.Value = dr["account_id"].Equals(System.DBNull.Value) ? "" : dr["account_id"].ToString(); lblAccountName.Text = dr["account_name"].Equals(System.DBNull.Value) ? "" : dr["account_name"].ToString(); if (!dr["full_name"].Equals(System.DBNull.Value)) { //launched by a user lblSubmittedBy.Text = dr["full_name"].ToString(); } else { lblSubmittedBy.Text = "Scheduler"; } // else if (!dr["schedule_instance_name"].Equals(System.DBNull.Value)) // { // //launched by scheduler // lblSubmittedBy.Text = " Schedule (" + dr["schedule_instance_name"].ToString() + ")"; // } //superusers AND those tagged with this Task can see the stop and resubmit button if (ui.UserIsInRole("Developer") || ui.UserIsInRole("Administrator") || ui.UserAndObjectTagsMatch(dr["original_task_id"].ToString(), 3)) { phResubmit.Visible = true; phCancel.Visible = true; } else { phResubmit.Visible = false; phCancel.Visible = false; } //if THIS instance is 'active', show additional warning info on the resubmit confirmation. //and if it's not, don't show the "cancel" button if ("processing,queued,submitted,pending,aborting,queued,staged".IndexOf(dr["task_status"].ToString().ToLower()) > -1) { lblResubmitMessage.Text = "This Task is currently active. You have requested to start another instance.<br /><br />"; } else { phCancel.Visible = false; } //check for OTHER active instances int iActiveCount = 0; sSQL = "select count(*) from tv_task_instance where task_id = '" + dr["task_id"].ToString() + "'" + " and task_instance <> '" + sTaskInstance + "'" + " and task_status in ('processing','submitted','pending','aborting','queued','staged')"; if (!dc.sqlGetSingleInteger(ref iActiveCount, sSQL, ref sErr)) { ui.RaiseError(Page, sErr, true, ""); return(false); } //and hide the resubmit button if we're over the limit //if active < concurrent do nothing //if active >= concurrent but there's room in the queue, change the message //if this one would pop the queue, hide the button if (iActiveCount > 0) { if (iConcurrent + iQueueDepth > 0) { if (iActiveCount >= iConcurrent && (iActiveCount + 1) <= iQueueDepth) { lblResubmitMessage.Text = "The maximum concurrent instances for this Task are running. This request will be queued.<br /><br />"; } else { phResubmit.Visible = false; } } //neato... show the user a list of all the other instances! sSQL = "select task_instance, task_status from tv_task_instance" + " where task_id = '" + dr["task_id"].ToString() + "'" + " and task_instance <> '" + sTaskInstance + "'" + " and task_status in ('processing','submitted','pending','aborting','queued','staged')" + " order by task_status"; DataTable dt = new DataTable(); if (!dc.sqlGetDataTable(ref dt, sSQL, ref sErr)) { ui.RaiseError(Page, sErr, true, ""); return(false); } rpOtherInstances.DataSource = dt; rpOtherInstances.DataBind(); pnlOtherInstances.Visible = true; } return(true); } else { return(false); } } catch (Exception ex) { throw ex; } }
public static string SaveNotifications(object[] oAsset) { dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); acUI.AppGlobals ag = new acUI.AppGlobals(); string sErr = ""; string sMessengerOnOff = oAsset[0].ToString(); string sPollLoop = oAsset[1].ToString(); string sRetryDelay = oAsset[2].ToString(); string sRetryMaxAttempts = oAsset[3].ToString(); string sSMTPServerAddress = oAsset[4].ToString().Replace("'", "''"); string sSMTPUserAccount = oAsset[5].ToString().Replace("'", "''"); string sSMTPUserPassword = oAsset[6].ToString(); string sSMTPServerPort = oAsset[7].ToString(); string sFromEmail = oAsset[8].ToString().Replace("'", "''"); string sFromName = oAsset[9].ToString().Replace("'", "''"); string sAdminEmail = oAsset[10].ToString().Replace("'", "''"); // get the current settings for the logging string sOrigMessengerOnOff = ""; string sOrigPollLoop = ""; string sOrigRetryDelay = ""; string sOrigRetryMaxAttempts = ""; string sOrigSMTPServerAddress = ""; string sOrigSMTPUserAccount = ""; string sOrigSMTPServerPort = ""; string sOrigFromEmail = ""; string sOrigFromName = ""; string sOrigAdminEmail = ""; string sSQL = "select mode_off_on, loop_delay_sec, retry_delay_min, retry_max_attempts," + " smtp_server_addr, smtp_server_user, smtp_server_password, smtp_server_port, from_email, from_name, admin_email" + " from messenger_settings" + " where id = 1"; DataTable dt = new DataTable(); if (!dc.sqlGetDataTable(ref dt, sSQL, ref sErr)) { return "Unable to continue. " + sErr; } if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; sOrigMessengerOnOff = dr["mode_off_on"].ToString(); sOrigPollLoop = dr["loop_delay_sec"].ToString(); sOrigRetryDelay = dr["retry_delay_min"].ToString(); sOrigRetryMaxAttempts = dr["retry_max_attempts"].ToString(); sOrigSMTPServerAddress = dr["smtp_server_addr"].ToString(); sOrigSMTPUserAccount = dr["smtp_server_user"].ToString(); sOrigSMTPServerPort = dr["smtp_server_port"].ToString(); sOrigFromEmail = dr["from_email"].ToString(); sOrigFromName = dr["from_name"].ToString(); sOrigAdminEmail = dr["admin_email"].ToString(); } sSQL = "update messenger_settings set mode_off_on='{0}', loop_delay_sec={1}, retry_delay_min={2}, retry_max_attempts={3}, smtp_server_addr='{4}', smtp_server_user='******', smtp_server_port={6}, from_email='{7}', from_name='{8}', admin_email='{9}'"; //only update password if it has been changed. string sPasswordFiller = "($%#d@x!&"; if (sSMTPUserPassword != sPasswordFiller) { sSQL += ",smtp_server_password='******'"; } sSQL = string.Format(sSQL, sMessengerOnOff, sPollLoop, sRetryDelay, sRetryMaxAttempts, sSMTPServerAddress, sSMTPUserAccount, sSMTPServerPort, sFromEmail, sFromName, sAdminEmail, dc.EnCrypt(sSMTPUserPassword)); if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { return "Update failed: " + sErr; } else { //logging var sLogObject = "Manage Notifications"; ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "Messenger On / Off", sOrigMessengerOnOff, sMessengerOnOff); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "Poll Loop", sOrigPollLoop, sPollLoop); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "Retry Delay", sOrigRetryDelay, sRetryDelay); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "Retry Max Attempts", sOrigRetryMaxAttempts, sRetryMaxAttempts); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "SMTP Server Address", sOrigSMTPServerAddress, sSMTPServerAddress); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "SMTP User Account", sOrigSMTPUserAccount, sSMTPUserAccount); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "SMTP Server Port", sOrigSMTPServerPort, sSMTPServerPort); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "From Email", sOrigFromEmail, sFromEmail); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "From Name", sOrigFromName, sFromName); ui.WriteObjectChangeLog(acObjectTypes.None, sLogObject, "From Name", sOrigAdminEmail, sAdminEmail); // send a notification to the user that made the change if (sMessengerOnOff == "on") { // get the users email, if they do not have an email tell them no message was created. string sUsersEmail = null; string sUserID = ui.GetSessionUserID(); sSQL = "select email from users where user_id = '" + sUserID + "'"; if (!dc.sqlGetSingleString(ref sUsersEmail, sSQL, ref sErr)) { return "Unable to create test email: " + sErr; } string sUserName = ""; sUserName = ui.GetSessionUserFullName(); if (string.IsNullOrEmpty(sUsersEmail) || sUsersEmail.Length < 5) { // all good, no email so notify user return "Notification settings updated.\n\nNo email on file for user " + sUserName + " - unable to send a test message"; } else { // create a test email ui.SendEmailMessage(sUsersEmail, ag.APP_COMPANYNAME + " Account Management", ag.APP_COMPANYNAME + " Messenger configuration change.", "<html><head></head><body><p>" + sUserName + ",</p><p>This is a test mail to confirm the smtp server that you have configured.</p><p>Do not reply to this message, and feel free to delete it.</p><p>Regards,\n\n" + ag.APP_COMPANYNAME + " Administration team.</p></body></html>", ref sErr); if (sErr != "") { return "Update completed. Unable to create test message: " + sErr; } } return "Notification settings updated. A test email will be sent to " + sUsersEmail + "."; } else { return "Notification settings updated."; } } }
public static string SaveCredential(object[] oAsset) { // we are passing in 16 elements, if we have 16 go if (oAsset.Length != 8) { return("Incorrect list of attributes:" + oAsset.Length.ToString()); } string sCredentialID = oAsset[0].ToString(); string sCredentialName = oAsset[1].ToString().Replace("'", "''"); string sUserName = oAsset[2].ToString().Replace("'", "''"); string sCredentialDesc = oAsset[3].ToString().Replace("'", "''"); string sPassword = oAsset[4].ToString(); string sDomain = oAsset[5].ToString(); string sMode = oAsset[6].ToString(); string sPrivilegedPassword = oAsset[7].ToString(); // for logging string sOriginalUserName = null; dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); string sSql = null; string sErr = null; //if we are editing get the original values if (sMode == "edit") { sSql = "select username from asset_credential " + "where credential_id = '" + sCredentialID + "'"; if (!dc.sqlGetSingleString(ref sOriginalUserName, sSql, ref sErr)) { throw new Exception(sErr); } } try { dataAccess.acTransaction oTrans = new dataAccess.acTransaction(ref sErr); // update the user fields. if (sMode == "edit") { // only update the passwword if it has changed string sNewPassword = ""; if (sPassword != "($%#d@x!&") { sNewPassword = "******" + dc.EnCrypt(sPassword) + "'"; } // bugzilla 1260 // same for privileged_password string sPriviledgedPasswordUpdate = null; if (sPrivilegedPassword == "($%#d@x!&") { // password has not been touched sPriviledgedPasswordUpdate = ""; } else { // updated password sPriviledgedPasswordUpdate = ",privileged_password = '******'"; } sSql = "update asset_credential set" + " credential_name = '" + sCredentialName + "'," + " username = '******'," + " domain = '" + sDomain.Replace("'", "''") + "'," + " shared_cred_desc = '" + sCredentialDesc + "'" + sNewPassword + sPriviledgedPasswordUpdate + " where credential_id = '" + sCredentialID + "'"; } else { // if the priviledged password is empty just set it to null string sPrivilegedPasswordUpdate = "NULL"; if (sPrivilegedPassword.Length != 0) { sPrivilegedPasswordUpdate = "'" + dc.EnCrypt(sPrivilegedPassword) + "'"; } ; sSql = "insert into asset_credential (credential_id, credential_name, username, password, domain, shared_cred_desc, shared_or_local, privileged_password)" + " values (" + "'" + ui.NewGUID() + "'," + "'" + sCredentialName.Replace("'", "''") + "'," + "'" + sUserName.Replace("'", "''") + "'," + "'" + dc.EnCrypt(sPassword) + "'," + "'" + sDomain.Replace("'", "''") + "'," + "'" + sCredentialDesc.Replace("'", "''") + "'," + "'0'," + sPrivilegedPasswordUpdate + ")"; } oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { if (sErr == "key_violation") { throw new Exception("A Credential with that name already exists. Please select another name."); } else { throw new Exception(sErr); } } oTrans.Commit(); } catch (Exception ex) { throw new Exception(ex.Message); } // add security log // since this is not handled as a page postback, theres no "Viewstate" settings // so 2 options either we keep an original setting for each value in hid values, or just get them from the db as part of the // update above, since we are already passing in 15 or so fields, lets just get the values at the start and reference them here if (sMode == "edit") { ui.WriteObjectChangeLog(Globals.acObjectTypes.Credential, sCredentialID, sUserName.Replace("'", "''"), sOriginalUserName, sUserName.Replace("'", "''")); } else { ui.WriteObjectAddLog(Globals.acObjectTypes.Credential, sCredentialID, sUserName.Replace("'", "''"), "Credential Created"); } // no errors to here, so return an empty string return(""); }
public static string ResetPassword(string sUserID) { dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); acUI.AppGlobals ag = new acUI.AppGlobals(); string sSQL = null; string sErr = null; //get the details of this user sSQL = "select u.username, u.full_name, u.email, u.authentication_type" + " from users u " + " where u.user_id = '" + sUserID + "'"; DataRow dr = null; if (!dc.sqlGetDataRow(ref dr, sSQL, ref sErr)) { throw new Exception(sErr); } if (dr != null) { if (!string.IsNullOrEmpty(dr["email"].ToString())) { string sEmail = dr["email"].ToString(); string sNewPassword = dc.GenerateNewPassword(); sSQL = "update users set user_password = '******' where user_id = '" + sUserID + "'"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { throw new Exception(sErr); } // add security log ui.WriteObjectAddLog(Globals.acObjectTypes.User, sUserID, sUserID, "Password Reset"); //email out the password string sBody = ""; if (!dc.sqlGetSingleString(ref sBody, "select new_user_email_message from login_security_settings where id = 1", ref sErr)) { throw new Exception(sErr); } //default message if undefined in the table if (string.IsNullOrEmpty(sBody)) { sBody = dr["full_name"].ToString() + " - your password has been reset by an Administrator." + Environment.NewLine + Environment.NewLine + "Your temporary password is: " + sNewPassword + "." + Environment.NewLine; } //replace our special tokens with the values sBody = sBody.Replace("##FULLNAME##", dr["full_name"].ToString()).Replace("##USERNAME##", dr["username"].ToString()).Replace("##PASSWORD##", sNewPassword); if (!ui.SendEmailMessage(sEmail.Trim(), ag.APP_COMPANYNAME + " Account Management", "Account Action in " + ag.APP_NAME, sBody, ref sErr)) { throw new Exception(sErr); } } else { return("Unable to reset - user does not have an email address defined."); } } return(""); }
public static string SaveAsset(object[] oAsset) { // check the # of elements in the array if (oAsset.Length != 19) return "Incorrect number of Asset Properties:" + oAsset.Length.ToString(); string sAssetID = oAsset[0].ToString(); string sAssetName = oAsset[1].ToString().Replace("'", "''"); string sDbName = oAsset[2].ToString().Replace("'", "''"); string sPort = oAsset[3].ToString(); string sConnectionType = oAsset[4].ToString(); string sIsConnection = "0"; // oAsset[5].ToString(); string sAddress = oAsset[5].ToString().Replace("'", "''"); // mode is edit or add string sMode = oAsset[6].ToString(); string sCredentialID = oAsset[7].ToString(); string sCredUsername = oAsset[8].ToString().Replace("'", "''"); string sCredPassword = oAsset[9].ToString().Replace("'", "''"); string sShared = oAsset[10].ToString(); string sCredentialName = oAsset[11].ToString().Replace("'", "''"); string sCredentialDescr = oAsset[12].ToString().Replace("'", "''"); string sDomain = oAsset[13].ToString().Replace("'", "''"); string sCredentialType = oAsset[14].ToString(); string sAssetStatus = oAsset[15].ToString(); string sPrivilegedPassword = oAsset[16].ToString(); string sTagArray = oAsset[17].ToString(); string sConnString = oAsset[18].ToString().Replace("'", "''"); // for logging string sOriginalAssetName = ""; string sOriginalPort = ""; string sOriginalDbName = ""; string sOriginalAddress = ""; string sOriginalConnectionType = ""; string sOriginalUserName = ""; string sOriginalConnString = ""; string sOriginalCredentialID = ""; string sOriginalAssetStatus = ""; dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); string sSql = null; string sErr = null; //if we are editing get the original values //this is getting original values for logging purposes if (sMode == "edit") { DataRow dr = null; sSql = "select a.asset_name, a.asset_status, a.port, a.db_name, a.address, a.db_name, a.connection_type, a.conn_string, ac.username, a.credential_id," + " case when a.is_connection_system = '1' then 'Yes' else 'No' end as is_connection_system " + " from asset a " + " left outer join asset_credential ac on ac.credential_id = a.credential_id " + " where a.asset_id = '" + sAssetID + "'"; if (!dc.sqlGetDataRow(ref dr, sSql, ref sErr)) throw new Exception(sErr); else { if (dr != null) { sOriginalAssetName = dr["asset_name"].ToString(); sOriginalPort = (object.ReferenceEquals(dr["port"], DBNull.Value) ? "" : dr["port"].ToString()); sOriginalDbName = (object.ReferenceEquals(dr["db_name"], DBNull.Value) ? "" : dr["db_name"].ToString()); sOriginalAddress = (object.ReferenceEquals(dr["address"], DBNull.Value) ? "" : dr["address"].ToString()); sOriginalConnectionType = (object.ReferenceEquals(dr["connection_type"], DBNull.Value) ? "" : dr["connection_type"].ToString()); sOriginalUserName = (object.ReferenceEquals(dr["username"], DBNull.Value) ? "" : dr["username"].ToString()); sOriginalConnString = (object.ReferenceEquals(dr["conn_string"], DBNull.Value) ? "" : dr["conn_string"].ToString()); sOriginalCredentialID = (object.ReferenceEquals(dr["credential_id"], DBNull.Value) ? "" : dr["credential_id"].ToString()); sOriginalAssetStatus = dr["asset_status"].ToString(); } } } //NOTE NOTE NOTE! //the following is a catch 22. //if we're adding a new asset, we will need to figure out the credential first so we can save the credential id on the asset //but if it's a new local credential, it gets the asset id as it's name. //so......... //if it's a new asset, go ahead and get the new guid for it here so the credential add will work. if (sMode == "add") sAssetID = ui.NewGUID(); //and move on... // there are three CredentialType's // 1) 'selected' = user selected a different credential, just save the credential_id // 2) 'new' = user created a new shared or local credential // 3) 'existing' = same credential, just update the username,description ad password string sPriviledgedPasswordUpdate = null; if (sCredentialType == "new") { if (sPrivilegedPassword.Length == 0) sPriviledgedPasswordUpdate = "NULL"; else sPriviledgedPasswordUpdate = "'" + dc.EnCrypt(sPrivilegedPassword) + "'"; //if it's a local credential, the credential_name is the asset_id. //if it's shared, there will be a name. if (sShared == "1") { sCredentialName = sAssetID; //whack and add - easiest way to avoid conflicts sSql = "delete from asset_credential where credential_name = '" + sCredentialName + "' and shared_or_local = '1'"; if (!dc.sqlExecuteUpdate(sSql, ref sErr)) throw new Exception(sErr); } //now we're clear to add sCredentialID = "'" + ui.NewGUID() + "'"; sSql = "insert into asset_credential " + "(credential_id,credential_name,username,password,domain,shared_or_local,shared_cred_desc,privileged_password) " + "values (" + sCredentialID + ",'" + sCredentialName + "','" + sCredUsername + "','" + dc.EnCrypt(sCredPassword) + "','" + sDomain + "','" + sShared + "','" + sCredentialDescr + "'," + sPriviledgedPasswordUpdate + ")"; if (!dc.sqlExecuteUpdate(sSql, ref sErr)) { if (sErr == "key_violation") throw new Exception("A Credential with that name already exists. Please select another name."); else throw new Exception(sErr); } // add security log ui.WriteObjectAddLog(Globals.acObjectTypes.Credential, sCredentialID, sCredentialName, ""); } else if (sCredentialType == "existing") { sCredentialID = "'" + sCredentialID + "'"; // bugzilla 1126 if the password has not changed leave it as is. string sPasswordUpdate = null; if (sCredPassword == "($%#d@x!&") // password has not been touched sPasswordUpdate = ""; else // updated password sPasswordUpdate = ",password = '******'"; // bugzilla 1260 // same for privileged_password if (sPrivilegedPassword == "($%#d@x!&") // password has not been touched sPriviledgedPasswordUpdate = ""; else { // updated password // bugzilla 1352 priviledged password can be blank, so if it is, set it to null if (sPrivilegedPassword.Length == 0) sPriviledgedPasswordUpdate = ",privileged_password = null"; else sPriviledgedPasswordUpdate = ",privileged_password = '******'"; } sSql = "update asset_credential " + "set username = '******'" + sPasswordUpdate + sPriviledgedPasswordUpdate + ",domain = '" + sDomain + "'," + "shared_or_local = '" + sShared + "',shared_cred_desc = '" + sCredentialDescr + "'" + "where credential_id = " + sCredentialID; if (!dc.sqlExecuteUpdate(sSql, ref sErr)) throw new Exception(sErr); // add security log ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + "Changed credential", sOriginalUserName, sCredUsername); } else { // user selected a shared credential // remove the local credential if one exists if (sOriginalCredentialID.Length > 0) { sSql = "delete from asset_credential where credential_id = '" + sOriginalCredentialID + "' and shared_or_local = '1'"; if (!dc.sqlExecuteUpdate(sSql, ref sErr)) throw new Exception(sErr); // add security log ui.WriteObjectDeleteLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''"), "Credential deleted" + sOriginalCredentialID + " " + sOriginalUserName); } sCredentialID = "'" + sCredentialID + "'"; } // checks that cant be done on the client side // is the name unique? string sInuse = ""; if (sMode == "edit") sSql = "select asset_id from asset where asset_name = '" + sAssetName.Trim() + "' and asset_id <> '" + sAssetID + "' limit 1"; else sSql = "select asset_id from asset where asset_name = '" + sAssetName.Trim() + "' limit 1"; if (!dc.sqlGetSingleString(ref sInuse, sSql, ref sErr)) throw new Exception(sErr); else if (!string.IsNullOrEmpty(sInuse)) return "Asset Name '" + sAssetName + "' already in use, choose another." + sAssetID; try { dataAccess.acTransaction oTrans = new dataAccess.acTransaction(ref sErr); if (sMode == "edit") { sSql = "update asset set asset_name = '" + sAssetName + "'," + " asset_status = '" + sAssetStatus + "'," + " address = '" + sAddress + "'" + "," + " conn_string = '" + sConnString + "'" + "," + " db_name = '" + sDbName + "'," + " port = " + (sPort == "" ? "NULL" : "'" + sPort + "'") + "," + " connection_type = '" + sConnectionType + "'," + " is_connection_system = '" + (sIsConnection == "Yes" ? 1 : 0) + "'," + " credential_id = " + sCredentialID + " where asset_id = '" + sAssetID + "'"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) throw new Exception(sErr); } else { sSql = "insert into asset (asset_id,asset_name,asset_status,address,conn_string,db_name,port,connection_type,is_connection_system,credential_id)" + " values (" + "'" + sAssetID + "'," + "'" + sAssetName + "'," + "'" + sAssetStatus + "'," + "'" + sAddress + "'," + "'" + sConnString + "'," + "'" + sDbName + "'," + (sPort == "" ? "NULL" : "'" + sPort + "'") + "," + "'" + sConnectionType + "'," + "'0'," + sCredentialID + ")"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) throw new Exception(sErr); } #region "tags" // remove the existing tags sSql = "delete from object_tags where object_id = '" + sAssetID + "'"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } // add user groups, if there are any if (sTagArray.Length > 0) { ArrayList aTags = new ArrayList(sTagArray.Split(',')); foreach (string sTagName in aTags) { sSql = "insert object_tags (object_id, object_type, tag_name)" + " values ('" + sAssetID + "', 2, '" + sTagName + "')"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } } } #endregion oTrans.Commit(); } catch (Exception ex) { throw new Exception(ex.Message); } //-------------------------------------------------------------------------------------------------- // NOTE! too many if edit... probably need to just make 2 functions, update asset, and create asset //-------------------------------------------------------------------------------------------------- // add security log // since this is not handled as a page postback, theres no "Viewstate" settings // so 2 options either we keep an original setting for each value in hid values, or just get them from the db as part of the // update above, since we are already passing in 15 or so fields, lets just get the values at the start and reference them here if (sMode == "edit") { string sOrigCredUsername = GetCredentialNameFromID(sOriginalCredentialID.Replace("'", "")).ToString(); string sCurrentCredUsername = GetCredentialNameFromID(sCredentialID.Replace("'", "")).ToString(); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Name", sOriginalAssetName, sAssetName); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Address", sOriginalAddress, sAddress); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Port", sOriginalPort, sPort); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " DB Name", sOriginalDbName, sDbName); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Connection Type", sOriginalConnectionType, sConnectionType); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Credential", sOrigCredUsername, sCurrentCredUsername); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " Status", sOriginalAssetStatus, sAssetStatus); ui.WriteObjectChangeLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''") + " ConnString", sOriginalConnString, sConnString); } else { ui.WriteObjectAddLog(Globals.acObjectTypes.Asset, sAssetID, sAssetName.Trim().Replace("'", "''"), "Asset Created"); } // no errors to here, so return an empty string return ""; }
public static string SaveAccount(string sMode, string sAccountID, string sAccountName, string sAccountNumber, string sProvider, string sLoginID, string sLoginPassword, string sLoginPasswordConfirm, string sIsDefault, string sAutoManageSecurity) { // for logging string sOriginalName = ""; dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); string sSql = ""; string sErr = ""; //if we are editing get the original values if (sMode == "edit") { } try { dataAccess.acTransaction oTrans = new dataAccess.acTransaction(ref sErr); // update the user fields. if (sMode == "edit") { sSql = "select account_name from cloud_account " + "where account_id = '" + sAccountID + "'"; if (!dc.sqlGetSingleString(ref sOriginalName, sSql, ref sErr)) { throw new Exception("Error getting original account name:" + sErr); } // only update the passwword if it has changed string sNewPassword = ""; if (sLoginPassword != "($%#d@x!&") { sNewPassword = "******" + dc.EnCrypt(sLoginPassword) + "'"; } sSql = "update cloud_account set" + " account_name = '" + sAccountName + "'," + " account_number = '" + sAccountNumber + "'," + " provider = '" + sProvider + "'," + " is_default = '" + sIsDefault + "'," + " auto_manage_security = '" + sAutoManageSecurity + "'," + " login_id = '" + sLoginID + "'" + sNewPassword + " where account_id = '" + sAccountID + "'"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception("Error updating account: " + sErr); } ui.WriteObjectChangeLog(Globals.acObjectTypes.CloudAccount, sAccountID, sAccountName, sOriginalName, sAccountName); } else { //now, for some reason we were having issues with the initial startup of apache //not able to perform the very first database hit. //this line serves as an inital db hit, but we aren't trapping it or showing the error dc.TestDBConnection(ref sErr); //if there are no rows yet, make this one the default even if the box isn't checked. if (sIsDefault == "0") { int iExists = -1; sSql = "select count(*) as cnt from cloud_account"; if (!dc.sqlGetSingleInteger(ref iExists, sSql, ref sErr)) { System.Threading.Thread.Sleep(300); if (!dc.sqlGetSingleInteger(ref iExists, sSql, ref sErr)) { System.Threading.Thread.Sleep(300); if (!dc.sqlGetSingleInteger(ref iExists, sSql, ref sErr)) { throw new Exception("Unable to count Cloud Accounts: " + sErr); } } } if (iExists == 0) { sIsDefault = "1"; } } sAccountID = ui.NewGUID(); sSql = "insert into cloud_account (account_id, account_name, account_number, provider, is_default, login_id, login_password, auto_manage_security)" + " values ('" + sAccountID + "'," + "'" + sAccountName + "'," + "'" + sAccountNumber + "'," + "'" + sProvider + "'," + "'" + sIsDefault + "'," + "'" + sLoginID + "'," + "'" + dc.EnCrypt(sLoginPassword) + "'," + "'" + sAutoManageSecurity + "')"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception("Error creating account: " + sErr); } ui.WriteObjectAddLog(Globals.acObjectTypes.CloudAccount, sAccountID, sAccountName, "Account Created"); } //if "default" was selected, unset all the others if (dc.IsTrue(sIsDefault)) { oTrans.Command.CommandText = "update cloud_account set is_default = 0 where account_id <> '" + sAccountID + "'"; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception("Error updating defaults: " + sErr); } } oTrans.Commit(); //refresh the cloud account list in the session if (!ui.PutCloudAccountsInSession(ref sErr)) { throw new Exception("Error refreshing accounts in session: " + sErr); } } catch (Exception ex) { throw new Exception("Error: General Exception: " + ex.Message); } // no errors to here, so return an empty string return("{'account_id':'" + sAccountID + "', 'account_name':'" + sAccountName + "', 'provider':'" + sProvider + "'}"); }
public string wmUpdateTaskParam(string sType, string sID, string sParamID, string sName, string sDesc, string sRequired, string sPrompt, string sEncrypt, string sPresentAs, string sValues) { dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); FunctionTemplates.HTMLTemplates ft = new FunctionTemplates.HTMLTemplates(); if (!ui.IsGUID(sID)) throw new Exception("Invalid or missing ID."); string sErr = ""; string sSQL = ""; //we encoded this in javascript before the ajax call. //the safest way to unencode it is to use the same javascript lib. //(sometimes the javascript and .net libs don't translate exactly, google it.) sDesc = ui.unpackJSON(sDesc).Trim(); //normalize and clean the values sRequired = (dc.IsTrue(sRequired) ? "true" : "false"); sPrompt = (dc.IsTrue(sPrompt) ? "true" : "false"); sEncrypt = (dc.IsTrue(sEncrypt) ? "true" : "false"); sName = sName.Trim().Replace("'", "''"); string sTable = ""; string sXML = ""; string sParameterXPath = "//parameter[@id = \"" + sParamID + "\"]"; //using this to keep the code below cleaner. if (sType == "ecosystem") sTable = "ecosystem"; else if (sType == "task") sTable = "task"; bool bParamAdd = false; //bool bParamUpdate = false; //if sParamID is empty, we are adding if (string.IsNullOrEmpty(sParamID)) { sParamID = "p_" + ui.NewGUID(); sParameterXPath = "//parameter[@id = \"" + sParamID + "\"]"; //reset this if we had to get a new id //does the task already have parameters? sSQL = "select parameter_xml from " + sTable + " where " + sType + "_id = '" + sID + "'"; if (!dc.sqlGetSingleString(ref sXML, sSQL, ref sErr)) throw new Exception(sErr); string sAddXML = "<parameter id=\"" + sParamID + "\" required=\"" + sRequired + "\" prompt=\"" + sPrompt + "\" encrypt=\"" + sEncrypt + "\">" + "<name>" + sName + "</name>" + "<desc>" + sDesc + "</desc>" + "</parameter>"; if (string.IsNullOrEmpty(sXML)) { //XML doesn't exist at all, add it to the record sAddXML = "<parameters>" + sAddXML + "</parameters>"; sSQL = "update " + sTable + " set " + " parameter_xml = '" + sAddXML + "'" + " where " + sType + "_id = '" + sID + "'"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) throw new Exception(sErr); bParamAdd = true; } else { //XML exists, add the node to it ft.AddNodeToXMLColumn(sTable, "parameter_xml", sType + "_id = '" + sID + "'", "//parameters", sAddXML); bParamAdd = true; } } else { //update the node values ft.SetNodeValueinXMLColumn(sTable, "parameter_xml", sType + "_id = '" + sID + "'", sParameterXPath + "/name", sName); ft.SetNodeValueinXMLColumn(sTable, "parameter_xml", sType + "_id = '" + sID + "'", sParameterXPath + "/desc", sDesc); //and the attributes ft.SetNodeAttributeinXMLColumn(sTable, "parameter_xml", sType + "_id = '" + sID + "'", sParameterXPath, "required", sRequired); ft.SetNodeAttributeinXMLColumn(sTable, "parameter_xml", sType + "_id = '" + sID + "'", sParameterXPath, "prompt", sPrompt); ft.SetNodeAttributeinXMLColumn(sTable, "parameter_xml", sType + "_id = '" + sID + "'", sParameterXPath, "encrypt", sEncrypt); bParamAdd = false; } // not clean at all handling both tasks and ecosystems in the same method, but whatever. if (bParamAdd) { if (sType == "task") { ui.WriteObjectAddLog(Globals.acObjectTypes.Task, sID, "Parameter", "Added Parameter:" + sName ); }; if (sType == "ecosystem") { ui.WriteObjectAddLog(Globals.acObjectTypes.Ecosystem, sID, "Parameter", "Added Parameter:" + sName); }; } else { // would be a lot of trouble to add the from to, why is it needed you have each value in the log, just scroll back // so just add a changed message to the log if (sType == "task") { dc.addSecurityLog(ui.GetSessionUserID(), Globals.SecurityLogTypes.Object, Globals.SecurityLogActions.ObjectModify, Globals.acObjectTypes.Task, sID, "Parameter Changed:[" + sName + "]", ref sErr); }; if (sType == "ecosystem") { dc.addSecurityLog(ui.GetSessionUserID(), Globals.SecurityLogTypes.Object, Globals.SecurityLogActions.ObjectModify, Globals.acObjectTypes.Ecosystem, sID, "Parameter Changed:[" + sName + "]", ref sErr); }; } //update the values string[] aValues = sValues.Split('|'); string sValueXML = ""; foreach (string sVal in aValues) { string sReadyValue = ""; //if encrypt is true we MIGHT want to encrypt this value. //but it might simply be a resubmit of an existing value in which case we DON'T //if it has oev: as a prefix, it needs no additional work if (dc.IsTrue(sEncrypt)) { if (sVal.IndexOf("oev:") > -1) sReadyValue = sVal.Replace("oev:", ""); else sReadyValue = dc.EnCrypt(ui.unpackJSON(sVal)); } else { sReadyValue = ui.unpackJSON(sVal); } sValueXML += "<value id=\"pv_" + ui.NewGUID() + "\">" + sReadyValue + "</value>"; } sValueXML = "<values present_as=\"" + sPresentAs + "\">" + sValueXML + "</values>"; //whack-n-add ft.RemoveNodeFromXMLColumn(sTable, "parameter_xml", sType + "_id = '" + sID + "'", sParameterXPath + "/values"); ft.AddNodeToXMLColumn(sTable, "parameter_xml", sType + "_id = '" + sID + "'", sParameterXPath, sValueXML); return ""; }
public static string SaveKeyPair(string sKeypairID, string sAccountID, string sName, string sPK, string sPP) { acUI.acUI ui = new acUI.acUI(); if (string.IsNullOrEmpty(sName)) { return("KeyPair Name is Required."); } //we encoded this in javascript before the ajax call. //the safest way to unencode it is to use the same javascript lib. //(sometimes the javascript and .net libs don't translate exactly, google it.) sPK = ui.unpackJSON(sPK); bool bUpdatePK = false; if (sPK != "-----BEGIN RSA PRIVATE KEY-----\n**********\n-----END RSA PRIVATE KEY-----") { //we want to make sure it's not just the placeholder, but DOES have the wrapper. //and 61 is the lenght of the wrapper with no content... effectively empty if (sPK.StartsWith("-----BEGIN RSA PRIVATE KEY-----\n") && sPK.EndsWith("\n-----END RSA PRIVATE KEY-----")) { //now, is there truly something in it? string sContent = sPK.Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "").Replace("\n", ""); if (sContent.Length > 0) { bUpdatePK = true; } else { return("Private Key contained within:<br />-----BEGIN RSA PRIVATE KEY-----<br />and<br />-----END RSA PRIVATE KEY-----<br />cannot be blank."); } } else { return("Private Key must be contained within:<br />-----BEGIN RSA PRIVATE KEY-----<br />and<br />-----END RSA PRIVATE KEY-----"); } } bool bUpdatePP = false; if (sPP != "!2E4S6789O") { bUpdatePP = true; } //all good, keep going dataAccess dc = new dataAccess(); string sSQL = null; string sErr = null; try { if (string.IsNullOrEmpty(sKeypairID)) { //empty id, it's a new one. string sPKClause = ""; if (bUpdatePK) { sPKClause = "'" + dc.EnCrypt(sPK) + "'"; } string sPPClause = "null"; if (bUpdatePP) { sPPClause = "'" + dc.EnCrypt(sPP) + "'"; } sSQL = "insert into cloud_account_keypair (keypair_id, account_id, keypair_name, private_key, passphrase)" + " values ('" + ui.NewGUID() + "'," + "'" + sAccountID + "'," + "'" + sName.Replace("'", "''") + "'," + sPKClause + "," + sPPClause + ")"; } else { string sPKClause = ""; if (bUpdatePK) { sPKClause = ", private_key = '" + dc.EnCrypt(sPK) + "'"; } string sPPClause = ""; if (bUpdatePP) { sPPClause = ", passphrase = '" + dc.EnCrypt(sPP) + "'"; } sSQL = "update cloud_account_keypair set" + " keypair_name = '" + sName.Replace("'", "''") + "'" + sPKClause + sPPClause + " where keypair_id = '" + sKeypairID + "'"; } if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { throw new Exception(sErr); } } catch (Exception ex) { throw new Exception(ex.Message); } //// add security log //// since this is not handled as a page postback, theres no "Viewstate" settings //// so 2 options either we keep an original setting for each value in hid values, or just get them from the db as part of the //// update above, since we are already passing in 15 or so fields, lets just get the values at the start and reference them here //if (sMode == "edit") //{ // ui.WriteObjectChangeLog(Globals.acObjectTypes.CloudAccount, sAccountID, sAccountName, sOriginalName, sAccountName); //} //else //{ // ui.WriteObjectAddLog(Globals.acObjectTypes.CloudAccount, sAccountID, sAccountName, "Account Created"); //} // no errors to here, so return an empty string return(""); }
public static string SaveKeyPair(string sKeypairID, string sAccountID, string sName, string sPK, string sPP) { acUI.acUI ui = new acUI.acUI(); if (string.IsNullOrEmpty(sName)) return "KeyPair Name is Required."; //we encoded this in javascript before the ajax call. //the safest way to unencode it is to use the same javascript lib. //(sometimes the javascript and .net libs don't translate exactly, google it.) sPK = ui.unpackJSON(sPK); bool bUpdatePK = false; if (sPK != "-----BEGIN RSA PRIVATE KEY-----\n**********\n-----END RSA PRIVATE KEY-----") { //we want to make sure it's not just the placeholder, but DOES have the wrapper. //and 61 is the lenght of the wrapper with no content... effectively empty if (sPK.StartsWith("-----BEGIN RSA PRIVATE KEY-----\n") && sPK.EndsWith("\n-----END RSA PRIVATE KEY-----")) { //now, is there truly something in it? string sContent = sPK.Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "").Replace("\n", ""); if (sContent.Length > 0) bUpdatePK = true; else return "Private Key contained within:<br />-----BEGIN RSA PRIVATE KEY-----<br />and<br />-----END RSA PRIVATE KEY-----<br />cannot be blank."; } else { return "Private Key must be contained within:<br />-----BEGIN RSA PRIVATE KEY-----<br />and<br />-----END RSA PRIVATE KEY-----"; } } bool bUpdatePP = false; if (sPP != "!2E4S6789O") bUpdatePP = true; //all good, keep going dataAccess dc = new dataAccess(); string sSQL = null; string sErr = null; try { if (string.IsNullOrEmpty(sKeypairID)) { //empty id, it's a new one. string sPKClause = ""; if (bUpdatePK) sPKClause = "'" + dc.EnCrypt(sPK) + "'"; string sPPClause = "null"; if (bUpdatePP) sPPClause = "'" + dc.EnCrypt(sPP) + "'"; sSQL = "insert into cloud_account_keypair (keypair_id, account_id, keypair_name, private_key, passphrase)" + " values ('" + ui.NewGUID() + "'," + "'" + sAccountID + "'," + "'" + sName.Replace("'", "''") + "'," + sPKClause + "," + sPPClause + ")"; } else { string sPKClause = ""; if (bUpdatePK) sPKClause = ", private_key = '" + dc.EnCrypt(sPK) + "'"; string sPPClause = ""; if (bUpdatePP) sPPClause = ", passphrase = '" + dc.EnCrypt(sPP) + "'"; sSQL = "update cloud_account_keypair set" + " keypair_name = '" + sName.Replace("'", "''") + "'" + sPKClause + sPPClause + " where keypair_id = '" + sKeypairID + "'"; } if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) throw new Exception(sErr); } catch (Exception ex) { throw new Exception(ex.Message); } //// add security log //// since this is not handled as a page postback, theres no "Viewstate" settings //// so 2 options either we keep an original setting for each value in hid values, or just get them from the db as part of the //// update above, since we are already passing in 15 or so fields, lets just get the values at the start and reference them here //if (sMode == "edit") //{ // ui.WriteObjectChangeLog(Globals.acObjectTypes.CloudAccount, sAccountID, sAccountName, sOriginalName, sAccountName); //} //else //{ // ui.WriteObjectAddLog(Globals.acObjectTypes.CloudAccount, sAccountID, sAccountName, "Account Created"); //} // no errors to here, so return an empty string return ""; }
public static string SaveNewUser(object[] oUser) { dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); acUI.AppGlobals ag = new acUI.AppGlobals(); string sSql = null; string sErr = null; // check the number of properties if (oUser.Length != 10) { return("Incorrect list of user properties"); } string sLoginID = oUser[0].ToString(); string sFullName = oUser[1].ToString(); string sAuthType = oUser[2].ToString(); string sUserPassword = oUser[3].ToString(); string sGeneratePW = oUser[4].ToString(); string sForcePasswordChange = oUser[5].ToString(); string sUserRole = oUser[6].ToString(); string sEmail = oUser[7].ToString(); string sStatus = oUser[8].ToString(); string sGroupArray = oUser[9].ToString(); // checks that cant be done on the client side // is the name unique? string sInuse = ""; if (!dc.sqlGetSingleString(ref sInuse, "select user_id from users where username = '******' limit 1", ref sErr)) { return("sErr"); } else { if (!string.IsNullOrEmpty(sInuse)) { return("Login ID '" + sLoginID + "' is unavailable, please choose another."); } } // password string sPassword = null; if (sAuthType == "local") { if (sGeneratePW == "1") //generate an initial strong password { sUserPassword = dc.GenerateNewPassword(); } sPassword = "******" + dc.EnCrypt(sUserPassword) + "'"; } else if (sAuthType == "ldap") { sPassword = "******"; } else { return("Unknown Authentication Type."); } // passed client and server validations, create the user string sNewUserID = ui.NewGUID(); try { dataAccess.acTransaction oTrans = new dataAccess.acTransaction(ref sErr); // all good, save the new user and redirect to the user edit page. sSql = "insert users" + " (user_id,username,full_name,authentication_type,user_password,force_change,email,status,user_role)" + " values " + "('" + sNewUserID + "'," + "'" + sLoginID.Trim().Replace("'", "''") + "'," + "'" + sFullName.Trim().Replace("'", "''") + "'," + "'" + sAuthType + "'," + sPassword + "," + "'" + sForcePasswordChange + "'," + "'" + sEmail.Trim() + "'," + "'" + sStatus + "'," + "'" + sUserRole + "'" + ")"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } #region "groups" // add user groups, if there are any if (sGroupArray.Length > 0) { ArrayList aGroups = new ArrayList(sGroupArray.Split(',')); foreach (string sGroupName in aGroups) { sSql = "insert object_tags (object_id, object_type, tag_name)" + " values ('" + sNewUserID + "', 1, '" + sGroupName + "')"; oTrans.Command.CommandText = sSql; if (!oTrans.ExecUpdate(ref sErr)) { throw new Exception(sErr); } } } #endregion oTrans.Commit(); } catch (Exception ex) { throw new Exception(ex.Message); } // add security log ui.WriteObjectAddLog(Globals.acObjectTypes.User, sNewUserID, sFullName.Trim().Replace("'", "''"), ""); //email out the password string sBody = ""; if (!dc.sqlGetSingleString(ref sBody, "select new_user_email_message from login_security_settings where id = 1", ref sErr)) { throw new Exception(sErr); } //default message if undefined in the table if (string.IsNullOrEmpty(sBody)) { sBody = sFullName + " - an account has been created for you in " + ag.APP_NAME + "." + Environment.NewLine + Environment.NewLine + "Your User Name: " + sLoginID + "." + Environment.NewLine + "Your temporary password: "******"." + Environment.NewLine; } //replace our special tokens with the values sBody = sBody.Replace("##FULLNAME##", sFullName).Replace("##USERNAME##", sLoginID); if (sGeneratePW == "1") { sBody = sBody.Replace("##PASSWORD##", sUserPassword); } else { sBody = sBody.Replace("##PASSWORD##", "Will be provided by an Administrator."); } if (!ui.SendEmailMessage(sEmail.Trim(), ag.APP_COMPANYNAME + " Account Management", "Welcome to " + ag.APP_COMPANYNAME, sBody, ref sErr)) { throw new Exception(sErr); } // no errors to here, so return an empty string return(""); }