/// <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> newrole(IAMDatabase database, Dictionary <String, Object> parameters) { Dictionary <String, Object> result = new Dictionary <String, Object>(); if (!parameters.ContainsKey("name")) { Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null); return(null); } String name = parameters["name"].ToString(); if (String.IsNullOrWhiteSpace(name)) { Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null); return(null); } Int64 parentid = 0; if (parameters.ContainsKey("parentid")) { try { parentid = Int64.Parse(parameters["parentid"].ToString()); } catch { Error(ErrorType.InvalidRequest, "Parameter parentid is not a long integer.", "", null); return(null); } } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@name", typeof(String)).Value = name; par.Add("@parent_id", typeof(Int64)).Value = parentid; par.Add("@system_admin", typeof(Boolean)).Value = false; par.Add("@enterprise_admin", typeof(Int64)).Value = (parameters.ContainsKey("enterprise_admin") && (parameters["enterprise_admin"] is Boolean) && (Boolean)parameters["enterprise_admin"]); DataTable dtUsers = database.ExecuteDataTable("sp_new_sys_role", CommandType.StoredProcedure, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "System role not found.", "", null); return(null); } parameters.Add("roleid", dtUsers.Rows[0]["id"]); return(get(database, parameters)); }
protected Dictionary <String, Object> GetAuthConfig(IAMDatabase database, System.Web.UI.Page page) { Dictionary <String, Object> config = new Dictionary <string, object>(); Int64 enterpriseId = 0; if ((page.Session["enterprise_data"]) != null && (page.Session["enterprise_data"] is EnterpriseData)) { enterpriseId = ((EnterpriseData)page.Session["enterprise_data"]).Id; } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@plugin", typeof(String)).Value = this.GetPluginId().AbsoluteUri; DataTable conf = database.ExecuteDataTable("select distinct [key], [value] from dbo.enterprise_auth_par where enterprise_id = @enterprise_id and plugin = @plugin", CommandType.Text, par); if ((conf != null) && (conf.Rows.Count > 0)) { foreach (DataRow dr in conf.Rows) { FillConfig(this, ref config, dr["key"].ToString(), dr["value"].ToString()); } } return(config); }
/// <summary> /// Método privado para processamento do método 'logs.list' /// </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 Object get(IAMDatabase database, Dictionary <String, Object> parameters) { if (!parameters.ContainsKey("logid")) { Error(ErrorType.InvalidRequest, "Parameter logid is not defined.", "", null); return(null); } String logid = parameters["logid"].ToString(); if (String.IsNullOrWhiteSpace(logid)) { Error(ErrorType.InvalidRequest, "Parameter logid is not defined.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@id", typeof(String)).Value = logid; String sql = ""; sql += "SELECT l.*, res.name resource_name, p.name plugin_name, e.full_name executed_by_name"; sql += " from logs l with(nolock) "; sql += " left join [identity] i with(nolock) on i.id = l.identity_id"; sql += " left join resource res with(nolock) on res.id = l.resource_id"; sql += " left join plugin p with(nolock) on p.id = l.plugin_id"; sql += " left join entity e with(nolock) on e.id = l.executed_by_entity_id"; sql += " WHERE"; sql += " l.id = @id"; DataTable dtLogs = database.ExecuteDataTable(sql, CommandType.Text, par, null); if ((dtLogs != null) && (dtLogs.Rows.Count > 0)) { DataRow dr1 = dtLogs.Rows[0]; Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("log_id", dr1["id"]); newItem.Add("date", (Int32)((((DateTime)dr1["date"]) - new DateTime(1970, 1, 1)).TotalSeconds)); newItem.Add("source", dr1["source"]); newItem.Add("level", dr1["level"]); newItem.Add("identity_id", dr1["identity_id"]); newItem.Add("resource_name", dr1["resource_name"]); newItem.Add("plugin_name", dr1["plugin_name"]); newItem.Add("text", dr1["text"]); newItem.Add("additional_data", dr1["additional_data"]); newItem.Add("executed_by_entity_id", (Int64)dr1["executed_by_entity_id"]); newItem.Add("executed_by_name", (dr1["executed_by_name"] == DBNull.Value ? "System" : dr1["executed_by_name"].ToString())); return(newItem); } return(null); }
/// <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 Boolean restart(IAMDatabase database, Dictionary <String, Object> parameters) { if (!parameters.ContainsKey("proxyid")) { Error(ErrorType.InvalidRequest, "Parameter proxyid is not defined.", "", null); return(false); } String proxy = parameters["proxyid"].ToString(); if (String.IsNullOrWhiteSpace(proxy)) { Error(ErrorType.InvalidRequest, "Parameter proxyid is not defined.", "", null); return(false); } Int64 proxyid = 0; try { proxyid = Int64.Parse(proxy); } catch { Error(ErrorType.InvalidRequest, "Parameter proxyid is not a long integer.", "", null); return(false); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@proxy_id", typeof(Int64)).Value = proxyid; DataTable dtProxy = database.ExecuteDataTable("select * from proxy p where (p.enterprise_id = @enterprise_id or p.enterprise_id = 0) and p.id = @proxy_id", CommandType.Text, par, null); if (dtProxy == null) { Error(ErrorType.InternalError, "", "", null); return(false); } if (dtProxy.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Proxy not found.", "", null); return(false); } database.ExecuteNonQuery("update proxy set restart = 1 where id = @proxy_id", CommandType.Text, par); database.AddUserLog(LogKey.Proxy_ResetRequest, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Proxy " + dtProxy.Rows[0]["name"] + " reset requested", ""); return(true); }
public static String getPath(IAMDatabase database, Int64 enterprise_id, Int64 container_id, Boolean show_atual) { List <String> path = new List <string>(); DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = enterprise_id; DataTable dtContainers = database.ExecuteDataTable("select c.*, c1.enterprise_id, c1.name context_name, entity_qty = (select COUNT(distinct e.id) from entity e with(nolock) inner join entity_container ec with(nolock) on e.id = ec.entity_id where ec.container_id = c.id) from container c with(nolock) inner join context c1 with(nolock) on c1.id = c.context_id where c1.enterprise_id = @enterprise_id order by c.name", CommandType.Text, par, null); if ((dtContainers != null) && (dtContainers.Rows.Count > 0)) { Func <Int64, Boolean> chields = null; chields = new Func <Int64, Boolean>(delegate(Int64 root) { foreach (DataRow dr in dtContainers.Rows) { if (((Int64)dr["id"] == root)) { if ((Int64)dr["parent_id"] == root) { break; } path.Add(dr["name"].ToString()); chields((Int64)dr["parent_id"]); break; } } return(true); }); foreach (DataRow dr in dtContainers.Rows) { if (((Int64)dr["id"] == container_id)) { if (show_atual) { path.Add(dr["name"].ToString()); } chields((Int64)dr["parent_id"]); } } } path.Reverse(); return("\\" + String.Join("\\", path)); }
public static EnterpriseData EnterpriseByService(Page page, String service) { if (String.IsNullOrEmpty(service)) { return(null); } DbParameterCollection par = null; try { par = new DbParameterCollection();; par.Add("@svc", typeof(String), service.Length).Value = service.TrimEnd("/".ToCharArray()).Replace("https://", "//").Replace("http://", "//").Trim(); using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { DataTable dt = db.ExecuteDataTable("select * from [cas_service] s inner join enterprise e on s.enterprise_id = e.id where s.service_uri = @svc", CommandType.Text, par); if ((dt != null) && (dt.Rows.Count > 0)) { EnterpriseData data = new EnterpriseData(); data.Host = page.Request.Url.Host.ToLower(); data.Host = dt.Rows[0]["fqdn"].ToString().ToLower(); data.Name = dt.Rows[0]["name"].ToString(); data.Language = dt.Rows[0]["language"].ToString(); data.Id = (Int64)dt.Rows[0]["id"]; return(data); } else { return(null); } } } catch (Exception ex) { return(null); } finally { par = null; } }
public static Boolean ServiceExists(String service) { if (String.IsNullOrEmpty(service)) { return(false); } DbParameterCollection par = null; try { par = new DbParameterCollection();; par.Add("@svc", typeof(String), service.Length).Value = service.TrimEnd("/".ToCharArray()).Replace("https://", "//").Replace("http://", "//").Trim(); DataTable dt = null; using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString())) dt = db.ExecuteDataTable("select * from [cas_service] where service_uri = @svc", CommandType.Text, par); if ((dt != null) && (dt.Rows.Count > 0)) { return(true); } else { return(false); } } catch (Exception ex) { return(false); } finally { par = null; } }
/// <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 Boolean deleteuser(IAMDatabase database, Dictionary <String, Object> parameters) { if (!parameters.ContainsKey("roleid")) { Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null); return(false); } String role = parameters["roleid"].ToString(); if (String.IsNullOrWhiteSpace(role)) { Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null); return(false); } Int64 roleid = 0; try { roleid = Int64.Parse(role); } catch { Error(ErrorType.InvalidRequest, "Parameter roleid is not a long integer.", "", null); return(false); } String user = parameters["userid"].ToString(); if (String.IsNullOrWhiteSpace(user)) { Error(ErrorType.InvalidRequest, "Parameter userid is not defined.", "", null); return(false); } Int64 userid = 0; try { userid = Int64.Parse(user); } catch { Error(ErrorType.InvalidRequest, "Parameter userid is not a long integer.", "", null); return(false); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@role_id", typeof(Int64)).Value = roleid; par.Add("@entity_id", typeof(Int64)).Value = userid; DataTable dtUsers = database.ExecuteDataTable("select c.enterprise_id, r.name as role_name, ir.*, i.entity_id from role r inner join context c with(nolock) on c.id = r.context_id left join identity_role ir on r.id = ir.role_id left join [identity] i with(nolock) on ir.identity_id = i.id and i.entity_id = @entity_id where c.enterprise_id = @enterprise_id and r.id = @role_id", CommandType.Text, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(false); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Role not found.", "", null); return(false); } foreach (DataRow dr in dtUsers.Rows) { if ((dr["identity_id"] != DBNull.Value) && (dr["entity_id"] != DBNull.Value)) { database.AddUserLog(LogKey.User_IdentityRoleUnbind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, (Int64)dr["entity_id"], (Int64)dr["identity_id"], "Identity unbind to role " + dr["role_name"], ""); database.ExecuteNonQuery("delete from identity_role where role_id = @role_id and identity_id = " + dr["identity_id"], CommandType.Text, par); database.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + dr["entity_id"] + ")", CommandType.Text, null, null); } } return(true); }
/// <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> get(IAMDatabase database, Dictionary <String, Object> parameters) { Dictionary <String, Object> result = new Dictionary <String, Object>(); if (!parameters.ContainsKey("roleid")) { Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null); return(null); } String role = parameters["roleid"].ToString(); if (String.IsNullOrWhiteSpace(role)) { Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null); return(null); } Int64 roleid = 0; try { roleid = Int64.Parse(role); } catch { Error(ErrorType.InvalidRequest, "Parameter roleid is not a long integer.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@role_id", typeof(Int64)).Value = roleid; DataTable dtUsers = database.ExecuteDataTable("select r.*, c.enterprise_id, entity_qty = (select COUNT(distinct i.entity_id) from identity_role ir inner join [identity] i with(nolock) on ir.identity_id = i.id where ir.role_id = r.id) from role r inner join context c with(nolock) on c.id = r.context_id where c.enterprise_id = @enterprise_id and r.id = @role_id order by r.name", CommandType.Text, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Role not found.", "", null); return(null); } DataRow dr1 = dtUsers.Rows[0]; Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("role_id", dr1["id"]); newItem.Add("parent_id", dr1["parent_id"]); newItem.Add("context_id", dr1["context_id"]); newItem.Add("name", dr1["name"]); newItem.Add("entity_qty", dr1["entity_qty"]); newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0)); result.Add("info", newItem); return(result); }
/// <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> newrole(IAMDatabase database, Dictionary <String, Object> parameters) { Dictionary <String, Object> result = new Dictionary <String, Object>(); if (!parameters.ContainsKey("name")) { Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null); return(null); } String name = parameters["name"].ToString(); if (String.IsNullOrWhiteSpace(name)) { Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null); return(null); } if (!parameters.ContainsKey("contextid")) { Error(ErrorType.InvalidRequest, "Parameter contextid is not defined.", "", null); return(null); } Int64 contextid = 0; try { contextid = Int64.Parse((String)parameters["contextid"]); } catch { Error(ErrorType.InvalidRequest, "Parameter contextid is not a long integer.", "", null); return(null); } Int64 parentid = 0; if (parameters.ContainsKey("parentid")) { try { parentid = Int64.Parse(parameters["parentid"].ToString()); } catch { Error(ErrorType.InvalidRequest, "Parameter parentid is not a long integer.", "", null); return(null); } } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@role_name", typeof(String)).Value = name; par.Add("@parent_id", typeof(Int64)).Value = parentid; par.Add("@context_id", typeof(Int64)).Value = contextid; DataTable dtUsers = database.ExecuteDataTable("sp_new_role", CommandType.StoredProcedure, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Role not found.", "", null); return(null); } DataRow dr1 = dtUsers.Rows[0]; Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("role_id", dr1["id"]); newItem.Add("parent_id", dr1["parent_id"]); newItem.Add("context_id", dr1["context_id"]); newItem.Add("name", dr1["name"]); newItem.Add("entity_qty", dr1["entity_qty"]); newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0)); result.Add("info", newItem); return(result); }
/// <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 Boolean deleteallusers(IAMDatabase database, Dictionary <String, Object> parameters) { if (!parameters.ContainsKey("containerid")) { Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null); return(false); } String role = parameters["containerid"].ToString(); if (String.IsNullOrWhiteSpace(role)) { Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null); return(false); } Int64 containerid = 0; try { containerid = Int64.Parse(role); } catch { Error(ErrorType.InvalidRequest, "Parameter containerid is not a long integer.", "", null); return(false); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@container_id", typeof(Int64)).Value = containerid; DataTable dtUsers = database.ExecuteDataTable("select c.*, e.entity_id from entity_container e inner join container c on c.id = e.container_id inner join context c1 on c.context_id = c1.id where c1.enterprise_id = @enterprise_id and e.container_id = @container_id", CommandType.Text, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(false); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Container not found.", "", null); return(false); } database.ExecuteNonQuery("delete from entity_container where container_id = @container_id", CommandType.Text, par); foreach (DataRow dr in dtUsers.Rows) { if (dr["entity_id"] != DBNull.Value) { database.AddUserLog(LogKey.User_ContainerRoleUnbind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, (Int64)dr["entity_id"], 0, "Identity unbind to container " + dr["name"], ""); database.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + dr["entity_id"] + ")", CommandType.Text, null, null); } } return(true); }
/// <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("fieldid")) { Error(ErrorType.InvalidRequest, "Parameter fieldid is not defined.", "", null); return(null); } String field = parameters["fieldid"].ToString(); if (String.IsNullOrWhiteSpace(field)) { Error(ErrorType.InvalidRequest, "Parameter fieldid is not defined.", "", null); return(null); } Int64 fieldid = 0; try { fieldid = Int64.Parse(field); } catch { Error(ErrorType.InvalidRequest, "Parameter fieldid is not a long integer.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@field_id", typeof(Int64)).Value = fieldid; DataTable dtField = database.ExecuteDataTable("select * from field with(nolock) where enterprise_id = @enterprise_id and id = @field_id", CommandType.Text, par, null); if (dtField == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtField.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Field not found.", "", null); return(null); } List <String> log = new List <String>(); String updateSQL = ""; Boolean update = false; foreach (String key in parameters.Keys) { switch (key) { case "name": String name = parameters["name"].ToString(); if ((!String.IsNullOrWhiteSpace(name)) && (name != (String)dtField.Rows[0]["name"])) { DbParameterCollection par2 = new DbParameterCollection(); par2.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par2.Add("@field_name", typeof(String)).Value = name; DataTable dtF1 = database.ExecuteDataTable("select * from field with(nolock) where enterprise_id = @enterprise_id and name = @field_name", CommandType.Text, par2, null); if ((dtF1 != null) && (dtF1.Rows.Count > 0)) { Error(ErrorType.InvalidRequest, "Field with the same name already exists.", "", null); return(null); } par.Add("@name", typeof(String)).Value = name; if (updateSQL != "") { updateSQL += ", "; } updateSQL += " name = @name"; update = true; log.Add("Name changed from '" + dtField.Rows[0]["name"] + "' to '" + name + "'"); } break; case "data_type": String data_type = parameters["data_type"].ToString(); if ((!String.IsNullOrWhiteSpace(data_type)) && (data_type != (String)dtField.Rows[0]["data_type"])) { switch (data_type.ToLower()) { case "string": case "datetime": case "numeric": break; default: Error(ErrorType.InvalidRequest, "Data type is not recognized.", "", null); return(null); break; } par.Add("@data_type", typeof(String)).Value = data_type; if (updateSQL != "") { updateSQL += ", "; } updateSQL += " data_type = @data_type"; update = true; log.Add("Data type changed from '" + dtField.Rows[0]["data_type"] + "' to '" + data_type + "'"); } break; case "public_field": Boolean public_field = true; try { public_field = Boolean.Parse(parameters["public_field"].ToString()); } catch (Exception ex) { Error(ErrorType.InvalidRequest, "Parameter public_field is not a boolean.", "", null); return(null); } if (public_field != (Boolean)dtField.Rows[0]["public"]) { par.Add("@public_field", typeof(Boolean)).Value = public_field; if (updateSQL != "") { updateSQL += ", "; } updateSQL += " [public] = @public_field"; update = true; log.Add("Changed to a " + (public_field ? "" : "non ") + "field"); } break; case "user_field": Boolean user_field = true; try { user_field = Boolean.Parse(parameters["user_field"].ToString()); } catch (Exception ex) { Error(ErrorType.InvalidRequest, "Parameter user_field is not a boolean.", "", null); return(null); } if (user_field != (Boolean)dtField.Rows[0]["user"]) { par.Add("@user_field", typeof(Boolean)).Value = user_field; if (updateSQL != "") { updateSQL += ", "; } updateSQL += " [user] = @user_field"; update = true; log.Add("Changed to " + (user_field ? "an" : "a non ") + "user editable field"); } break; } } if (update) { updateSQL = "update field set " + updateSQL + " where id = @field_id"; database.ExecuteNonQuery(updateSQL, CommandType.Text, par); database.AddUserLog(LogKey.Field_Changed, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Field changed", String.Join("\r\n", log)); } //Atualiza a busca com os dados atualizados dtField = database.ExecuteDataTable("select * from field with(nolock) where enterprise_id = @enterprise_id and id = @field_id", CommandType.Text, par, null); DataRow dr1 = dtField.Rows[0]; Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("field_id", dr1["id"]); newItem.Add("data_type", dr1["data_type"]); newItem.Add("name", dr1["name"]); newItem.Add("public_field", dr1["public"]); newItem.Add("user_field", dr1["user"]); result.Add("info", newItem); return(result); }
/// <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> get(IAMDatabase database, Dictionary <String, Object> parameters) { Dictionary <String, Object> result = new Dictionary <String, Object>(); if (!parameters.ContainsKey("fieldid")) { Error(ErrorType.InvalidRequest, "Parameter fieldid is not defined.", "", null); return(null); } String field = parameters["fieldid"].ToString(); if (String.IsNullOrWhiteSpace(field)) { Error(ErrorType.InvalidRequest, "Parameter fieldid is not defined.", "", null); return(null); } Int64 fieldid = 0; try { fieldid = Int64.Parse(field); } catch { Error(ErrorType.InvalidRequest, "Parameter fieldid is not a long integer.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@field_id", typeof(Int64)).Value = fieldid; DataTable dtResource = database.ExecuteDataTable("select * from field with(nolock) where enterprise_id = @enterprise_id and id = @field_id", CommandType.Text, par, null); if (dtResource == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtResource.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Field not found.", "", null); return(null); } DataRow dr1 = dtResource.Rows[0]; Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("field_id", dr1["id"]); newItem.Add("data_type", dr1["data_type"]); newItem.Add("name", dr1["name"]); newItem.Add("public_field", dr1["public"]); newItem.Add("user_field", dr1["user"]); result.Add("info", newItem); return(result); }
private void BuildBackup() { StringBuilder bkpLog = new StringBuilder(); IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); bkpLog.AppendLine("Listando tabelas da base de dados..."); DataTable dtS = db.Select("select TABLE_NAME from information_schema.tables where TABLE_TYPE = 'BASE TABLE' order by TABLE_NAME"); if ((dtS == null) || (dtS.Rows.Count == 0)) { bkpLog.AppendLine("Listagem de tabelas vazia ou nula"); throw new Exception("Table list is null or empty"); } bkpLog.AppendLine(dtS.Rows.Count + " tabelas"); FileInfo bkpFile = new FileInfo(Path.Combine(Path.Combine(basePath, "Backup"), "bkp-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm") + ".iambkp")); if (!bkpFile.Directory.Exists) { bkpFile.Directory.Create(); } bkpLog.AppendLine("Criando arquivo de backup: " + bkpFile.FullName); using (SqliteBase exportDB = new SqliteBase(bkpFile)) { foreach (DataRow drSrc in dtS.Rows) { String tableName = drSrc["TABLE_NAME"].ToString(); bkpLog.AppendLine("Exportando tabela: " + tableName); Console.WriteLine(tableName); DataTable dtSchema = db.GetSchema(tableName); StringBuilder createCmd = new StringBuilder(); createCmd.AppendLine("DROP TABLE IF EXISTS [" + tableName.ToLower() + "];"); /* * CREATE TABLE [Events] ( * id INTEGER PRIMARY KEY AUTOINCREMENT, * test_id TEXT NOT NULL, * date datetime not null DEFAULT (datetime('now','localtime')), * event_text TEXT NULL * );*/ List <String> columns = new List <string>(); bkpLog.AppendLine("Criando estrutura da tabela"); try { foreach (DataColumn dc in dtSchema.Columns) { if (dc.DataType.Equals(typeof(Int32)) || dc.DataType.Equals(typeof(Int64))) { columns.Add("[" + dc.ColumnName + "] INTEGER NULL"); } else if (dc.DataType.Equals(typeof(DateTime))) { columns.Add("[" + dc.ColumnName + "] datetime NULL"); } else { columns.Add("[" + dc.ColumnName + "] TEXT NULL"); } } } catch (Exception ex) { bkpLog.AppendLine("Erro ao listar as colunas da tabela '" + tableName + "': " + ex.Message); TextLog.Log("Backup", "\tErro ao listar as colunas da tabela '" + tableName + "': " + ex.Message); throw ex; } try { createCmd.AppendLine("CREATE TABLE [" + tableName.ToLower() + "] ("); createCmd.AppendLine(String.Join(", " + Environment.NewLine, columns)); createCmd.AppendLine(");"); exportDB.ExecuteNonQuery(createCmd.ToString()); } catch (Exception ex) { bkpLog.AppendLine("Erro ao criando tabela '" + tableName + "': " + ex.Message); TextLog.Log("Backup", "\tErro ao criando tabela '" + tableName + "': " + ex.Message); throw ex; } //Copiando dados das tabelas try { bkpLog.AppendLine("Copiando dados"); if (tableName.ToLower() == "logs") { DataTable dtSrcData = db.ExecuteDataTable("select l.* from [logs] l with(nolock) inner join [entity_timeline] et with(nolock) on et.log_id = l.id"); exportDB.BulkCopy(dtSrcData, tableName.ToLower()); } else if (tableName.ToLower() == "entity") { DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)"); exportDB.BulkCopy(dtSrcData, tableName.ToLower()); } else { DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)"); exportDB.BulkCopy(dtSrcData, tableName.ToLower()); } } catch (Exception ex) { bkpLog.AppendLine("Erro copiando dados da tabela '" + tableName + "': " + ex.Message); TextLog.Log("Backup", "\tErro copiando dados da tabela '" + tableName + "': " + ex.Message); //throw ex; } } //No final de todo o processo atualiza as senhas como cleartext try { bkpLog.AppendLine("Atualizando as senhas das entidades"); DataTable dtEnt = db.ExecuteDataTable("select id from [enterprise] with(nolock)"); foreach (DataRow drEnt in dtEnt.Rows) { using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, (Int64)drEnt["id"])) { DataTable dtSrcData = db.ExecuteDataTable("select e.id, e.password, c.enterprise_id from [entity] e with(nolock) inner join [context] c with(nolock) on e.context_id = c.id where c.enterprise_id = " + drEnt["id"]); //Atualiza senha em clear text de cada usu[ario foreach (DataRow drUser in dtSrcData.Rows) { try { using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(drUser["password"].ToString()))) { exportDB.ExecuteNonQuery("update entity set password = '******' where id = " + drUser["id"]); } } catch (Exception ex) { bkpLog.AppendLine("Erro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message); TextLog.Log("Backup", "\tErro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message); //throw ex; } } } } } catch (Exception ex) { bkpLog.AppendLine("Erro atualizando as senhas para cleartext: " + ex.Message); TextLog.Log("Backup", "\tErro atualizando as senhas para cleartext: " + ex.Message); //throw ex; } } db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Backup realizado com sucesso", bkpLog.ToString()); } catch (Exception ex) { TextLog.Log("Backup", "\tError building backup: " + ex.Message); bkpLog.AppendLine("Error building backup: " + ex.Message); try { db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Backup finalizado com erro", bkpLog.ToString()); } catch { } } finally { if (bkpLog != null) { bkpLog = null; } if (db != null) { db.Dispose(); } } }
/// <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 List <Object> list(IAMDatabase database, Dictionary <String, Object> parameters) { List <Object> result = new List <Object>(); String text = ""; if (parameters.ContainsKey("text")) { text = (String)parameters["text"]; } if (String.IsNullOrWhiteSpace(text)) { text = ""; } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@text", typeof(String)).Value = text; Int32 page = 1; Int32 pageSize = 10; if (parameters.ContainsKey("page")) { Int32.TryParse(parameters["page"].ToString(), out page); } if (parameters.ContainsKey("page_size")) { Int32.TryParse(parameters["page_size"].ToString(), out pageSize); } if (pageSize < 1) { pageSize = 1; } if (page < 1) { page = 1; } Int32 rStart = ((page - 1) * pageSize) + 1; Int32 rEnd = rStart + (pageSize - 1); String sql = ""; sql += "WITH result_set AS ("; sql += " SELECT "; sql += " ROW_NUMBER() OVER (ORDER BY r.name) AS [row_number], r.*, c.enterprise_id, entity_qty = (select COUNT(distinct i.entity_id) from identity_role ir inner join [identity] i with(nolock) on ir.identity_id = i.id where ir.role_id = r.id) "; sql += " from role r inner join context c with(nolock) on c.id = r.context_id "; sql += " where c.enterprise_id = @enterprise_id " + (String.IsNullOrWhiteSpace(text) ? "" : " and r.name like '%'+@text+'%'"); if ((parameters.ContainsKey("filter")) && (parameters["filter"] is Dictionary <String, Object>)) { Dictionary <String, Object> filter = (Dictionary <String, Object>)parameters["filter"]; foreach (String k in filter.Keys) { switch (k.ToLower()) { case "contextid": try{ sql += " and c.id = " + Int64.Parse(filter[k].ToString()).ToString(); }catch {} break; } } } sql += ") SELECT"; sql += " *"; sql += " FROM"; sql += " result_set"; sql += " WHERE"; sql += " [row_number] BETWEEN " + rStart + " AND " + rEnd; DataTable dtRoles = database.ExecuteDataTable(sql, CommandType.Text, par, null); if ((dtRoles != null) && (dtRoles.Rows.Count > 0)) { foreach (DataRow dr1 in dtRoles.Rows) { Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("role_id", dr1["id"]); newItem.Add("parent_id", dr1["parent_id"]); newItem.Add("context_id", dr1["context_id"]); newItem.Add("name", dr1["name"]); newItem.Add("entity_qty", dr1["entity_qty"]); newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0)); result.Add(newItem); } } return(result); }
/// <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 Boolean adduser(IAMDatabase database, Dictionary <String, Object> parameters) { if (!parameters.ContainsKey("roleid")) { Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null); return(false); } String role = parameters["roleid"].ToString(); if (String.IsNullOrWhiteSpace(role)) { Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null); return(false); } String userid = parameters["userid"].ToString(); if (String.IsNullOrWhiteSpace(userid)) { Error(ErrorType.InvalidRequest, "Parameter userid is not defined.", "", null); return(false); } Int64 roleid = 0; try { roleid = Int64.Parse(role); } catch { Error(ErrorType.InvalidRequest, "Parameter roleid is not a long integer.", "", null); return(false); } List <Int64> users = new List <Int64>(); String[] t = userid.Split(",".ToCharArray()); foreach (String u in t) { try { Int64 tmp = Int64.Parse(u); users.Add(tmp); } catch { Error(ErrorType.InvalidRequest, "Parameter users is not a long integer.", "", null); return(false); } } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@role_id", typeof(Int64)).Value = roleid; DataTable dtUsers = database.ExecuteDataTable("select r.*, c.enterprise_id, entity_qty = (select COUNT(distinct i.entity_id) from identity_role ir inner join [identity] i with(nolock) on ir.identity_id = i.id where ir.role_id = r.id) from role r inner join context c with(nolock) on c.id = r.context_id where c.enterprise_id = @enterprise_id and r.id = @role_id order by r.name", CommandType.Text, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(false); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Role not found.", "", null); return(false); } foreach (Int64 u in users) { DbParameterCollection par2 = new DbParameterCollection(); par2.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par2.Add("@role_id", typeof(Int64)).Value = roleid; par2.Add("@entity_id", typeof(Int64)).Value = u; DataTable dtRet = database.ExecuteDataTable("sp_insert_entity_to_role", CommandType.StoredProcedure, par2); if ((dtRet != null) && (dtRet.Rows.Count > 0)) { database.AddUserLog(LogKey.User_IdentityRoleBind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, u, (Int64)dtRet.Rows[0]["identity_id"], "Identity bind to role " + dtRet.Rows[0]["role_name"].ToString(), ""); } } return(true); }
/// <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> newcontainer(IAMDatabase database, Dictionary <String, Object> parameters) { Dictionary <String, Object> result = new Dictionary <String, Object>(); if (!parameters.ContainsKey("name")) { Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null); return(null); } String name = parameters["name"].ToString(); if (String.IsNullOrWhiteSpace(name)) { Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null); return(null); } if (!parameters.ContainsKey("contextid")) { Error(ErrorType.InvalidRequest, "Parameter contextid is not defined.", "", null); return(null); } Int64 contextid = 0; try { contextid = Int64.Parse((String)parameters["contextid"]); } catch { Error(ErrorType.InvalidRequest, "Parameter contextid is not a long integer.", "", null); return(null); } Int64 parentid = 0; if (parameters.ContainsKey("parentid")) { try { parentid = Int64.Parse(parameters["parentid"].ToString()); } catch { Error(ErrorType.InvalidRequest, "Parameter parentid is not a long integer.", "", null); return(null); } } if (parentid > 0) { DataTable dtPar = database.ExecuteDataTable("select * from [container] c with(nolock) where c.id = " + parentid + " and c.context_id = " + contextid); if ((dtPar == null) || (dtPar.Rows.Count == 0)) { Error(ErrorType.InvalidRequest, "Parent container is not a chield of this context", "", null); return(null); } } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@container_name", typeof(String)).Value = name; par.Add("@parent_id", typeof(Int64)).Value = parentid; par.Add("@context_id", typeof(Int64)).Value = contextid; DataTable dtUsers = database.ExecuteDataTable("sp_new_container", CommandType.StoredProcedure, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Container not found.", "", null); return(null); } //Atualiza a busca com os dados atualizados Dictionary <String, Object> par2 = new Dictionary <string, object>(); par2.Add("containerid", dtUsers.Rows[0]["id"]); return(get(database, par2)); }
/// <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)); }
/// <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> get(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 e.* from enterprise e with(nolock) where e.id = @enterprise_id order by e.name", 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); } DataRow dr1 = dtEnterprise.Rows[0]; Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["id"]); newItem.Add("name", dr1["name"]); newItem.Add("fqdn", dr1["fqdn"]); newItem.Add("server_cert", dr1["server_cert"]); newItem.Add("language", dr1["language"]); newItem.Add("auth_plugin", dr1["auth_plugin"]); newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0)); result.Add("info", newItem); DataTable dtEnterpriseFqdn = database.ExecuteDataTable("select * from enterprise_fqdn_alias where enterprise_id = " + dr1["id"], CommandType.Text, null, null); if ((dtEnterpriseFqdn != null) && (dtEnterpriseFqdn.Rows.Count > 0)) { List <String> fqdn = new List <String>(); foreach (DataRow dr in dtEnterpriseFqdn.Rows) { fqdn.Add(dr["fqdn"].ToString()); } result.Add("fqdn_alias", fqdn); } DataTable dtEnterpriseAuthPars = database.ExecuteDataTable("select * from dbo.enterprise_auth_par where enterprise_id = " + dr1["id"] + " and plugin = '" + dr1["auth_plugin"] + "'", CommandType.Text, null, null); if ((dtEnterpriseAuthPars != null) && (dtEnterpriseAuthPars.Rows.Count > 0)) { List <Dictionary <string, object> > p1 = new List <Dictionary <string, object> >(); foreach (DataRow dr in dtEnterpriseAuthPars.Rows) { Dictionary <string, object> newItem2 = new Dictionary <string, object>(); newItem2.Add("key", dr["key"].ToString()); newItem2.Add("value", dr["value"].ToString()); p1.Add(newItem2); } result.Add("auth_parameters", p1); } return(result); }
/// <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> newenterprise(IAMDatabase database, Dictionary <String, Object> parameters) { Dictionary <String, Object> result = new Dictionary <String, Object>(); if (!parameters.ContainsKey("name")) { Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null); return(null); } String name = parameters["name"].ToString(); if (String.IsNullOrWhiteSpace(name)) { Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null); return(null); } throw new NotImplementedException(); if (!parameters.ContainsKey("password_rule")) { Error(ErrorType.InvalidRequest, "Parameter password_rule is not defined.", "", null); return(null); } String password_rule = parameters["password_rule"].ToString(); if (String.IsNullOrWhiteSpace(password_rule)) { Error(ErrorType.InvalidRequest, "Parameter password_rule is not defined.", "", null); return(null); } if (!parameters.ContainsKey("password_length")) { Error(ErrorType.InvalidRequest, "Parameter password_length is not defined.", "", null); return(null); } String pwdlength = parameters["password_length"].ToString(); if (String.IsNullOrWhiteSpace(pwdlength)) { Error(ErrorType.InvalidRequest, "Parameter password_length is not defined.", "", null); return(null); } Int32 password_length = 0; try { password_length = Int32.Parse(pwdlength); } catch { Error(ErrorType.InvalidRequest, "Parameter password_length is not a integer.", "", null); return(null); } Boolean password_upper_case = true; if (parameters.ContainsKey("password_upper_case")) { try { password_upper_case = Boolean.Parse(parameters["password_upper_case"].ToString()); } catch (Exception ex) { Error(ErrorType.InvalidRequest, "Parameter password_upper_case is not a boolean.", "", null); return(null); } } Boolean password_lower_case = true; if (parameters.ContainsKey("password_lower_case")) { try { password_lower_case = Boolean.Parse(parameters["password_lower_case"].ToString()); } catch (Exception ex) { Error(ErrorType.InvalidRequest, "Parameter password_lower_case is not a boolean.", "", null); return(null); } } Boolean password_digit = true; if (parameters.ContainsKey("password_digit")) { try { password_digit = Boolean.Parse(parameters["password_digit"].ToString()); } catch (Exception ex) { Error(ErrorType.InvalidRequest, "Parameter password_digit is not a boolean.", "", null); return(null); } } Boolean password_symbol = true; if (parameters.ContainsKey("password_symbol")) { try { password_symbol = Boolean.Parse(parameters["password_symbol"].ToString()); } catch (Exception ex) { Error(ErrorType.InvalidRequest, "Parameter password_symbol is not a boolean.", "", null); return(null); } } Boolean password_no_name = true; if (parameters.ContainsKey("password_no_name")) { try { password_no_name = Boolean.Parse(parameters["password_no_name"].ToString()); } catch (Exception ex) { Error(ErrorType.InvalidRequest, "Parameter password_no_name is not a boolean.", "", null); return(null); } } //Valida a regra de senha String pwdMethod = ""; String pwdValue = ""; Regex rex = new Regex(@"(.*?)\[(.*?)\]"); Match m = rex.Match(password_rule); if (m.Success) { pwdMethod = m.Groups[1].Value.ToLower(); pwdValue = m.Groups[2].Value; } if (pwdMethod.ToLower() == "default") { if (String.IsNullOrEmpty(pwdValue)) { Error(ErrorType.InvalidRequest, "Password rule error: not valid password for method 'default'.", "", null); return(null); } else { password_rule = "default[" + pwdValue + "]"; } } else if (pwdMethod.ToLower() == "random") { password_rule = "random[]"; } else { Error(ErrorType.InvalidRequest, "Password rule error: has no valid method.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@name", typeof(String)).Value = name; par.Add("@password_rule", typeof(String)).Value = password_rule; par.Add("@pwd_length", typeof(Int32)).Value = password_length; par.Add("@pwd_upper_case", typeof(Boolean)).Value = password_upper_case; par.Add("@pwd_lower_case", typeof(Boolean)).Value = password_lower_case; par.Add("@pwd_digit", typeof(Boolean)).Value = password_digit; par.Add("@pwd_symbol", typeof(Boolean)).Value = password_symbol; par.Add("@pwd_no_name", typeof(Boolean)).Value = password_no_name; DataTable dtUsers = database.ExecuteDataTable("sp_new_context", CommandType.StoredProcedure, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Context not found.", "", null); return(null); } DataRow dr1 = dtUsers.Rows[0]; Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("context_id", dr1["id"]); newItem.Add("name", dr1["name"]); newItem.Add("password_rule", dr1["password_rule"]); newItem.Add("auth_key_time", dr1["auth_key_time"]); newItem.Add("password_length", dr1["pwd_length"]); newItem.Add("password_upper_case", (Boolean)dr1["pwd_upper_case"]); newItem.Add("password_lower_case", (Boolean)dr1["pwd_lower_case"]); newItem.Add("password_digit", (Boolean)dr1["pwd_digit"]); newItem.Add("password_symbol", (Boolean)dr1["pwd_symbol"]); newItem.Add("password_no_name", (Boolean)dr1["pwd_no_name"]); newItem.Add("entity_qty", (Int32)dr1["entity_qty"]); newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0)); result.Add("info", newItem); return(result); }
/// <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("roleid")) { Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null); return(null); } String role = parameters["roleid"].ToString(); if (String.IsNullOrWhiteSpace(role)) { Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null); return(null); } Int64 roleid = 0; try { roleid = Int64.Parse(role); } catch { Error(ErrorType.InvalidRequest, "Parameter roleid is not a long integer.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@role_id", typeof(Int64)).Value = roleid; DataTable dtUsers = database.ExecuteDataTable("select r.*, c.enterprise_id, entity_qty = (select COUNT(distinct i.entity_id) from identity_role ir inner join [identity] i with(nolock) on ir.identity_id = i.id where ir.role_id = r.id) from role r inner join context c with(nolock) on c.id = r.context_id where c.enterprise_id = @enterprise_id and r.id = @role_id order by r.name", CommandType.Text, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Role not found.", "", null); return(null); } List <String> log = new List <String>(); String updateSQL = "update role set "; Boolean update = false; if (parameters["name"] != null) { String name = parameters["name"].ToString(); if (!String.IsNullOrWhiteSpace(name)) { par.Add("@name", typeof(String)).Value = name; updateSQL += "name = @name"; update = true; log.Add("Name changed from '" + dtUsers.Rows[0]["name"] + "' to '" + name + "'"); } } if (update) { updateSQL += " where id = @role_id"; database.ExecuteNonQuery(updateSQL, CommandType.Text, par); database.AddUserLog(LogKey.Role_Changed, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Role changed", String.Join("\r\n", log)); } //Atualiza a busca com os dados atualizados dtUsers = database.ExecuteDataTable("select r.*, c.enterprise_id, entity_qty = (select COUNT(distinct i.entity_id) from identity_role ir inner join [identity] i with(nolock) on ir.identity_id = i.id where ir.role_id = r.id) from role r inner join context c with(nolock) on c.id = r.context_id where c.enterprise_id = @enterprise_id and r.id = @role_id order by r.name", CommandType.Text, par, null); DataRow dr1 = dtUsers.Rows[0]; Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("role_id", dr1["id"]); newItem.Add("parent_id", dr1["parent_id"]); newItem.Add("context_id", dr1["context_id"]); newItem.Add("name", dr1["name"]); newItem.Add("entity_qty", dr1["entity_qty"]); newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0)); result.Add("info", newItem); return(result); }
/// <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> get(IAMDatabase database, Dictionary <String, Object> parameters) { Dictionary <String, Object> result = new Dictionary <String, Object>(); if (!parameters.ContainsKey("containerid")) { Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null); return(null); } String container = parameters["containerid"].ToString(); if (String.IsNullOrWhiteSpace(container)) { Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null); return(null); } Int64 containerid = 0; try { containerid = Int64.Parse(container); } catch { Error(ErrorType.InvalidRequest, "Parameter containerid is not a long integer.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@container_id", typeof(Int64)).Value = containerid; DataTable dtUsers = database.ExecuteDataTable("select c.*, c1.enterprise_id, c1.name context_name, entity_qty = (select COUNT(distinct e.id) from entity e with(nolock) inner join entity_container ec with(nolock) on e.id = ec.entity_id where ec.container_id = c.id) from container c with(nolock) inner join context c1 with(nolock) on c1.id = c.context_id where c1.enterprise_id = @enterprise_id and c.id = @container_id order by c.name", CommandType.Text, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Container not found.", "", null); return(null); } DataRow dr1 = dtUsers.Rows[0]; Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("container_id", dr1["id"]); newItem.Add("context_id", dr1["context_id"]); newItem.Add("context_name", dr1["context_name"]); newItem.Add("parent_id", dr1["parent_id"]); newItem.Add("name", dr1["name"]); newItem.Add("path", getPath(database, this._enterpriseId, (Int64)dr1["id"])); newItem.Add("entity_qty", (Int32)dr1["entity_qty"]); newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0)); result.Add("info", newItem); return(result); }
/// <summary> /// Método privado para processamento do método 'user.search' /// </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 List <Dictionary <String, Object> > users(IAMDatabase database, Dictionary <String, Object> parameters) { List <Dictionary <String, Object> > result = new List <Dictionary <String, Object> >(); if (!parameters.ContainsKey("roleid")) { Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null); return(null); } String role = parameters["roleid"].ToString(); if (String.IsNullOrWhiteSpace(role)) { Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null); return(null); } Int64 roleid = 0; try { roleid = Int64.Parse(role); } catch { Error(ErrorType.InvalidRequest, "Parameter roleid is not a long integer.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@role_id", typeof(Int64)).Value = roleid; Boolean deleted = false; if ((parameters.ContainsKey("deleted")) && (parameters["deleted"] is Boolean)) { deleted = (Boolean)parameters["deleted"]; } Int32 page = 1; Int32 pageSize = 10; if (parameters.ContainsKey("page")) { Int32.TryParse(parameters["page"].ToString(), out page); } if (parameters.ContainsKey("page_size")) { Int32.TryParse(parameters["page_size"].ToString(), out pageSize); } if (pageSize < 1) { pageSize = 1; } if (page < 1) { page = 1; } Int32 rStart = ((page - 1) * pageSize) + 1; Int32 rEnd = rStart + (pageSize - 1); String sql = ""; sql += "WITH result_set AS ("; sql += " SELECT"; sql += " ROW_NUMBER() OVER (ORDER BY e.full_name) AS [row_number], e.*"; sql += " from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id"; sql += " inner join [identity] i with(nolock) on i.entity_id = e.id"; sql += " inner join identity_role ir on ir.identity_id = i.id"; sql += " inner join role r on ir.role_id = r.id"; sql += " WHERE "; sql += " (" + (deleted ? "" : "e.deleted = 0 and") + " c.enterprise_id = @enterprise_id and r.id = @role_id)"; sql += " ) SELECT"; sql += " *"; sql += " FROM"; sql += " result_set"; sql += " WHERE"; sql += " [row_number] BETWEEN " + rStart + " AND " + rEnd; //DataTable dtUsers = database.ExecuteDataTable( "select * from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id where " + (deleted ? "" : "e.deleted = 0 and") + " c.enterprise_id = @enterprise_id " + (String.IsNullOrWhiteSpace(text) ? "" : " and e.full_name like '%'+@text+'%' or e.login like '%'+@text+'%' ") + " order by e.full_name", CommandType.Text, par, null); DataTable dtUsers = database.ExecuteDataTable(sql, CommandType.Text, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "User list not found.", "", null); return(null); } foreach (DataRow dr in dtUsers.Rows) { Dictionary <String, Object> newItem = new Dictionary <string, object>(); newItem.Add("userid", dr["id"]); newItem.Add("alias", dr["alias"]); newItem.Add("login", dr["login"]); newItem.Add("full_name", dr["full_name"]); newItem.Add("create_date", (Int32)((((DateTime)dr["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds)); newItem.Add("change_password", (dr["change_password"] != DBNull.Value ? (Int32)((((DateTime)dr["change_password"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0)); newItem.Add("last_login", (dr["last_login"] != DBNull.Value ? (Int32)((((DateTime)dr["last_login"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0)); newItem.Add("must_change_password", dr["must_change_password"]); newItem.Add("locked", dr["locked"]); result.Add(newItem); } return(result); }
/// <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 Boolean delete(IAMDatabase database, Dictionary <String, Object> parameters) { if (!parameters.ContainsKey("containerid")) { Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null); return(false); } String container = parameters["containerid"].ToString(); if (String.IsNullOrWhiteSpace(container)) { Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null); return(false); } Int64 containerid = 0; try { containerid = Int64.Parse(container); } catch { Error(ErrorType.InvalidRequest, "Parameter containerid is not a long integer.", "", null); return(false); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@container_id", typeof(Int64)).Value = containerid; DataTable dtUsers = database.ExecuteDataTable("select c.*, entity_qty = (select COUNT(distinct e.id) from entity e with(nolock) inner join entity_container ec with(nolock) on e.id = ec.entity_id where ec.container_id = c.id), chield_qty = (select COUNT(distinct chield.id) from container chield with(nolock) where chield.parent_id = c.id) from container c with(nolock) inner join context c1 with(nolock) on c1.id = c.context_id where c1.enterprise_id = @enterprise_id and c.id = @container_id order by c.name", CommandType.Text, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(false); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Container not found.", "", null); return(false); } if ((Int32)dtUsers.Rows[0]["entity_qty"] > 0) { Error(ErrorType.InvalidRequest, "Container is not empty.", "", null); return(false); } if ((Int32)dtUsers.Rows[0]["chield_qty"] > 0) { Error(ErrorType.InvalidRequest, "Container has chield containers.", "", null); return(false); } database.ExecuteNonQuery("delete from container where id = @container_id", CommandType.Text, par); database.AddUserLog(LogKey.Context_Deleted, null, "API", UserLogLevel.Error, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Container " + dtUsers.Rows[0]["name"] + " deleted", ""); return(true); }
/// <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> newfield(IAMDatabase database, Dictionary <String, Object> parameters) { Dictionary <String, Object> result = new Dictionary <String, Object>(); if (!parameters.ContainsKey("name")) { Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null); return(null); } String name = parameters["name"].ToString(); if (String.IsNullOrWhiteSpace(name)) { Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null); return(null); } if (!parameters.ContainsKey("data_type")) { Error(ErrorType.InvalidRequest, "Parameter data_type is not defined.", "", null); return(null); } String data_type = parameters["data_type"].ToString(); if (String.IsNullOrWhiteSpace(data_type)) { Error(ErrorType.InvalidRequest, "Parameter data_type is not defined.", "", null); return(null); } Boolean public_field = false; if (parameters.ContainsKey("public_field")) { try { public_field = Boolean.Parse(parameters["public_field"].ToString()); } catch (Exception ex) { Error(ErrorType.InvalidRequest, "Parameter public_field is not a boolean.", "", null); return(null); } } Boolean user_field = false; if (parameters.ContainsKey("user_field")) { try { user_field = Boolean.Parse(parameters["user_field"].ToString()); } catch (Exception ex) { Error(ErrorType.InvalidRequest, "Parameter user_field is not a boolean.", "", null); return(null); } } switch (data_type.ToLower()) { case "string": case "datetime": case "numeric": break; default: Error(ErrorType.InvalidRequest, "Data type is not recognized.", "", null); return(null); break; } DbParameterCollection par2 = new DbParameterCollection(); par2.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par2.Add("@field_name", typeof(String)).Value = name; DataTable dtF1 = database.ExecuteDataTable("select * from field with(nolock) where enterprise_id = @enterprise_id and name = @field_name", CommandType.Text, par2, null); if ((dtF1 != null) && (dtF1.Rows.Count > 0)) { Error(ErrorType.InvalidRequest, "Field with the same name already exists.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@data_type", typeof(String)).Value = data_type; par.Add("@field_name", typeof(String)).Value = name; par.Add("@public", typeof(Boolean)).Value = public_field; par.Add("@user", typeof(Boolean)).Value = user_field; DataTable dtUsers = database.ExecuteDataTable("sp_new_field", CommandType.StoredProcedure, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Field not found.", "", null); return(null); } DataRow dr1 = dtUsers.Rows[0]; Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("field_id", dr1["id"]); newItem.Add("name", dr1["name"]); newItem.Add("public_field", dr1["public"]); newItem.Add("user_field", dr1["user"]); result.Add("info", newItem); return(result); }
/// <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("containerid")) { Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null); return(null); } String container = parameters["containerid"].ToString(); if (String.IsNullOrWhiteSpace(container)) { Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null); return(null); } Int64 containerid = 0; try { containerid = Int64.Parse(container); } catch { Error(ErrorType.InvalidRequest, "Parameter containerid is not a long integer.", "", null); return(null); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@container_id", typeof(Int64)).Value = containerid; DataTable dtUsers = database.ExecuteDataTable("select c.* from container c with(nolock) inner join context c1 with(nolock) on c1.id = c.context_id where c1.enterprise_id = @enterprise_id and c.id = @container_id order by c.name", CommandType.Text, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(null); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Container not found.", "", null); return(null); } String updateSQL = "update container set "; String updateFields = ""; Boolean update = 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 "parentid": Int64 parentid = 0; if (parameters.ContainsKey("parentid")) { try { parentid = Int64.Parse(parameters["parentid"].ToString()); } catch { Error(ErrorType.InvalidRequest, "Parameter parentid is not a long integer.", "", null); return(null); } } if (parentid > 0) { if (parentid == (Int64)dtUsers.Rows[0]["context_id"]) { Error(ErrorType.InvalidRequest, "Parent container can not be this container", "", null); return(null); } DataTable dtPar = database.ExecuteDataTable("select * from [container] c with(nolock) where c.id = " + parentid + " and c.context_id = " + dtUsers.Rows[0]["context_id"]); if ((dtPar == null) || (dtPar.Rows.Count == 0)) { Error(ErrorType.InvalidRequest, "Parent container is not a chield of this context", "", null); return(null); } } par.Add("@parent_id", typeof(Int64)).Value = parentid; if (updateFields != "") { updateFields += ", "; } updateFields += "parent_id = @parent_id"; update = true; break; } } if (update) { updateSQL += updateFields + " where id = @container_id"; database.ExecuteNonQuery(updateSQL, CommandType.Text, par); } //Atualiza a busca com os dados atualizados return(get(database, parameters)); }
/// <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 Boolean delete(IAMDatabase database, Dictionary <String, Object> parameters) { if (!parameters.ContainsKey("fieldid")) { Error(ErrorType.InvalidRequest, "Parameter fieldid is not defined.", "", null); return(false); } String field = parameters["fieldid"].ToString(); if (String.IsNullOrWhiteSpace(field)) { Error(ErrorType.InvalidRequest, "Parameter fieldid is not defined.", "", null); return(false); } Int64 fieldid = 0; try { fieldid = Int64.Parse(field); } catch { Error(ErrorType.InvalidRequest, "Parameter fieldid is not a long integer.", "", null); return(false); } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@field_id", typeof(Int64)).Value = fieldid; DataTable dtField = database.ExecuteDataTable("select f.*, qty = (select COUNT(*) from resource_plugin rp with(nolock) where name_field_id = f.id or mail_field_id = f.id or login_field_id = f.id) + (select COUNT(*) from resource_plugin_mapping rpm with(nolock) where rpm.field_id = f.id) from field f with(nolock) where f.enterprise_id = @enterprise_id and f.id = @field_id", CommandType.Text, par, null); if (dtField == null) { Error(ErrorType.InternalError, "", "", null); return(false); } if (dtField.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Field not found.", "", null); return(false); } //Verifica se está sendo usado if ((Int32)dtField.Rows[0]["qty"] > 0) { Error(ErrorType.SystemError, "Field is being used and can not be deleted.", "", null); return(false); } database.ExecuteNonQuery("delete from field where id = @field_id", CommandType.Text, par); database.AddUserLog(LogKey.Field_Deleted, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Field " + dtField.Rows[0]["name"] + " deleted", ""); return(true); }
/// <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 List <Object> list(IAMDatabase database, Dictionary <String, Object> parameters) { List <Object> result = new List <Object>(); String text = ""; if (parameters.ContainsKey("text")) { text = (String)parameters["text"]; } if (String.IsNullOrWhiteSpace(text)) { text = ""; } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@text", typeof(String)).Value = text; Int32 page = 1; Int32 pageSize = 10; if (parameters.ContainsKey("page")) { Int32.TryParse(parameters["page"].ToString(), out page); } if (parameters.ContainsKey("page_size")) { Int32.TryParse(parameters["page_size"].ToString(), out pageSize); } if (pageSize < 1) { pageSize = 1; } if (page < 1) { page = 1; } Int32 rStart = ((page - 1) * pageSize) + 1; Int32 rEnd = rStart + (pageSize - 1); //select c.*, entity_qty = (select COUNT(distinct e.id) from entity e with(nolock) inner join entity_container ec with(nolock) on e.id = ec.entity_id where ec.container_id = c.id) from container c with(nolock) inner join context c1 with(nolock) on c1.id = c.context_id where c1.enterprise_id = @enterprise_id and c.id = @container_id order by c.name String sql = ""; sql += "WITH result_set AS ("; sql += " SELECT "; sql += " ROW_NUMBER() OVER (ORDER BY c.name) AS [row_number], c.*, c1.enterprise_id, c1.name context_name, entity_qty = (select COUNT(distinct e.id) from entity e with(nolock) inner join entity_container ec with(nolock) on e.id = ec.entity_id where ec.container_id = c.id) "; sql += " from container c with(nolock) inner join context c1 with(nolock) on c1.id = c.context_id "; sql += " where c1.enterprise_id = @enterprise_id " + (String.IsNullOrWhiteSpace(text) ? "" : " and c.name like '%'+@text+'%'"); sql += ") SELECT"; sql += " *"; sql += " FROM"; sql += " result_set"; sql += " WHERE"; sql += " [row_number] BETWEEN " + rStart + " AND " + rEnd; DataTable dtContext = database.ExecuteDataTable(sql, CommandType.Text, par, null); if ((dtContext != null) && (dtContext.Rows.Count > 0)) { foreach (DataRow dr1 in dtContext.Rows) { Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("container_id", dr1["id"]); newItem.Add("context_id", dr1["context_id"]); newItem.Add("context_name", dr1["context_name"]); newItem.Add("parent_id", dr1["parent_id"]); newItem.Add("name", dr1["name"]); newItem.Add("path", getPath(database, this._enterpriseId, (Int64)dr1["id"])); newItem.Add("entity_qty", (Int32)dr1["entity_qty"]); newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0)); result.Add(newItem); } } return(result); }
/// <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 List <Object> list(IAMDatabase database, Dictionary <String, Object> parameters) { List <Object> result = new List <Object>(); String text = ""; if (parameters.ContainsKey("text")) { text = (String)parameters["text"]; } if (String.IsNullOrWhiteSpace(text)) { text = ""; } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@text", typeof(String)).Value = text; Int32 page = 1; Int32 pageSize = 10; if (parameters.ContainsKey("page")) { Int32.TryParse(parameters["page"].ToString(), out page); } if (parameters.ContainsKey("page_size")) { Int32.TryParse(parameters["page_size"].ToString(), out pageSize); } if (pageSize < 1) { pageSize = 1; } if (page < 1) { page = 1; } Int32 rStart = ((page - 1) * pageSize) + 1; Int32 rEnd = rStart + (pageSize - 1); String sql = ""; sql += "WITH result_set AS ("; sql += " SELECT "; sql += " ROW_NUMBER() OVER (ORDER BY f.name) AS [row_number], f.* "; sql += " from field f with(nolock)"; sql += " where f.enterprise_id = @enterprise_id " + (String.IsNullOrWhiteSpace(text) ? "" : " and f.name like '%'+@text+'%'"); sql += ") SELECT"; sql += " *"; sql += " FROM"; sql += " result_set"; sql += " WHERE"; sql += " [row_number] BETWEEN " + rStart + " AND " + rEnd; DataTable dtRoles = database.ExecuteDataTable(sql, CommandType.Text, par, null); if ((dtRoles != null) && (dtRoles.Rows.Count > 0)) { foreach (DataRow dr1 in dtRoles.Rows) { Dictionary <string, object> newItem = new Dictionary <string, object>(); newItem.Add("enterprise_id", dr1["enterprise_id"]); newItem.Add("field_id", dr1["id"]); newItem.Add("data_type", dr1["data_type"]); newItem.Add("name", dr1["name"]); newItem.Add("public_field", dr1["public"]); newItem.Add("user_field", dr1["user"]); result.Add(newItem); } } return(result); }
/// <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 Boolean adduser(IAMDatabase database, Dictionary <String, Object> parameters) { if (!parameters.ContainsKey("containerid")) { Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null); return(false); } String role = parameters["containerid"].ToString(); if (String.IsNullOrWhiteSpace(role)) { Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null); return(false); } String userid = parameters["userid"].ToString(); if (String.IsNullOrWhiteSpace(userid)) { Error(ErrorType.InvalidRequest, "Parameter userid is not defined.", "", null); return(false); } Int64 containerid = 0; try { containerid = Int64.Parse(role); } catch { Error(ErrorType.InvalidRequest, "Parameter containerid is not a long integer.", "", null); return(false); } List <Int64> users = new List <Int64>(); String[] t = userid.Split(",".ToCharArray()); foreach (String u in t) { try { Int64 tmp = Int64.Parse(u); users.Add(tmp); } catch { Error(ErrorType.InvalidRequest, "Parameter users is not a long integer.", "", null); return(false); } } DbParameterCollection par = new DbParameterCollection(); par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par.Add("@container_id", typeof(Int64)).Value = containerid; DataTable dtUsers = database.ExecuteDataTable("select c.*, c1.enterprise_id, c1.name context_name, entity_qty = (select COUNT(distinct e.id) from entity e with(nolock) inner join entity_container ec with(nolock) on e.id = ec.entity_id where ec.container_id = c.id) from container c with(nolock) inner join context c1 with(nolock) on c1.id = c.context_id where c1.enterprise_id = @enterprise_id and c.id = @container_id order by c.name", CommandType.Text, par, null); if (dtUsers == null) { Error(ErrorType.InternalError, "", "", null); return(false); } if (dtUsers.Rows.Count == 0) { Error(ErrorType.InvalidRequest, "Container not found.", "", null); return(false); } try { SqlTransaction trans = (SqlTransaction)database.BeginTransaction(); foreach (Int64 u in users) { DbParameterCollection par2 = new DbParameterCollection(); par2.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId; par2.Add("@container_id", typeof(Int64)).Value = containerid; par2.Add("@entity_id", typeof(Int64)).Value = u; //Select all old containers DataTable drContainers = database.ExecuteDataTable("select c.* from entity_container e inner join container c on c.id = e.container_id where e.entity_id = @entity_id", CommandType.Text, par2, trans); if ((drContainers != null) && (drContainers.Rows.Count > 0)) { foreach (DataRow dr in drContainers.Rows) { if ((Int64)dr["id"] == containerid) { database.AddUserLog(LogKey.User_ContainerRoleUnbind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, u, 0, "Identity unbind to container " + dr["name"].ToString(), "", Acl.EntityId, trans); } } } DataTable dtRet = database.ExecuteDataTable("sp_insert_entity_to_container", CommandType.StoredProcedure, par2, trans); if ((dtRet != null) && (dtRet.Rows.Count > 0)) { database.AddUserLog(LogKey.User_ContainerRoleBind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, u, 0, "Identity bind to container " + dtRet.Rows[0]["name"].ToString(), "", Acl.EntityId, trans); database.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + u + ")", CommandType.Text, null, trans); } } database.Commit(); } catch (Exception ex) { database.Rollback(); Error(ErrorType.InvalidRequest, "Error on bind user to container", ex.Message, null); return(false); } return(true); }