protected void Page_Load(object sender, EventArgs e) { if (Request.HttpMethod != "POST") { return; } String area = ""; if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"])) { area = (String)RouteData.Values["area"]; } String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString(); EnterpriseData ent = (EnterpriseData)Page.Session["enterprise_data"]; LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/"); LMenu menu2 = new LMenu("Empresa", ApplicationVirtualPath + "admin/enterprise/"); LMenu menu3 = new LMenu(ent.Name, ApplicationVirtualPath + "admin/enterprise/"); WebJsonResponse contentRet = null; String html = ""; String eHtml = ""; String error = ""; String filter = ""; HashData hashData = new HashData(this); EnterpriseGetResult selectedEnterprise = null; //No caso específico da empresa (que não possibilita que o usuário selecione outra) //O ID se tornará o filtro if (!String.IsNullOrWhiteSpace((String)RouteData.Values["id"])) { filter = (String)RouteData.Values["id"]; } String errorTemplate = "<span class=\"empty-results\">{0}</span>"; if (area.ToLower() != "search") { try { var tmpReq = new { jsonrpc = "1.0", method = "enterprise.get", parameters = new { enterpriseid = ent.Id }, id = 1 }; String rData = SafeTrend.Json.JSON.Serialize2(tmpReq); String jData = ""; using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData); if (String.IsNullOrWhiteSpace(jData)) { throw new Exception(""); } selectedEnterprise = JSON.Deserialize <EnterpriseGetResult>(jData); if (selectedEnterprise == null) { error = MessageResource.GetMessage("enterprise_not_found"); //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true); } else if (selectedEnterprise.error != null) { error = selectedEnterprise.error.data; selectedEnterprise = null; } else if (selectedEnterprise.result == null || selectedEnterprise.result.info == null) { error = MessageResource.GetMessage("enterprise_not_found"); selectedEnterprise = null; } else { menu3.Name = selectedEnterprise.result.info.name; } } catch (Exception ex) { error = MessageResource.GetMessage("api_error"); Tools.Tool.notifyException(ex, this); selectedEnterprise = null; //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true); } } switch (area) { case "": case "content": if (selectedEnterprise != null) { switch (filter) { case "": case "info": String infoTemplate = "<div class=\"form-group\">"; infoTemplate += "<label>{0}</label>"; infoTemplate += "<span class=\"no-edit\">{1}</span></div>"; String jsAdd = ""; if (filter == "" || filter == "info") { if (hashData.GetValue("edit") == "1") { html += "<form id=\"form_enterprise_change\" method=\"POST\" action=\"" + ApplicationVirtualPath + "admin/enterprise/action/change/\">"; html += "<h3>Informações gerais</h3>"; html += "<div class=\"no-tabs pb10\">"; html += String.Format(infoTemplate, "Nome", "<input id=\"name\" name=\"name\" placeholder=\"Digite o nome da empresa\" type=\"text\"\" value=\"" + selectedEnterprise.result.info.name + "\">"); html += String.Format(infoTemplate, "Host principal", selectedEnterprise.result.info.fqdn); html += String.Format(infoTemplate, "Criado em", MessageResource.FormatDate(((DateTime) new DateTime(1970, 1, 1)).AddSeconds(selectedEnterprise.result.info.create_date), false)); //Resgata a listagem dos plugins de autenticação disponíveis List <AuthBase> plugins = AuthBase.GetPlugins <AuthBase>(); String select = ""; select += "<select id=\"auth_plugin\" name=\"auth_plugin\" >"; foreach (AuthBase p in plugins) { select += "<option selector=\"" + p.GetPluginId().AbsoluteUri.Replace("/", "").Replace(":", "") + "\" value=\"" + p.GetPluginId().AbsoluteUri + "\" " + (p.Equal(new Uri(selectedEnterprise.result.info.auth_plugin)) ? "selected=\"selected\"" : "") + ">" + p.GetPluginName() + "</option>"; } select += "</select>"; html += String.Format(infoTemplate, "Serviço de autenticação", select); //Caso tenha algum paràmetro p/ o plugin exibe foreach (AuthBase p in plugins) { AuthConfigFields[] fields = p.GetConfigFields(); if (fields.Length > 0) { html += "<div class=\"auth_cont " + p.GetPluginId().AbsoluteUri.Replace("/", "").Replace(":", "") + "\" " + (p.Equal(new Uri(selectedEnterprise.result.info.auth_plugin)) ? "" : "style=\"display:none;\"") + ">"; foreach (AuthConfigFields f in fields) { String value = ""; try { foreach (EnterpriseAuthPars par in selectedEnterprise.result.auth_parameters) { if (par.key == f.Key) { value = par.value; } } } catch { } html += String.Format(infoTemplate, f.Name, "<input id=\"f_" + f.Key + "\" name=\"f_" + f.Key + "\" placeholder=\"" + f.Description + "\" type=\"text\"\" value=\"" + value + "\">"); } html += "</div>"; } } html += "<div class=\"clear-block\"></div></div>"; } else { html += "<h3>Informações gerais<div class=\"btn-box\"><div class=\"a-btn ico icon-change\" onclick=\"iamadmin.changeHash( 'edit/1' );\">Editar</div></div></h3>"; html += "<div class=\"no-tabs pb10\">"; html += String.Format(infoTemplate, "Nome", selectedEnterprise.result.info.name); html += String.Format(infoTemplate, "Host principal", selectedEnterprise.result.info.fqdn); html += String.Format(infoTemplate, "Criado em", MessageResource.FormatDate(((DateTime) new DateTime(1970, 1, 1)).AddSeconds(selectedEnterprise.result.info.create_date), false)); try { AuthBase plugin = AuthBase.GetPlugin(new Uri(selectedEnterprise.result.info.auth_plugin)); html += String.Format(infoTemplate, "Serviço de autenticação", plugin.GetPluginName()); AuthConfigFields[] fields = plugin.GetConfigFields(); if (fields.Length > 0) { foreach (AuthConfigFields f in fields) { String value = ""; try { foreach (EnterpriseAuthPars par in selectedEnterprise.result.auth_parameters) { if (par.key == f.Key) { value = par.value; } } } catch { } html += String.Format(infoTemplate, f.Name, value); } } } catch { html += String.Format(infoTemplate, "Serviço de autenticação", "Erro ao carregar informações do plugin"); } html += "<div class=\"clear-block\"></div></div>"; } html += "<h3>Hosts complementares</h3>"; html += "<div class=\"no-tabs pb10\">"; if (hashData.GetValue("edit") == "1") { html += "<div id=\"enterprise_hosts\">"; if (selectedEnterprise.result.fqdn_alias != null) { for (Int32 i = 1; i <= selectedEnterprise.result.fqdn_alias.Count; i++) { html += String.Format(infoTemplate, "Host " + i, "<input id=\"host_" + i + "\" name=\"host_" + i + "\" placeholder=\"Digite o host\" type=\"text\"\" value=\"" + selectedEnterprise.result.fqdn_alias[i - 1] + "\">"); } } html += "</div>"; //Div enterprise_hosts html += String.Format(infoTemplate, "", "<div class=\"a-btn blue secondary floatleft\" onclick=\"iamfnc.addHostField()\">Adicionar host</div>"); jsAdd = "iamfnc = $.extend({}, iamfnc, { addHostField: function() { var host = 'host_'+ new Date().getTime(); $('#enterprise_hosts').append('" + String.Format(infoTemplate, "Host ", "<input id=\"'+ host +'\" name=\"'+ host +'\" placeholder=\"Digite o host\" type=\"text\">") + "'); } });"; jsAdd += "$('#auth_plugin').change(function() { $('.auth_cont').css('display','none'); $('.' + $('#auth_plugin option:selected').attr('selector') ).css('display','block'); });"; } else { if (selectedEnterprise.result.fqdn_alias != null) { for (Int32 i = 1; i <= selectedEnterprise.result.fqdn_alias.Count; i++) { html += String.Format(infoTemplate, "Host " + i, selectedEnterprise.result.fqdn_alias[i - 1]); } } } html += "<div class=\"clear-block\"></div></div>"; if (hashData.GetValue("edit") == "1") { html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button> <a class=\"button link floatleft\" onclick=\"iamadmin.changeHash( 'edit/0' );\">Cancelar</a></form>"; } } contentRet = new WebJsonResponse("#content-wrapper", html); contentRet.js = jsAdd; break; case "flow": String js2 = ""; if (filter == "" || filter == "flow") { html += "<h3>Fluxo de dados</h3>"; html += "<div id=\"enterpriseChart\"></div>"; js2 = "$('#enterpriseChart').flowchart({load_uri: '" + ApplicationVirtualPath + "admin/chartdata/flow/enterprise/'});"; } contentRet = new WebJsonResponse("#content-wrapper", html); contentRet.js = js2; break; } } else { contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error)); } break; case "sidebar": if (menu1 != null) { html += "<div class=\"section-nav-header\">"; html += " <div class=\"crumbs\">"; html += " <div class=\"subject subject-color\">"; html += " <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>"; html += " </div>"; if (menu2 != null) { html += " <div class=\"topic topic-color\">"; html += " <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>"; html += " </div>"; } html += " </div>"; if (menu3 != null) { html += " <div class=\"crumbs tutorial-title\">"; html += " <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>"; html += " </div>"; } html += "</div>"; } if (selectedEnterprise != null) { html += "<ul class=\"user-profile\">"; html += "<li " + (filter == "" ? "class=\"bold\"" : "") + "><span><a href=\"" + ApplicationVirtualPath + "admin/enterprise/\">Todas as informações</a></span></li>"; html += "<li " + (filter == "flow" ? "class=\"bold\"" : "") + "><span><a href=\"" + ApplicationVirtualPath + "admin/enterprise/flow\">Fluxo</a></span></li>"; html += "</ul>"; } contentRet = new WebJsonResponse("#main aside", html); break; case "mobilebar": break; case "buttonbox": break; } if (contentRet != null) { if (!String.IsNullOrWhiteSpace((String)Request["cid"])) { contentRet.callId = (String)Request["cid"]; } Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON())); } }
/// <summary> /// Método privado para processamento do método 'user.resetpassword' /// </summary> /// <param name="sqlConnection">Conexão com o banco de dados MS-SQL</param> /// <param name="parameters">Dicionário (String, Object) contendo todos os parâmetros necessários</param> private Dictionary <String, Object> change(IAMDatabase database, Dictionary <String, Object> parameters) { Dictionary <String, Object> result = new Dictionary <String, Object>(); if (!parameters.ContainsKey("enterpriseid")) { Error(ErrorType.InvalidRequest, "Parameter enterpriseid is not defined.", "", null); return(null); } String enterprise = parameters["enterpriseid"].ToString(); if (String.IsNullOrWhiteSpace(enterprise)) { Error(ErrorType.InvalidRequest, "Parameter enterpriseid is not defined.", "", null); return(null); } Int64 enterpriseid = 0; try { enterpriseid = Int64.Parse(enterprise); } catch { Error(ErrorType.InvalidRequest, "Parameter enterpriseid is not a long integer.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseid; DataTable dtEnterprise = database.ExecuteDataTable("select * from enterprise where id = @enterprise_id", CommandType.Text, par, null); if (dtEnterprise == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtEnterprise.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Enterprise not found.", "", null); return(null); } List <String> hosts = new List <String>(); Dictionary <String, String> pgValues = new Dictionary <string, string>(); Uri pluginUri = null; String updateSQL = "update enterprise set "; String updateFields = ""; Boolean update = false; Boolean updateHosts = false; Boolean updateAuthPars = false; foreach (String key in parameters.Keys) { switch (key.ToLower()) { case "name": String name = parameters["name"].ToString(); if (!String.IsNullOrWhiteSpace(name)) { par.Add("@name", typeof(String)).Value = name; if (updateFields != "") { updateFields += ", "; } updateFields += "name = @name"; update = true; } else { Error(ErrorType.InvalidRequest, "Parameter name is empty.", "", null); return(null); } break; case "auth_plugin": String auth_plugin = parameters["auth_plugin"].ToString(); if (!String.IsNullOrWhiteSpace(auth_plugin)) { try { Uri tmp = new Uri(auth_plugin); if (tmp.Scheme.ToLower() != "auth") { throw new Exception(); } } catch { Error(ErrorType.InvalidRequest, "Parameter auth_plugin is not a valid uri.", "", null); return(null); } try { AuthBase plugin = AuthBase.GetPlugin(new Uri(auth_plugin)); if (plugin == null) { throw new Exception(); } } catch { Error(ErrorType.InvalidRequest, MessageResource.GetMessage("invalid_auth_service"), "", null); break; } par.Add("@auth_plugin", typeof(String)).Value = auth_plugin; if (updateFields != "") { updateFields += ", "; } updateFields += "auth_plugin = @auth_plugin"; update = true; } else { Error(ErrorType.InvalidRequest, "Parameter auth_plugin is empty.", "", null); return(null); } break; case "fqdn_alias": if (parameters[key] is ArrayList) { updateHosts = true; List <Object> ht = new List <Object>(); ht.AddRange(((ArrayList)parameters[key]).ToArray()); foreach (String host in ht) { if (!String.IsNullOrWhiteSpace(host)) { try { Uri tmp = new Uri("http://" + host); hosts.Add(host); } catch { Error(ErrorType.InvalidRequest, "Parameter fqdn_alias->" + host + " is not a valid hostname.", "", null); return(null); } } } } break; case "auth_paramters": if (parameters[key] is Dictionary <String, Object> ) { if (!parameters.ContainsKey("auth_plugin")) { Error(ErrorType.InvalidRequest, "Parameter auth_plugin is not defined.", "", null); return(null); } if (String.IsNullOrWhiteSpace(parameters["auth_plugin"].ToString())) { Error(ErrorType.InvalidRequest, "Parameter auth_plugin is not defined.", "", null); return(null); } try { Uri tmp = new Uri(parameters["auth_plugin"].ToString()); if (tmp.Scheme.ToLower() != "auth") { throw new Exception(); } } catch { Error(ErrorType.InvalidRequest, "Parameter auth_plugin is not a valid uri.", "", null); return(null); } AuthBase plugin = null; try { plugin = AuthBase.GetPlugin(new Uri(parameters["auth_plugin"].ToString())); if (plugin == null) { throw new Exception(); } } catch { Error(ErrorType.InvalidRequest, MessageResource.GetMessage("invalid_auth_service"), "", null); break; } pluginUri = plugin.GetPluginId(); updateAuthPars = true; Dictionary <String, Object> p1 = (Dictionary <String, Object>)parameters[key]; AuthConfigFields[] fields = plugin.GetConfigFields(); foreach (AuthConfigFields f in fields) { String value = ""; if (p1.ContainsKey(f.Key)) { value = p1[f.Key].ToString(); } if (!String.IsNullOrEmpty(value)) { pgValues.Add(f.Key, value); } if (f.Required && !pgValues.ContainsKey(f.Key)) { Error(ErrorType.InvalidRequest, MessageResource.GetMessage("required_field") + " " + f.Name, "", null); break; } } } break; } } if (update) { updateSQL += updateFields + " where id = @enterprise_id"; database.ExecuteNonQuery(updateSQL, CommandType.Text, par); } if (updateHosts) { foreach (String host in hosts) { if (!String.IsNullOrWhiteSpace(host)) { DbParameterCollection par1 = new DbParameterCollection(); par1.Add("@enterprise_id", typeof(Int64)).Value = enterpriseid; par1.Add("@fqdn", typeof(String)).Value = host; database.ExecuteNonQuery("insert into enterprise_fqdn_alias (enterprise_id, fqdn) select @enterprise_id, @fqdn where not exists (select 1 from enterprise_fqdn_alias where enterprise_id = @enterprise_id and fqdn = @fqdn) ", CommandType.Text, par1); } } database.ExecuteNonQuery("delete from enterprise_fqdn_alias where enterprise_id = @enterprise_id " + (hosts.Count > 0 ? " and fqdn not in ('" + String.Join("', '", hosts) + "')" : ""), CommandType.Text, par); } if (updateAuthPars) { database.ExecuteNonQuery("delete from enterprise_auth_par where enterprise_id = @enterprise_id and plugin = '" + pluginUri.AbsoluteUri + "'", CommandType.Text, par); foreach (String key in pgValues.Keys) { if (!String.IsNullOrWhiteSpace(pgValues[key])) { DbParameterCollection par1 = new DbParameterCollection(); par1.Add("@enterprise_id", typeof(Int64)).Value = enterpriseid; par1.Add("@plugin", typeof(String)).Value = pluginUri.AbsoluteUri; par1.Add("@key", typeof(String)).Value = key; par1.Add("@value", typeof(String)).Value = pgValues[key]; database.ExecuteNonQuery("insert into enterprise_auth_par (enterprise_id, plugin,[key],[value]) VALUES(@enterprise_id, @plugin, @key, @value)", CommandType.Text, par1); } } } //Atualiza a busca com os dados atualizados return(get(database, parameters)); }
protected void Page_Load(object sender, EventArgs e) { WebJsonResponse contentRet = null; EnterpriseData ent = (EnterpriseData)Page.Session["enterprise_data"]; String action = ""; if (!String.IsNullOrWhiteSpace((String)RouteData.Values["action"])) { action = (String)RouteData.Values["action"]; } String rData = ""; ////SqlConnection //conn = DB.GetConnection(); String jData = ""; try { switch (action) { case "change": String name = Request.Form["name"]; if (String.IsNullOrEmpty(name)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("invalid_name"), 3000, true); break; } String auth_plugin = Request.Form["auth_plugin"]; if (String.IsNullOrEmpty(auth_plugin)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("select_auth_service"), 3000, true); break; } AuthBase plugin = null; try { plugin = AuthBase.GetPlugin(new Uri(auth_plugin)); if (plugin == null) { throw new Exception(); } } catch { contentRet = new WebJsonResponse("", MessageResource.GetMessage("invalid_auth_service"), 3000, true); break; } Dictionary <String, String> pgValues = new Dictionary <string, string>(); AuthConfigFields[] fields = plugin.GetConfigFields(); if (fields.Length > 0) { WebJsonResponse err = null; foreach (AuthConfigFields f in fields) { String value = Request.Form["f_" + f.Key]; if (!String.IsNullOrEmpty(value)) { pgValues.Add(f.Key, value); } if (f.Required && !pgValues.ContainsKey(f.Key)) { err = new WebJsonResponse("", MessageResource.GetMessage("required_field") + " " + f.Name, 3000, true); break; } } if (err != null) { contentRet = err; break; } } List <String> hosts = new List <String>(); foreach (String key in Request.Form.Keys) { if (key.ToLower().IndexOf("host_") == 0) { String[] ht = Request.Form[key].ToString().Split(",".ToCharArray()); foreach (String host in ht) { if (!String.IsNullOrWhiteSpace(host)) { hosts.Add(host); } } } } var reqD = new { jsonrpc = "1.0", method = "enterprise.change", parameters = new { enterpriseid = ent.Id, name = name, auth_plugin = auth_plugin, fqdn_alias = hosts.ToArray(), auth_paramters = pgValues }, id = 1 }; rData = JSON.Serialize2(reqD); using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData); if (String.IsNullOrWhiteSpace(jData)) { throw new Exception(""); } RoleGetResult retD = JSON.Deserialize <RoleGetResult>(jData); if (retD == null) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("enterprise_not_found"), 3000, true); } else if (retD.error != null) { contentRet = new WebJsonResponse("", retD.error.data, 3000, true); } else if (retD.result == null) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("enterprise_not_found"), 3000, true); } else if (retD.result == null || retD.result.info == null) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("enterprise_not_found"), 3000, true); } else { contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/enterprise/"); } break; } } catch (Exception ex) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true); } finally { } if (contentRet != null) { if (!String.IsNullOrWhiteSpace((String)Request["cid"])) { contentRet.callId = (String)Request["cid"]; } Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON())); } }