private void DebugLog(PluginLogType type, String text) { #if DEBUG if (OnLog != null) { OnLog(this, type, text); } #endif }
/// <summary> /// Process Import, this Method is called when the system is Import all users from replicated system /// </summary> /// <param name="cacheId">Unique ID to cache</param> /// <param name="importId">Unique ID to import package</param> /// <param name="config">Dictionary with all configuration filled by Admin</param> /// <param name="fieldMapping">Fields mapping filled by Admin at "Web Console > Resource x Plugin > Fields Mapping"</param> public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { String lastStep = "CheckInputConfig"; if (!CheckInputConfig(config, true, Log)) { return; } StringBuilder processLog = new StringBuilder(); StringBuilder debugLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { lastStep = "Get user List"; for (Int32 user = 0; user <= 10; user++) { //One package by user PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId); package.AddProperty("username", "test-" + user, "string"); // User Login from replicated system package.AddProperty("full_name", "Test Name to Sample User " + user, "string"); // User Full Name from replicated system ImportPackageUser(package); } } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process import (" + lastStep + "): " + ex.Message); Log2(this, PluginLogType.Error, 0, 0, "Error on process import: " + ex.Message, "Last step: " + lastStep); } finally { if (logType != PluginLogType.Information) { processLog.AppendLine(debugLog.ToString()); } Log2(this, logType, 0, 0, "Import executed", processLog.ToString()); processLog.Clear(); processLog = null; debugLog.Clear(); debugLog = null; } }
private void OnDebugLog(PluginLogType logtype, string msg) { switch (logtype) { case PluginLogType.Information: Debug.Log(msg); break; case PluginLogType.Warning: Debug.LogWarning(msg); break; case PluginLogType.Error: Debug.LogError(msg); break; } }
/// <summary> /// Process Import After User Deploy, this Method is called when the system is Import only deployed user from replicated system /// </summary> /// <param name="cacheId">Unique ID to cache</param> /// <param name="package">Deployed package</param> /// <param name="config">Dictionary with all configuration filled by Admin</param> /// <param name="fieldMapping">Fields mapping filled by Admin at "Web Console > Resource x Plugin > Fields Mapping"</param> public override void ProcessImportAfterDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { String lastStep = "CheckInputConfig"; if (!CheckInputConfig(config, true, Log)) { return; } StringBuilder processLog = new StringBuilder(); StringBuilder debugLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; String importId = Guid.NewGuid().ToString(); try { lastStep = "Get User Data"; PluginConnectorBaseImportPackageUser packageImport = new PluginConnectorBaseImportPackageUser(importId); //package.AddProperty(key, u[key], "string"); ImportPackageUser(packageImport); } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process import (" + lastStep + "): " + ex.Message); Log2(this, PluginLogType.Error, 0, 0, "Error on process import: " + ex.Message, "Last step: " + lastStep); } finally { if (logType != PluginLogType.Information) { processLog.AppendLine(debugLog.ToString()); } Log2(this, logType, 0, 0, "Import executed", processLog.ToString()); processLog.Clear(); processLog = null; debugLog.Clear(); debugLog = null; } }
public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { if (!CheckInputConfig(config, true, Log)) { return; } String table = config["table"].ToString(); String lock_column = (config.ContainsKey("lock_column") ? config["lock_column"].ToString().ToLower() : null); String locked_value = (config.ContainsKey("locked_value") ? config["locked_value"].ToString().ToLower() : null); String unlocked_value = (config.ContainsKey("unlocked_value") ? config["unlocked_value"].ToString().ToLower() : null); OdbcDB db = null; StringBuilder processLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { db = new OdbcDB(config["system_dsn"].ToString(), (config.ContainsKey("username") ? config["username"].ToString() : ""), (config.ContainsKey("password") ? config["password"].ToString() : "")); db.openDB(); List <String> prop = new List <String>(); String login = package.login; //Monta a tabela de campos para a filtragem Dictionary <String, String> filter = new Dictionary <String, String>(); //Adiciona os mapeamentos que são ID ou único para filtragem foreach (PluginConnectorBaseDeployPackageMapping m in fieldMapping) { if ((m.isId || m.isUnique) && !filter.ContainsKey(m.dataName.ToLower())) { filter.Add(m.dataName.ToLower(), null); } } foreach (PluginConnectorBaseDeployPackageMapping m in fieldMapping) { if (m.isLogin && filter.ContainsKey(m.dataName.ToLower())) { filter[m.dataName.ToLower()] = package.login; } else if (m.isName && filter.ContainsKey(m.dataName)) { filter[m.dataName.ToLower()] = package.fullName.fullName; } } //Verifica se a coluna do login é uma coluna da filtragem /* * foreach (String f in deploy_filter.Trim(", ".ToCharArray()).Split(",".ToCharArray())) * if (!filter.ContainsKey(f.ToLower().Trim())) * filter.Add(f.ToLower().Trim(), null); * * if (login_column != null && filter.ContainsKey(login_column)) * filter[login_column] = package.login; * * if (name_column != null && filter.ContainsKey(name_column)) * filter[name_column] = package.fullName.fullName;*/ foreach (PluginConnectorBasePackageData dt in package.importsPluginData) { if (filter.ContainsKey(dt.dataName.ToLower()) && filter[dt.dataName.ToLower()] == null) { filter[dt.dataName.ToLower()] = dt.dataValue; } } foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (filter.ContainsKey(dt.dataName.ToLower()) && filter[dt.dataName.ToLower()] == null) { filter[dt.dataName.ToLower()] = dt.dataValue; } } foreach (PluginConnectorBasePackageData dt in package.properties) { if (filter.ContainsKey(dt.dataName.ToLower()) && filter[dt.dataName.ToLower()] == null) { filter[dt.dataName.ToLower()] = dt.dataValue; } } //Verifica se algum campo da filtragem é nulo foreach (String k in filter.Keys) { if (filter[k] == null) { logType = PluginLogType.Error; processLog.AppendLine("Deploy filter column data of '" + k + "' not found"); String debugInfo = JSON.Serialize2(new { package = package, fieldMapping = fieldMapping }); if (package.password != "") { debugInfo = debugInfo.Replace(package.password, "Replaced for user security"); } Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Deploy filter column data of '" + k + "' not found", debugInfo); return; } } //Resgata a restutura da tabela de destino DataTable dtInsertSchema = db.GetSchema(table); //Monta o where OdbcParameterCollection par = OdbcDB.GetSqlParameterObject(); //Preenche a tabela de parâmetros com os campos do where List <String> f1 = new List <string>(); foreach (DataColumn dc in dtInsertSchema.Columns) { if (filter.ContainsKey(dc.ColumnName.ToLower())) { if (dc.DataType.Equals(typeof(String))) { par.Add("@s_" + dc.ColumnName, GetDBType(dc.DataType)).Value = Corte(filter[dc.ColumnName.ToLower()], dc.MaxLength); } else { par.Add("@s_" + dc.ColumnName, GetDBType(dc.DataType)).Value = filter[dc.ColumnName.ToLower()]; } f1.Add(dc.ColumnName + " = @s_" + dc.ColumnName); } } //Monta todos os campos que serão inseridos/atualizados Dictionary <String, String> data = new Dictionary <String, String>(); foreach (DataColumn dc in dtInsertSchema.Columns) { if (dc.AutoIncrement) { processLog.AppendLine("Field " + dc.ColumnName + " ignored because it was indicated with an AutoIncrement fiend"); } else if (!data.ContainsKey(dc.ColumnName.ToLower())) { //Nao adiciona coluna que é autoincremento (ID) data.Add(dc.ColumnName.ToLower(), null); } } if (data.ContainsKey("locked")) { data["locked"] = (package.locked || package.temp_locked ? "1" : "0"); } DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "lock_column = " + (String.IsNullOrEmpty(lock_column) ? "empty" : lock_column), ""); DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "locked_value = " + (String.IsNullOrEmpty(locked_value) ? "empty" : locked_value), ""); DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "unlocked_value = " + (String.IsNullOrEmpty(unlocked_value) ? "empty" : unlocked_value), ""); if ((lock_column != null) && (data.ContainsKey(lock_column))) { if ((package.locked || package.temp_locked) && (!String.IsNullOrEmpty(locked_value))) { data[lock_column] = locked_value; } else if ((!package.locked && !package.temp_locked) && (!String.IsNullOrEmpty(unlocked_value))) { data[lock_column] = unlocked_value; } else { data[lock_column] = (package.locked || package.temp_locked ? "1" : "0"); } DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "data[lock_column] = " + data[lock_column], ""); } String password_column = ""; foreach (PluginConnectorBaseDeployPackageMapping m in fieldMapping) { if (m.isPassword && data.ContainsKey(m.dataName)) { data[m.dataName] = package.password; password_column = m.dataName; } else if (m.isLogin && data.ContainsKey(m.dataName)) { data[m.dataName] = package.login; } else if (m.isName && data.ContainsKey(m.dataName)) { data[m.dataName] = package.fullName.fullName; } } /*if (login_column != null && data.ContainsKey(login_column)) * data[login_column] = package.login; * * if (password_column != null && data.ContainsKey(password_column)) * data[password_column] = package.password; * * if (name_column != null && data.ContainsKey(name_column)) * data[name_column] = package.fullName.fullName;*/ #if DEBUG processLog.AppendLine("1. Entity Data"); #endif foreach (PluginConnectorBasePackageData dt in package.entiyData) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "1. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("1. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } #if DEBUG processLog.AppendLine("2. Import Plugin Data"); #endif foreach (PluginConnectorBasePackageData dt in package.importsPluginData) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "1. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("2. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } #if DEBUG processLog.AppendLine("3. Plugin Data"); #endif foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "2. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("3. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } #if DEBUG processLog.AppendLine("4. Properties"); #endif foreach (PluginConnectorBasePackageData dt in package.properties) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "3. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("4. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } #if DEBUG processLog.AppendLine("5. Final data"); #endif foreach (String k in data.Keys) { //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "4. data[" + k + "] = " + data[k], ""); #if DEBUG processLog.AppendLine("5. data[" + k + "] = " + data[k]); #endif } //Verifica se o registro existe DataTable dtReg = db.ExecuteDataTable("select * from " + table + " where " + String.Join(" and ", f1), CommandType.Text, par); if (dtReg == null) { logType = PluginLogType.Error; processLog.AppendLine("Error on select data: " + db.LastError); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on select data: " + db.LastError, ""); return; } LogEvent dbExecLog = new LogEvent(delegate(Object sender, PluginLogType type, String text) { processLog.AppendLine(text); }); //Preenche a tabela de parâmetros com os campos que serão inseridos/atualizados if (dtReg.Rows.Count > 0) { //Existe, atualiza List <String> c1 = new List <string>(); foreach (DataColumn dc in dtInsertSchema.Columns) { if (data.ContainsKey(dc.ColumnName.ToLower())) { if (!String.IsNullOrWhiteSpace(data[dc.ColumnName.ToLower()])) { if (dc.DataType.Equals(typeof(String))) { String txt = Corte((data[dc.ColumnName.ToLower()] != null ? data[dc.ColumnName.ToLower()] : ""), dc.MaxLength); par.Add("@" + dc.ColumnName, GetDBType(dc.DataType), txt.Length).Value = txt; } else { par.Add("@" + dc.ColumnName, GetDBType(dc.DataType)).Value = (data[dc.ColumnName.ToLower()] != null ? data[dc.ColumnName.ToLower()] : ""); } c1.Add(dc.ColumnName + " = @" + dc.ColumnName); } } } foreach (OdbcParameter p in par) { #if DEBUG processLog.AppendLine("5. par[" + p.ParameterName + "] = " + p.Value); #endif } String update = "update " + table + " set " + String.Join(", ", c1) + " where " + String.Join(" and ", f1); db.OnLog += dbExecLog; db.ExecuteNonQuery(update, CommandType.Text, par); db.OnLog -= dbExecLog; NotityChangeUser(this, package.entityId); if (package.password != "") { processLog.AppendLine("User updated with password"); } else { processLog.AppendLine("User updated without password"); } } else { //Não existe, cria if ((data.ContainsKey(password_column)) && (package.password == "")) { package.password = IAM.Password.RandomPassword.Generate(16); data[password_column] = package.password; processLog.AppendLine("User not found in AD and IAM Password not found in properties list, creating a random password (" + package.password + ")"); } //Limpa os parâmetros par.Clear(); List <String> c1 = new List <string>(); List <String> c2 = new List <string>(); foreach (DataColumn dc in dtInsertSchema.Columns) { if (data.ContainsKey(dc.ColumnName.ToLower())) { try { if (!String.IsNullOrWhiteSpace(data[dc.ColumnName.ToLower()])) { if (dc.DataType.Equals(typeof(String))) { String txt = Corte((data[dc.ColumnName.ToLower()] != null ? data[dc.ColumnName.ToLower()] : ""), dc.MaxLength); par.Add("@" + dc.ColumnName, GetDBType(dc.DataType), txt.Length).Value = txt; } else { par.Add("@" + dc.ColumnName, GetDBType(dc.DataType)).Value = data[dc.ColumnName.ToLower()]; } c1.Add(dc.ColumnName); c2.Add("@" + dc.ColumnName); } } catch (Exception ex) { processLog.AppendLine("Column: " + dc.ColumnName + ", DataType: " + dc.DataType.ToString()); try { processLog.AppendLine("Value: " + data[dc.ColumnName.ToLower()]); } catch (Exception ex1) { processLog.AppendLine("Value error: " + ex1.Message); } throw new Exception("Erro filling data. Column=" + dc.ColumnName + ", " + dc.DataType.ToString(), ex); } } } foreach (OdbcParameter p in par) { //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "6. par[" + p.ParameterName + "] = " + p.Value, ""); #if DEBUG processLog.AppendLine("6. par[" + p.ParameterName + "] = " + p.Value); #endif } String insert = "insert into " + table + " (" + String.Join(",", c1) + ") values (" + String.Join(",", c2) + ")"; db.OnLog += dbExecLog; db.ExecuteNonQuery(insert, CommandType.Text, par); db.OnLog -= dbExecLog; NotityChangeUser(this, package.entityId); processLog.AppendLine("User added"); } //Executa as ações do RBAC if ((package.pluginAction != null) && (package.pluginAction.Count > 0)) { foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction) { try { switch (act.actionKey.ToLower()) { case "procedure": String sql1 = act.actionValue.Replace("{login}", package.login).Replace("{full_name}", package.fullName.fullName); db.ExecuteNonQuery(sql1, CommandType.StoredProcedure, null); break; case "sql": String sql2 = act.actionValue.Replace("{login}", package.login).Replace("{full_name}", package.fullName.fullName); db.ExecuteNonQuery(sql2, CommandType.Text, null); break; default: processLog.AppendLine("Action not recognized: " + act.actionKey); Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "Action not recognized: " + act.actionKey, ""); break; } } catch (Exception ex) { processLog.AppendLine("Error on execute action (" + act.actionKey + "): " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on execute action (" + act.actionKey + "): " + ex.Message, ""); } } } } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process deploy: " + ex.Message); String debugInfo = JSON.Serialize2(new { package = package, fieldMapping = fieldMapping }); if (package.password != "") { debugInfo = debugInfo.Replace(package.password, "Replaced for user security"); } Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, debugInfo); } finally { if (db != null) { db.Dispose(); } Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString()); processLog.Clear(); processLog = null; } }
static void pg_Log2(Object sender, PluginLogType type, long entityId, long identityId, string text, string additionalData) { Console.WriteLine(text); }
public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { String lastStep = "CheckInputConfig"; if (!CheckInputConfig(config, true, Log)) { return; } StringBuilder processLog = new StringBuilder(); StringBuilder debugLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; AknaAPI akna = new AknaAPI(config["username"].ToString(), config["password"].ToString()); XML.DebugMessage dbgC = new XML.DebugMessage(delegate(String data, String debug) { debugLog.AppendLine("######"); debugLog.AppendLine("## JSON Debug message: " + data); debugLog.AppendLine(debug); #if DEBUG Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "JSON Debug message: " + data, debug); #endif }); try { lastStep = "Check info"; String container = package.container; if (String.IsNullOrEmpty(container)) { container = "IAMUsers"; } //Este plugin estava gerando milhares de listas indevidamente devido ao container //Desta forma foi fixado o container como sempre Sendo SafeIDUsers container = "IAMUsers"; String email = ""; String mail_domain = "";//config["mail_domain"].ToString(); if ((config.ContainsKey("mail_domain")) && (!String.IsNullOrEmpty(config["mail_domain"].ToString()))) { mail_domain = config["mail_domain"].ToString(); } //Busca o e-mail nas propriedades específicas desto usuário foreach (PluginConnectorBasePackageData dt in package.entiyData) { if (dt.dataValue.ToLower().IndexOf("@" + mail_domain) > 1) { email = dt.dataValue; } } //Busca o e-mail nas propriedades específicas deste plugin if ((email == null) || (email == "")) { foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (dt.dataValue.ToLower().IndexOf("@" + mail_domain) > 1) { email = dt.dataValue; } } } //Se não encontrou o e-mail testa nas propriedades maracas como ID if ((email == null) || (email == "")) { foreach (PluginConnectorBasePackageData dt in package.ids) { if (dt.dataValue.ToLower().IndexOf("@" + mail_domain) > 1) { email = dt.dataValue; } } } //Se não encontrou o e-mail testa nas propriedades gerais if ((email == null) || (email == "")) { foreach (PluginConnectorBasePackageData dt in package.properties) { if (dt.dataValue.ToLower().IndexOf("@" + mail_domain) > 1) { email = dt.dataValue; } } } //Se não encontrou nenhum e-mail do dominio principal adiciona qualquer outro e-mail if ((email == null) || (email == "")) { foreach (PluginConnectorBasePackageData dt in package.properties) { if (dt.dataValue.ToLower().IndexOf("@") > 1) { email = dt.dataValue; } } } if (email == "") { String jData = ""; try { jData = JSON.Serialize <PluginConnectorBaseDeployPackage>(package); if (package.password != "") { jData = jData.Replace(package.password, "Replaced for user security"); } } catch { } logType = PluginLogType.Error; processLog.AppendLine("IAM Email not found in properties list. " + jData); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Email not found in properties list.", jData); return; } if ((package.fullName == null) || (package.fullName.fullName.Trim() == "")) { String jData = ""; try { jData = JSON.Serialize <PluginConnectorBaseDeployPackage>(package); if (package.password != "") { jData = jData.Replace(package.password, "Replaced for user security"); } } catch { } logType = PluginLogType.Error; processLog.AppendLine("IAM Full Name not found in properties list. " + jData); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Full Name not found in properties list", jData); return; } lastStep = "Auth"; Uri serverUri = new Uri("https://api.akna.com.br/emkt/int/integracao.php"); CookieContainer cookie = new CookieContainer(); lastStep = "Get groups"; String tst = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<MAIN><FUNC TRANS=\"\" KEY=\"0ea001e9ca76917fcfaffacf5bad\"><RETURN ID=\"01\">Usuário e/ou senha inválidos</RETURN></FUNC></MAIN>"; AknaListResponse tst2 = SafeTrend.Xml.XML.Deserialize <AknaListResponse>(tst); AknaListResponse listas = akna.GetData <AknaListResponse>("<main><emkt trans=\"11.02\"></emkt></main>", cookie, dbgC); //AknaListResponse listas = JSON.JsonWebRequest<AknaListResponse>(serverUri, getPostData(config["username"].ToString(), config["password"].ToString(), "<main><emkt trans=\"11.02\"></emkt></main>"), "application/x-www-form-urlencoded", null, "POST", cookie, dbgC); if ((listas == null) || (listas.EMKT == null) || (listas.EMKT.Listas == null) || (listas.EMKT.Listas.Count == 0)) { logType = PluginLogType.Error; if ((listas != null) && (listas.FUNC != null) && (listas.FUNC._return != null) && (!String.IsNullOrEmpty(listas.FUNC._return[0].value))) { throw new Exception("Error retriving groups: " + listas.FUNC._return[0].value); } else { throw new Exception("Error retriving groups"); } } List <String> dbg = new List <string>(); if ((listas.EMKT.Listas != null) && (listas.EMKT.Listas.Count > 0)) { foreach (AknaListResponse.aknaLista.aknaListaItem l in listas.EMKT.Listas) { dbg.Add("Lista: " + l.name.ToString()); } } lastStep = "Check groups/roles"; List <String> grpIds = new List <String>(); List <String> grpIdsRemove = new List <String>(); //Busca os grupos que este usuário fará parte if ((package.pluginAction != null) && (package.pluginAction.Count > 0)) { foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction) { try { processLog.AppendLine("Role: " + act.roleName + " (" + act.actionType.ToString() + ") " + act.ToString()); switch (act.actionKey.ToLower()) { case "group": if (act.actionType == PluginActionType.Add) { String grpAddId = null; if ((listas.EMKT.Listas != null) && (listas.EMKT.Listas.Count > 0)) { foreach (AknaListResponse.aknaLista.aknaListaItem l in listas.EMKT.Listas) { if ((!String.IsNullOrEmpty(l.name)) && (l.name.ToLower() == act.actionValue.ToLower())) { grpAddId = l.name; grpIds.Add(grpAddId); } } } if (grpAddId == null) { processLog.AppendLine("List '" + act.actionValue + "' not exists yet, creating..."); } try { StringBuilder putXML = new StringBuilder(); putXML.Append("<main><emkt trans=\"11.05\">"); putXML.Append("<nome>" + act.actionValue + "</nome>"); putXML.Append("<substituir>N</substituir>"); putXML.Append("<destinatario codigo=\"" + package.login + "\">"); putXML.Append("<nome>" + package.fullName.fullName + "</nome>"); putXML.Append("<email>" + email + "</email>"); putXML.Append("</destinatario></emkt></main>"); AknaCommandResponse cmd = akna.GetData <AknaCommandResponse>(putXML.ToString(), cookie, dbgC); if ((cmd == null) || (cmd.EMKT == null) || (cmd.EMKT._return == null) || (cmd.EMKT._return.Count == 0) || (cmd.EMKT._return[0].id != "00")) { if ((cmd != null) && (cmd.EMKT != null) && (cmd.EMKT._return != null) && (!String.IsNullOrEmpty(cmd.EMKT._return[0].value))) { throw new Exception("Adding group " + act.actionValue + " by role " + act.roleName + ": " + cmd.EMKT._return[0].value); } else { throw new Exception("Adding group " + act.actionValue + " by role " + act.roleName); } } processLog.AppendLine("User added in group " + act.actionValue + " by role " + act.roleName); } catch (Exception ex) { StringBuilder putXML = new StringBuilder(); putXML.Append("<main><emkt trans=\"11.05\">"); putXML.Append("<nome>" + act.actionValue + "</nome>"); putXML.Append("<substituir>N</substituir>"); putXML.Append("<destinatario codigo=\"" + package.login + "\">"); putXML.Append("<nome>" + package.fullName.fullName + "</nome>"); putXML.Append("<email>" + email + "</email>"); putXML.Append("</destinatario></emkt></main>"); AknaCommandResponse cmd = akna.GetData <AknaCommandResponse>(putXML.ToString(), cookie, dbgC); if ((cmd == null) || (cmd.EMKT == null) || (cmd.EMKT._return == null) || (cmd.EMKT._return.Count == 0) || (cmd.EMKT._return[0].id != "00")) { if ((cmd != null) && (cmd.EMKT != null) && (cmd.EMKT._return != null) && (!String.IsNullOrEmpty(cmd.EMKT._return[0].value))) { throw new Exception("Adding group " + act.actionValue + " by role " + act.roleName + ": " + cmd.EMKT._return[0].value); } else { throw new Exception("Adding group " + act.actionValue + " by role " + act.roleName); } } processLog.AppendLine("User added in group " + act.actionValue + " by role " + act.roleName); } } else if (act.actionType == PluginActionType.Remove) { /*if ((groups != null) && (groups.Length > 0)) * foreach (emGroup g in groups) * if ((!String.IsNullOrEmpty(g.name)) && (g.name.ToLower() == act.actionValue.ToLower())) * { * grpIdsRemove.Add(g.id); * processLog.AppendLine("User removed from group " + act.actionValue + " by role " + act.roleName); * }*/ } break; default: processLog.AppendLine("Action not recognized: " + act.actionKey); break; } } catch (Exception ex) { processLog.AppendLine("Error on execute action (" + act.actionKey + "): " + ex.Message); } } } } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process deploy (" + lastStep + "): " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, "Last step: " + lastStep); } finally { if (logType != PluginLogType.Information) { processLog.AppendLine(debugLog.ToString()); } Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString()); processLog.Clear(); processLog = null; debugLog.Clear(); debugLog = null; } }
public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { if (!CheckInputConfig(config, true, Log)) { return; } String deployLogShort = ""; String deployLogLong = ""; StringBuilder processLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { List <String> prop = new List <String>(); LDAP ldap = new LDAP(config["ldap_server"].ToString(), config["username"].ToString(), config["password"].ToString(), ""); LDAP.DebugLog reg = new LDAP.DebugLog(delegate(String text) { #if DEBUG Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "LDAP log: " + text, ""); #endif }); ldap.Log += reg; try { ldap.Bind(); } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on connect to ActiveDirectory: " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on connect to ActiveDirectory: " + ex.Message, ""); ldap = null; return; } String login = package.login; foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (dt.dataName.ToLower() == "samaccountname") { login = dt.dataValue; } } /*else if (dt.dataName.ToLower() == "displayname") * login = dt.dataValue;*/ if (login == "") { login = package.login; } if (login == "") { logType = PluginLogType.Error; processLog.AppendLine("IAM Login not found in properties list"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Login not found in properties list", ""); return; } String container = "";// package.container; String ou_base = (config.ContainsKey("ou_base") ? config["ou_base"].ToString() : ""); if (!String.IsNullOrWhiteSpace(ou_base)) { container += ou_base.TrimEnd("\\ ".ToCharArray()); } if (container == "") { container = "IAMUsers"; } container = container.Trim("\\ ".ToCharArray()); DirectoryEntry baseCN = ldap.DirectoryEntryRoot; if ((container != null) && (container != "")) { baseCN = ldap.AddContainerTree(container); } if (!String.IsNullOrWhiteSpace(package.container)) { container += "\\" + package.container.Trim("\\ ".ToCharArray()); } container = container.Trim("\\ ".ToCharArray()); DirectoryEntry user = null; SearchResultCollection res = ldap.Find(login); DirectoryEntry ct = ldap.DirectoryEntryRoot; if ((container != null) && (container != "")) { ct = ldap.AddContainerTree(container); } #if DEBUG Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "Container = " + ct.Path, ""); Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "Find user? " + (res.Count > 0), ""); StringBuilder users = new StringBuilder(); users.AppendLine("User collection:"); foreach (SearchResult sr in res) { users.AppendLine("\t" + sr.Path); } #endif if (res.Count == 0) { if (package.password == "") { package.password = IAM.Password.RandomPassword.Generate(16); processLog.AppendLine("User not found in AD and IAM Password not found in properties list, creating a random password (" + package.password + ")"); } ldap.AddUser(ct, package.fullName.fullName, login, package.password); res = ldap.Find(login); processLog.AppendLine("User added"); } user = res[0].GetDirectoryEntry(); processLog.AppendLine("User CN: " + user.Path); try { if (container != "IAMUsers") { ldap.ChangeObjectContainer(user, ct); } } catch (Exception ex) { processLog.AppendLine("Error on change user container: " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on change user container: " + ex.Message, ""); } #if DEBUG Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "User = "******""); #endif UserAccountControl ctrl = (UserAccountControl)user.Properties["useraccountcontrol"][0]; //Limpa as flags que serão verificadas por este sistema if ((ctrl & UserAccountControl.ACCOUNTDISABLE) == UserAccountControl.ACCOUNTDISABLE) { ctrl -= UserAccountControl.ACCOUNTDISABLE; } if ((package.locked) || (package.temp_locked)) { ctrl = (UserAccountControl)((Int32)ctrl + UserAccountControl.ACCOUNTDISABLE); } processLog.AppendLine("User locked? " + (package.locked || package.temp_locked ? "true" : "false")); String[] propNames = new String[user.Properties.PropertyNames.Count]; user.Properties.PropertyNames.CopyTo(propNames, 0); user.Properties["displayname"].Value = package.fullName.fullName; user.Properties["givenName"].Value = package.fullName.givenName; user.Properties["sn"].Value = package.fullName.familyName; user.Properties["userAccountControl"].Value = ctrl; try { try { user.CommitChanges(); } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on commit user data: " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on commit user data: " + ex.Message, ""); return; } try { if (!String.IsNullOrWhiteSpace(package.password)) { user.Invoke("SetPassword", (Object)package.password); } user.CommitChanges(); } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on set user password, check the password complexity rules"); processLog.AppendLine(ex.Message); if (ex.InnerException != null) { processLog.AppendLine(ex.InnerException.Message); } String sPs = ""; try { PasswordStrength ps = CheckPasswordStrength(package.password, package.fullName.fullName); sPs += "Length = " + package.password.Length + Environment.NewLine; sPs += "Contains Uppercase? " + ps.HasUpperCase + Environment.NewLine; sPs += "Contains Lowercase? " + ps.HasLowerCase + Environment.NewLine; sPs += "Contains Symbol? " + ps.HasSymbol + Environment.NewLine; sPs += "Contains Number? " + ps.HasDigit + Environment.NewLine; sPs += "Contains part of the name/username? " + ps.HasNamePart + Environment.NewLine; processLog.AppendLine(sPs); } catch { } Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on set user password, check the password complexity rules", ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : "") + Environment.NewLine + sPs); return; } //Atribui as outras variáveis processLog.AppendLine("Property update"); try { processLog.AppendLine("\tCompany: " + package.enterprise); processLog.AppendLine("\tCompany exists: " + user.Properties.Contains("company")); if (!String.IsNullOrEmpty(package.enterprise)) { if (user.Properties.Contains("company")) { user.Properties["company"].Value = package.enterprise; } else { user.Properties["company"].Add(package.enterprise); } } user.CommitChanges(); } catch (Exception ex) { processLog.AppendLine("\tError on set user company: " + ex.Message); } //Monta todos os campos que serão inseridos/atualizados Dictionary <String, String> data = new Dictionary <String, String>(); Dictionary <String, String> mostKnolege = GetCommonItems(); foreach (String k in mostKnolege.Keys) { if (!data.ContainsKey(k)) { data.Add(k, null); } } foreach (PropertyValueCollection property in user.Properties) { if (!data.ContainsKey(property.PropertyName.ToLower())) { data.Add(property.PropertyName.ToLower(), null); } } foreach (PluginConnectorBasePackageData dt in package.importsPluginData) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "1. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("1. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "2. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("2. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } foreach (PluginConnectorBasePackageData dt in package.properties) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "3. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("3. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } //Remove os ítens protegidos pelo AD, onde a forma de atualização deve ser outra data.Remove("whencreated"); data.Remove("lastlogon"); data.Remove("name"); data.Remove("lockouttime"); data.Remove("useraccountcontrol"); data.Remove("memberof"); data.Remove("distinguishedname"); data.Remove("samaccountname"); data.Remove("displayname"); data.Remove("givenname"); data.Remove("sn"); data.Remove("cn"); foreach (String k in data.Keys) { if (data[k] != null) { try { // SearchResultCollection res2 = ldap.Find(login); user = res2[0].GetDirectoryEntry(); processLog.AppendLine("\t" + k + " exists: " + user.Properties.Contains(k)); if (!String.IsNullOrEmpty(package.enterprise)) { if (user.Properties.Contains(k)) { user.Properties[k].Value = data[k]; } else { user.Properties[k].Add(data[k]); } } user.CommitChanges(); } catch (Exception ex) { processLog.AppendLine("\tError setting data '" + k + "': " + ex.Message); } } } processLog.AppendLine("RBAC"); //Busca o usuário novamente //Para não aplicas as informações incorretas //Devido a definição das propriedades anteriores res = ldap.Find(login); user = res[0].GetDirectoryEntry(); //Executa as ações do RBAC if ((package.pluginAction != null) && (package.pluginAction.Count > 0)) { foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction) { try { processLog.AppendLine("\tRole: " + act.roleName + " (" + act.actionType.ToString() + ") " + act.ToString()); switch (act.actionKey.ToLower()) { case "group": if (act.actionType == PluginActionType.Add) { String grpCN = ldap.FindOrCreateGroup(baseCN, act.actionValue); if (ldap.addUserToGroup(user.Name, grpCN)) { processLog.AppendLine("\tUser added in group " + act.actionValue + " by role " + act.roleName); } } else if (act.actionType == PluginActionType.Remove) { String grpCN = ldap.FindOrCreateGroup(baseCN, act.actionValue); if (ldap.removeUserFromGroup(user.Name, grpCN)) { processLog.AppendLine("\tUser removed from group " + act.actionValue + " by role " + act.roleName); } } break; default: processLog.AppendLine("\tAction not recognized: " + act.actionKey); break; } } catch (Exception ex) { processLog.AppendLine("\tError on execute action (" + act.actionKey + "): " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on execute action (" + act.actionKey + "): " + ex.Message, ""); } } } } finally { user.Close(); } NotityChangeUser(this, package.entityId); if (package.password != "") { processLog.AppendLine("User updated with password"); } else { processLog.AppendLine("User updated without password"); } } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process deploy: " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, ""); } finally { Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString()); processLog.Clear(); processLog = null; } }
public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { if (!CheckInputConfig(config, true, Log)) { return; } StringBuilder processLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { GetLoginToken(config); setUserGrp(config); String login = package.login; foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (dt.dataName.ToLower() == "login") { login = dt.dataValue; } } if (login == "") { login = package.login; } if (login == "") { logType = PluginLogType.Error; processLog.AppendLine("IAM Login not found in properties list"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Login not found in properties list", ""); return; } String email = ""; String container = package.container; //Busca o e-mail nas propriedades específicas da entidade foreach (PluginConnectorBasePackageData dt in package.entiyData) { if ((dt.dataName.ToLower() == "email") && (dt.dataValue.ToLower().IndexOf("@") > 1)) { email = dt.dataValue; } } //Busca o e-mail nas propriedades específicas deste plugin if ((email == null) || (email == "")) { foreach (PluginConnectorBasePackageData dt in package.pluginData) { if ((dt.dataName.ToLower() == "email") && (dt.dataValue.ToLower().IndexOf("@") > 1)) { email = dt.dataValue; } } } //Se não encontrou o e-mail testa nas propriedades maracas como ID if ((email == null) || (email == "")) { foreach (PluginConnectorBasePackageData dt in package.ids) { if ((dt.dataName.ToLower() == "email") && (dt.dataValue.ToLower().IndexOf("@") > 1)) { email = dt.dataValue; } } } //Se não encontrou o e-mail testa nas propriedades gerais if ((email == null) || (email == "")) { foreach (PluginConnectorBasePackageData dt in package.properties) { if ((dt.dataName.ToLower() == "email") && (dt.dataValue.ToLower().IndexOf("@") > 1)) { email = dt.dataValue; } } } if (email == "") { logType = PluginLogType.Error; processLog.AppendLine("IAM E-mail not found in properties list"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM E-mail not found in properties list", ""); return; } if (container == "") { container = "IAMUsers"; } WebServiceObjectInterface oUser = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "getUser", new Object[] { this.loginToken, email }); if ((oUser == null) || (oUser.BaseObject == null)) { //User not found, create then if ((package.locked) || (package.temp_locked)) { logType = PluginLogType.Error; processLog.AppendLine("User not found in JIRA and user is locked. Accound not created"); Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "User not found in JIRA and user is locked. Accound not created", ""); return; } if (package.password == "") { package.password = IAM.Password.RandomPassword.Generate(16); processLog.AppendLine("User not found in JIRA and IAM Password not found in properties list, creating a random password (" + package.password + ")"); } if ((package.locked) || (package.temp_locked)) { //O JIRA não permite o bloqueio da conta, a forma encontrada de bloquea-la é trocando a senha package.password = IAM.Password.RandomPassword.Generate(16); package.fullName.familyName += " (locked)"; } oUser = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "createUser", new Object[] { this.loginToken, email, package.password, package.fullName.fullName, email }); if ((oUser == null) || (oUser.BaseObject == null)) { logType = PluginLogType.Error; processLog.AppendLine("Unexpected error on add user on JIRA"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Unexpected error on add user on JIRA", ""); return; } //Mantem somente os grupos padrões if (oUser.BaseObject != null) { List <String> groups = GetUserGroups(config, email); foreach (String usrG in groups) { Boolean remove = false; if ((package.locked) || (package.temp_locked)) { remove = true; } else if (!defaultGroups.Exists(g => (g.ToLower() == usrG.ToLower()))) { remove = true; } if (remove) //Remove o grupo do usuário { try { WebServiceObjectInterface oGrp = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "getGroup", new Object[] { this.loginToken, usrG }); if (oGrp.BaseObject == null) { processLog.AppendLine("Error on remove user from group '" + usrG + "' group not found"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on remove user from group '" + usrG + "' group not found", ""); } else { WebServiceObjectInterface tst3 = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "removeUserFromGroup", new Object[] { this.loginToken, oGrp.BaseObject, oUser.BaseObject }); } } catch (Exception ex) { processLog.AppendLine("Error on remove user from group '" + usrG + "' " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : "")); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on remove user from group '" + usrG + "' " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : ""), ""); } } } } processLog.AppendLine("User added"); } else { //User found, update if ((package.locked) || (package.temp_locked)) { //O JIRA não permite o bloqueio da conta, a forma encontrada de bloquea-la é trocando a senha package.password = IAM.Password.RandomPassword.Generate(16); processLog.AppendLine("User locked, password temporarily changed to a random password " + package.password); } /* * oUser.SettPropertyValue("email", email); * oUser.SettPropertyValue("fullname", package.fullName.fullName + (package.locked ? " (locked)" : "")); * oUser.SettPropertyValue("name", email);*/ ChangeUser(config, email, package.fullName.fullName + (package.locked || package.temp_locked ? " (locked)" : ""), email); if (!String.IsNullOrWhiteSpace(package.password) && (ChangePassword(config, email, package.password))) { processLog.AppendLine("User updated with password"); } else { processLog.AppendLine("User updated without password"); } } //Verifica e redefine os grupos if (oUser.BaseObject != null) { List <String> groups = GetUserGroups(config, email); //Verifica os grupos padrões foreach (String dfG in defaultGroups) { if ((package.locked) || (package.temp_locked)) { foreach (String usrG in groups) { try { WebServiceObjectInterface oGrp = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "getGroup", new Object[] { this.loginToken, usrG }); WebServiceObjectInterface tst3 = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "removeUserFromGroup", new Object[] { this.loginToken, oGrp.BaseObject, oUser.BaseObject }); } catch (Exception ex) { processLog.AppendLine("Error on remove user from group '" + usrG + "' " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : "")); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on remove user from group '" + usrG + "' " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : ""), ""); } } } else if (!groups.Exists(g => (g.ToLower() == dfG.ToLower()))) { //Adiciona o grupo padrão try { WebServiceObjectInterface oGrp = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "getGroup", new Object[] { this.loginToken, dfG }); WebServiceObjectInterface tst3 = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "addUserToGroup", new Object[] { this.loginToken, oGrp.BaseObject, oUser.BaseObject }); } catch (Exception ex) { processLog.AppendLine("Error on add user to group '" + dfG + "': " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : "")); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on add user to group '" + dfG + "': " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : ""), ""); } } } NotityChangeUser(this, package.entityId); //Executa as ações do RBAC if ((package.pluginAction != null) && (package.pluginAction.Count > 0)) { foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction) { try { processLog.AppendLine("Role: " + act.roleName + " (" + act.actionType.ToString() + ") " + act.ToString()); switch (act.actionKey.ToLower()) { case "group": if ((act.actionType == PluginActionType.Add) && (!groups.Exists(g => (g == act.actionValue)))) { WebServiceObjectInterface oGrp = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "getGroup", new Object[] { this.loginToken, act.actionValue }); if (oGrp.BaseObject != null) { try { WebServiceObjectInterface tst3 = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "addUserToGroup", new Object[] { this.loginToken, oGrp.BaseObject, oUser.BaseObject }); processLog.AppendLine("User added in group " + act.actionValue + " by role " + act.roleName); } catch { } } else { processLog.AppendLine("Erro adding in group " + act.actionValue + " by role " + act.roleName + ": Group nor found"); Log2(this, PluginLogType.Information, package.entityId, package.identityId, "Erro adding in group " + act.actionValue + " by role " + act.roleName + ": Group nor found", ""); } } else if ((act.actionType == PluginActionType.Remove) && (groups.Exists(g => (g == act.actionValue)))) { WebServiceObjectInterface oGrp = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "getGroup", new Object[] { this.loginToken, act.actionValue }); if (oGrp.BaseObject != null) { try { WebServiceObjectInterface tst3 = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "addUserToGroup", new Object[] { this.loginToken, oGrp.BaseObject, oUser.BaseObject }); processLog.AppendLine("User removed in group " + act.actionValue + " by role " + act.roleName); } catch { } } else { processLog.AppendLine("Erro removing in group " + act.actionValue + " by role " + act.roleName + ": Group nor found"); Log2(this, PluginLogType.Information, package.entityId, package.identityId, "Erro removing in group " + act.actionValue + " by role " + act.roleName + ": Group nor found", ""); } } break; default: processLog.AppendLine("Action not recognized: " + act.actionKey); Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "Action not recognized: " + act.actionKey, ""); break; } } catch (Exception ex) { processLog.AppendLine("Error on execute action (" + act.actionKey + "): " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on execute action (" + act.actionKey + "): " + ex.Message, ""); } } } } } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process deploy: " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : "")); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : ""), ""); } finally { Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString()); processLog.Clear(); processLog = null; } }
public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { if (!CheckInputConfig(config, true, Log)) { return; } String connectionstring = "Data Source=" + config["server"].ToString() + ";Initial Catalog=master;User Id=" + config["username"].ToString() + ";Password='******';"; MSSQLDB db = null; StringBuilder processLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { if (!String.IsNullOrEmpty(package.password)) { processLog.AppendLine("Package contains password"); } else { processLog.AppendLine("Package not contains password"); } db = new MSSQLDB(connectionstring); db.openDB(); LogEvent dbExecLog = new LogEvent(delegate(Object sender, PluginLogType type, String text) { processLog.AppendLine(text); }); db.OnLog += dbExecLog; //Verifica se o registro existe DataTable dtReg = db.ExecuteDataTable("SELECT name AS Login_Name FROM sys.server_principals WHERE TYPE IN ('S') and name = '" + package.login + "'", CommandType.Text, null); if (dtReg == null) { logType = PluginLogType.Error; processLog.AppendLine("Error on select data: " + db.LastError); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on select data: " + db.LastError, ""); return; } //Preenche a tabela de parâmetros com os campos que serão inseridos/atualizados if (dtReg.Rows.Count == 0) { //Não existe, cria String tmpPwd = IAM.Password.RandomPassword.Generate(20); tmpPwd = tmpPwd.Replace("'", ""); tmpPwd = tmpPwd.Replace(".", ""); tmpPwd = tmpPwd.Replace("\\", ""); tmpPwd = tmpPwd.Replace("[", ""); tmpPwd = tmpPwd.Replace("]", ""); if (package.password == "") { processLog.AppendLine("User not found in AD and IAM Password not found in properties list, creating a random password (" + tmpPwd + ")"); } String insert = "CREATE LOGIN [" + package.login + "] WITH PASSWORD=N'" + tmpPwd + "', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF"; StringBuilder tmpText = new StringBuilder(); try { tmpText.AppendLine("ExecuteNonQuery.SQL = " + insert); db.ExecuteNonQuery(insert, CommandType.Text, null); } catch (Exception ex2) { processLog.AppendLine(tmpText.ToString()); throw new Exception("Error adding user", ex2); } finally { tmpText.Clear(); tmpText = null; } NotityChangeUser(this, package.entityId); processLog.AppendLine(""); processLog.AppendLine("User added"); } if (package.password != "") { String insert = "ALTER LOGIN [" + package.login + "] WITH PASSWORD=N'" + package.password + "'"; StringBuilder tmpText = new StringBuilder(); try { tmpText.AppendLine("ExecuteNonQuery.SQL = " + insert); db.ExecuteNonQuery(insert, CommandType.Text, null); } catch (Exception ex2) { String sPs = ""; try { PasswordStrength ps = CheckPasswordStrength(package.password, package.fullName.fullName); sPs += "Length = " + package.password.Length + Environment.NewLine; sPs += "Contains Uppercase? " + ps.HasUpperCase + Environment.NewLine; sPs += "Contains Lowercase? " + ps.HasLowerCase + Environment.NewLine; sPs += "Contains Symbol? " + ps.HasSymbol + Environment.NewLine; sPs += "Contains Number? " + ps.HasDigit + Environment.NewLine; sPs += "Contains part of the name/username? " + ps.HasNamePart + Environment.NewLine; } catch { } Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on set user password, check the password complexity rules", ex2.Message + (ex2.InnerException != null ? " " + ex2.InnerException.Message : "") + Environment.NewLine + sPs); return; } finally { tmpText.Clear(); tmpText = null; } } NotityChangeUser(this, package.entityId); db.OnLog -= dbExecLog; //Executa as ações do RBAC if ((package.pluginAction != null) && (package.pluginAction.Count > 0)) { processLog.AppendLine(""); foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction) { try { switch (act.actionKey.ToLower()) { case "sql": String sql2 = act.actionValue.Replace("{login}", package.login).Replace("{full_name}", package.fullName.fullName); db.ExecuteNonQuery(sql2, CommandType.Text, null); break; default: processLog.AppendLine("Action not recognized: " + act.actionKey); Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "Action not recognized: " + act.actionKey, ""); break; } } catch (Exception ex) { processLog.AppendLine("Error on execute action (" + act.actionKey + "): " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on execute action (" + act.actionKey + "): " + ex.Message, ""); } } } if (package.password != "") { Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User updated with password", ""); } else { Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User updated without password", ""); } } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process deploy: " + ex.Message + (ex.InnerException != null ? " --> " + ex.InnerException.Message : "")); #if DEBUG String debugInfo = JSON.Serialize2(new { package = package, fieldMapping = fieldMapping }); if (package.password != "") { debugInfo = debugInfo.Replace(package.password, "Replaced for user security"); } processLog.AppendLine(debugInfo); #endif Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, processLog.ToString()); } finally { if (db != null) { db.Dispose(); } Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString()); processLog.Clear(); processLog = null; } }
public override void ProcessDelete(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { JSON.DebugMessage dbg = new JSON.DebugMessage(delegate(String data, String debug) { #if DEBUG Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "JSON Debug message: " + data, debug); #endif }); if (!CheckInputConfig(config, true, Log)) { return; } //contactDelete String lastStep = "CheckInputConfig"; if (!CheckInputConfig(config, true, Log)) { return; } StringBuilder processLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { lastStep = "Check info"; String container = package.container; if (String.IsNullOrEmpty(container)) { container = "IAMUsers"; } //Este plugin estava gerando milhares de listas indevidamente devido ao container //Desta forma foi fixado o container como sempre Sendo SafeIDUsers container = "IAMUsers"; String email = ""; String mail_domain = "";//config["mail_domain"].ToString(); if ((config.ContainsKey("mail_domain")) && (!String.IsNullOrEmpty(config["mail_domain"].ToString()))) { mail_domain = config["mail_domain"].ToString(); } //Busca o e-mail nas propriedades específicas deste plugin foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (dt.dataValue.ToLower().IndexOf("@" + mail_domain) > 1) { email = dt.dataValue; } } //Se não encontrou o e-mail testa nas propriedades maracas como ID if ((email == null) || (email == "")) { foreach (PluginConnectorBasePackageData dt in package.ids) { if (dt.dataValue.ToLower().IndexOf("@" + mail_domain) > 1) { email = dt.dataValue; } } } //Se não encontrou o e-mail testa nas propriedades gerais if ((email == null) || (email == "")) { foreach (PluginConnectorBasePackageData dt in package.properties) { if (dt.dataValue.ToLower().IndexOf("@" + mail_domain) > 1) { email = dt.dataValue; } } } //Se não encontrou nenhum e-mail do dominio principal adiciona qualquer outro e-mail if ((email == null) || (email == "")) { foreach (PluginConnectorBasePackageData dt in package.properties) { if (dt.dataValue.ToLower().IndexOf("@") > 1) { email = dt.dataValue; } } } if (email == "") { String jData = ""; try { jData = JSON.Serialize <PluginConnectorBaseDeployPackage>(package); if (package.password != "") { jData = jData.Replace(package.password, "Replaced for user security"); } } catch { } logType = PluginLogType.Error; processLog.AppendLine("IAM Email not found in properties list. " + jData); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Email not found in properties list.", jData); return; } if ((package.fullName == null) || (package.fullName.fullName.Trim() == "")) { String jData = ""; try { jData = JSON.Serialize <PluginConnectorBaseDeployPackage>(package); if (package.password != "") { jData = jData.Replace(package.password, "Replaced for user security"); } } catch { } logType = PluginLogType.Error; processLog.AppendLine("IAM Full Name not found in properties list. " + jData); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Full Name not found in properties list", jData); return; } lastStep = "Auth"; //http://api.emailmanager.com/1.0/?method=authentLogin&domain=<subdomínio>&username=<usuário>&password=<senha> Uri serverUri = new Uri("http://api.emailmanager.com/"); CookieContainer cookie = new CookieContainer(); emLogin[] login = JSON.JsonWebRequest <emLogin[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?method=authentLogin&language=en_US&output=json&domain=" + config["domain"].ToString() + "&username="******"username"].ToString() + "&password="******"password"].ToString()), null, "", null, "GET", cookie, dbg); if ((login == null) || (login.Length == 0)) { logType = PluginLogType.Error; processLog.AppendLine("Login result is empty"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Login result is empty", ""); return; } if (String.IsNullOrEmpty(login[0].apikey)) { logType = PluginLogType.Error; processLog.AppendLine("Login error: " + login[0].message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Login error: " + login[0].message, ""); return; } string apiKey = login[0].apikey; JSON.DebugMessage dbgC = new JSON.DebugMessage(delegate(String data, String debug) { #if DEBUG Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "JSON Debug message: " + data, debug); #endif }); lastStep = "Get User"; //Verifica se o usuário existe String userId = null; emUser[] user = JSON.JsonWebRequest <emUser[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=contacts&email=" + email + "&language=en_US&output=json"), null, "", null, "GET", cookie, dbgC); if ((user != null) && (user.Length > 0) && (!String.IsNullOrEmpty(user[0].id))) { //Encontrou userId = user[0].id; } if (userId == null) { logType = PluginLogType.Error; processLog.AppendLine("User not found"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "User not found", ""); return; } //Atualiza os campos personalizados do usuario emUserCreate[] userUpdate = JSON.JsonWebRequest <emUserCreate[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=contactCancel&cid=" + userId + "&language=en_US&extra_89=teste001&output=json"), null, "", null, "GET", cookie, dbgC); if ((userUpdate != null) && (userUpdate.Length > 0) && (userUpdate[0].code != 0)) { processLog.AppendLine("Error cancelling user info: " + userUpdate[0].message); } processLog.AppendLine("User canceled on Email Manager"); } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process delete (" + lastStep + "): " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process delete: " + ex.Message, "Last step: " + lastStep); } finally { Log2(this, logType, package.entityId, package.identityId, "Delete executed", processLog.ToString()); processLog.Clear(); processLog = null; } }
public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { String lastStep = "CheckInputConfig"; JSON.DebugMessage dbgC = new JSON.DebugMessage(delegate(String data, String debug) { #if DEBUG Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "JSON Debug message: " + data, debug); #endif }); if (!CheckInputConfig(config, true, Log)) { return; } StringBuilder processLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { lastStep = "Check info"; String container = ""; Uri apiUri = GetNcallUriFromConfig(config); if ((package.fullName == null) || (package.fullName.fullName.Trim() == "")) { String jData = ""; try { jData = JSON.Serialize <PluginConnectorBaseDeployPackage>(package); if (package.password != "") { jData = jData.Replace(package.password, "Replaced for user security"); } } catch { } logType = PluginLogType.Error; processLog.AppendLine("IAM Full Name not found in properties list. " + jData); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Full Name not found in properties list", jData); return; } lastStep = "Auth"; //http://api.emailmanager.com/1.0/?method=authentLogin&domain=<subdomínio>&username=<usuário>&password=<senha> Uri serverUri = new Uri(apiUri, "/ncall/controle.php"); CookieContainer cookie = new CookieContainer(); String ret = JSON.TextWebRequest(new Uri(apiUri, "/ncall/controle.php"), "proxacao=login¶ms=" + HttpUtility.UrlEncode("usuario=" + config["username"] + "|senha=" + MD5Checksum(config["password"].ToString())) + "&usuario=" + config["username"] + "&senhaLogin="******"password"].ToString()), "application/x-www-form-urlencoded", null, "POST", cookie, dbgC); //Tenta localizar texto de que o login foi com sucesso if (ret.ToLower().IndexOf("troncomonitor.php") <= 0) { logType = PluginLogType.Error; processLog.AppendLine("Login result is empty"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Login result is empty", ""); return; } String tst = ""; /* * emLogin[] login = JSON.JsonWebRequest<emLogin[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?method=authentLogin&language=en_US&output=json&domain=" + config["domain"].ToString() + "&username="******"username"].ToString() + "&password="******"password"].ToString()), null, "", null, "GET", cookie, dbgC); * * if ((login == null) || (login.Length == 0)) * { * logType = PluginLogType.Error; * processLog.AppendLine("Login result is empty"); * Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Login result is empty", ""); * return; * } * * if (String.IsNullOrEmpty(login[0].apikey)) * { * logType = PluginLogType.Error; * processLog.AppendLine("Login error: " + login[0].message); * Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Login error: " + login[0].message, ""); * return; * } * * string apiKey = login[0].apikey; * * //Lista todas as pastas do sistema * //editionFolders * //Esta parte não foi implementada pois a API não está funcionando * //emailMonitorLogin[] login2 = JSON.JsonWebRequest<emailMonitorLogin[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=editionFolders&parent_id=0&language=en_US&output=json"), null, "", null, "GET", cookie); * * //Cria o 'container', se não houver * //emailMonitorLogin[] login3 = JSON.JsonWebRequest<emailMonitorLogin[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=editionFolderCreate&parent_id=0&name="+ container +"&language=en_US&output=json"), null, "", null, "GET", cookie); * * lastStep = "Get groups"; * * //Lista os grupos para vinculação de 'Role', caso o usuário não esteja em nenhuma role não será adicionado * //groups * * emGroup[] groups = JSON.JsonWebRequest<emGroup[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=groups&folder_id=0&parent_id=0&language=en_US&output=json&limit="+ Int32.MaxValue), null, "", null, "GET", cookie, dbgC); * * if (groups.Length == 1) * { * if (groups[0].id == "") * throw new Exception("Error retriving groups"); * } * * * /* * //Exclui todos os grupos com nome SafeIDUsers * if ((groups != null) && (groups.Length > 0)) * foreach (emGroup g in groups) * if ((!String.IsNullOrEmpty(g.name)) && (g.name.ToLower() == "iamusers") && (Int32.Parse( g.id) > 55)) * { * Object tst = JSON.JsonWebRequest<Object>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=groupDelete&group_id=" + g.id + "&language=en_US&output=json"), null, "", null, "GET", cookie, dbgC); * Console.WriteLine("Deleting " + g.id); * } * / * * String baseGrpId = "0"; * if ((groups != null) && (groups.Length > 0)) * foreach (emGroup g in groups) * if ((!String.IsNullOrEmpty(g.name)) && (g.name.ToLower() == container.ToLower())) * baseGrpId = g.id; * * List<String> dbg = new List<string>(); * if ((groups != null) && (groups.Length > 0)) * foreach (emGroup g in groups) * dbg.Add(g.ToString()); * * * if (baseGrpId == "0") * { * //Cria o grupo Base com o nome do container * emGroupCreate[] grpCreate = JSON.JsonWebRequest<emGroupCreate[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=groupCreate&folder_id=0&parent_id=0&name=" + container + "&description=" + container + "&language=en_US&output=json"), null, "", null, "GET", cookie, dbgC); * if ((grpCreate != null) && (grpCreate.Length > 0) && (!String.IsNullOrEmpty(grpCreate[0].id))) * baseGrpId = grpCreate[0].id; * else * baseGrpId = "0"; * * groups = JSON.JsonWebRequest<emGroup[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=groups&folder_id=0&parent_id=0&language=en_US&output=json&limit=" + Int32.MaxValue), null, "", null, "GET", cookie, dbgC); * } * * dbg = new List<string>(); * if ((groups != null) && (groups.Length > 0)) * foreach (emGroup g in groups) * dbg.Add(g.ToString()); * * * lastStep = "Get User"; * //Verifica se o usuário existe * String userId = null; * emUser[] user = JSON.JsonWebRequest<emUser[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=contacts&email=" + email + "&language=en_US&output=json"), null, "", null, "GET", cookie, dbgC); * if ((user != null) && (user.Length > 0) && (!String.IsNullOrEmpty(user[0].id))) * { * //Encontrou * userId = user[0].id; * * } * else * { * lastStep = "Create User"; * * if ((package.locked) || (package.temp_locked)) * { * logType = PluginLogType.Warning; * processLog.AppendLine("User not found in Mail Manager and user is locked. Accound not created"); * Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "User not found in Mail Manager and user is locked. Accound not created", ""); * return; * } * * //Cria * emUserCreate[] userCreate = JSON.JsonWebRequest<emUserCreate[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=contactCreate&name=" + HttpUtility.UrlEncode(package.fullName.fullName) + "&email=" + email + "&groups_id=" + baseGrpId + "&language=en_US&output=json"), null, "", null, "GET", cookie, dbgC); * if ((userCreate != null) && (userCreate.Length > 0) && (!String.IsNullOrEmpty(userCreate[0].cid))) * userId = userCreate[0].cid; * * processLog.AppendLine("User created on Email Manager"); * * /* * user = JSON.JsonWebRequest<emUser[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=contacts&email=" + email + "&language=en_US&output=json"), null, "", null, "GET", cookie); * if ((user != null) && (user.Length > 0) && (!String.IsNullOrEmpty(user[0].id))) * userId = user[0].id;* / * } * * if (userId == null) * { * logType = PluginLogType.Error; * processLog.AppendLine("Unknow erro on add user"); * Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Unknow erro on add user", ""); * return; * } * * //Atualiza os campos personalizados do usuario * Dictionary<String, String> extraData = new Dictionary<String, String>(); * * foreach (PluginConnectorBaseDeployPackageMapping m in fieldMapping) * if ((m.dataName.ToLower().IndexOf("extra_") != -1) && !extraData.ContainsKey(m.dataName.ToLower())) * extraData.Add(m.dataName.ToLower(), null); * * foreach (PluginConnectorBasePackageData dt in package.importsPluginData) * if (extraData.ContainsKey(dt.dataName.ToLower()) && extraData[dt.dataName.ToLower()] == null) * { * extraData[dt.dataName.ToLower()] = dt.dataValue; #if DEBUG * processLog.AppendLine("1. extraData[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif * } * * foreach (PluginConnectorBasePackageData dt in package.pluginData) * if (extraData.ContainsKey(dt.dataName.ToLower()) && extraData[dt.dataName.ToLower()] == null) * { * extraData[dt.dataName.ToLower()] = dt.dataValue; #if DEBUG * processLog.AppendLine("2. extraData[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif * } * * foreach (PluginConnectorBasePackageData dt in package.properties) * if (extraData.ContainsKey(dt.dataName.ToLower()) && extraData[dt.dataName.ToLower()] == null) * { * extraData[dt.dataName.ToLower()] = dt.dataValue; #if DEBUG * processLog.AppendLine("3. extraData[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif * } * * * String userExtraData = ""; * foreach (String k in extraData.Keys) * { * * if (userExtraData != "") userExtraData += "&"; * userExtraData += k + "=" + HttpUtility.UrlEncode(extraData[k]); * #if DEBUG * processLog.AppendLine("4. extraData[" + k + "] = " + extraData[k]); #endif * } * * //emUserCreate[] userUpdate = JSON.JsonWebRequest<emUserCreate[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=contactUpdate&cid=" + userId + "&name=" + HttpUtility.UrlEncode(package.fullName.fullName) + "&email=" + email + "&groups_id=" + baseGrpId + "&language=en_US&" + userExtraData + "&output=json"), null, "", null, "GET", cookie, dbgC); * * /* * //Desabilitado este ponto de atualiza;c'ao e transferido para uma unica atualizacao final, juntamente com os grupos * emUserCreate[] userUpdate = JSON.JsonWebRequest<emUserCreate[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=contactUpdate&cid=" + userId + "&name=" + HttpUtility.UrlEncode(package.fullName.fullName) + "&email=" + email + "&language=en_US&" + userExtraData + "&output=json"), null, "", null, "GET", cookie, dbgC); * if ((userUpdate != null) && (userUpdate.Length > 0) && (userUpdate[0].code != 0)) * { * processLog.AppendLine("Error updating user info: " + userUpdate[0].message); * } * * processLog.AppendLine("User updated on Email Manager");* / * * * lastStep = "Check groups/roles"; * List<String> grpIds = new List<String>(); * List<String> grpIdsRemove = new List<String>(); * grpIds.Add(baseGrpId); * Boolean rebuildGrpList = false; * * //Busca os grupos que este usuário fará parte * if ((package.pluginAction != null) && (package.pluginAction.Count > 0)) * { * foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction) * try * { * processLog.AppendLine("Role: " + act.roleName + " (" + act.actionType.ToString() + ") " + act.ToString()); * * switch (act.actionKey.ToLower()) * { * case "group": * if (act.actionType == PluginActionType.Add) * { * String grpAddId = null; * if ((groups != null) && (groups.Length > 0)) * foreach (emGroup g in groups) * if ((!String.IsNullOrEmpty(g.name)) && (g.name.ToLower() == act.actionValue.ToLower())) * { * grpAddId = g.id; * grpIds.Add(grpAddId); * } * * if (grpAddId == null) * { * emGroupCreate[] grpCreate = JSON.JsonWebRequest<emGroupCreate[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=groupCreate&folder_id=0&parent_id=0&name=" + act.actionValue + "&description=" + act.actionValue + "&language=en_US&output=json"), null, "", null, "GET", cookie, dbgC); * if ((grpCreate != null) && (grpCreate.Length > 0) && (!String.IsNullOrEmpty(grpCreate[0].id))) * { * rebuildGrpList = true; * grpAddId = grpCreate[0].id; * grpIds.Add(grpAddId); * processLog.AppendLine("User added in group " + act.actionValue + " by role " + act.roleName); * } * } * else * { * processLog.AppendLine("User added in group " + act.actionValue + " by role " + act.roleName); * } * * } * else if (act.actionType == PluginActionType.Remove) * { * if ((groups != null) && (groups.Length > 0)) * foreach (emGroup g in groups) * if ((!String.IsNullOrEmpty(g.name)) && (g.name.ToLower() == act.actionValue.ToLower())) * { * grpIdsRemove.Add(g.id); * processLog.AppendLine("User removed from group " + act.actionValue + " by role " + act.roleName); * } * } * break; * * default: * processLog.AppendLine("Action not recognized: " + act.actionKey); * break; * } * } * catch (Exception ex) * { * processLog.AppendLine("Error on execute action (" + act.actionKey + "): " + ex.Message); * } * } * * * //Remove o usuário dos grupos criados erroneamente * //Remove de todos os grupos iniciados com "\" ou com o mesmo nome do container * /* * if ((!String.IsNullOrEmpty(package.container)) && (groups != null) && (groups.Length > 0)) * foreach (emGroup g in groups) * if ((!String.IsNullOrEmpty(g.name)) && ((g.name.ToLower() == package.container.ToLower()) || (g.name.ToLower().Substring(0, 1) == "\\"))) * { * grpIdsRemove.Add(g.id); * processLog.AppendLine("User removed from group " + package.container + " by container rule"); * } * / * * grpIds.Remove("0");//Remove o grupo "zero" pois a API não o aceita * * lastStep = "Rebuild groups"; * if (rebuildGrpList) //Como alguns grupos fram criados, recarrega a listagem de grupos * groups = JSON.JsonWebRequest<emGroup[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=groups&folder_id=0&parent_id=0&language=en_US&output=json&limit=" + Int32.MaxValue), null, "", null, "GET", cookie, dbgC); * * * lastStep = "Check final groups"; * //Checa a listagem de grupos deste usuário, remove somente os que foram explicitamente definidos pelo IM * //Mantendo os grupos que foram adicionados pela console do mail manager * List<String> finalGrps = new List<String>(); * finalGrps.AddRange(grpIds); * * emUserGroup[] userGroups = JSON.JsonWebRequest<emUserGroup[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=contactGroups&cid=" + userId + "&language=en_US&output=json"), null, "", null, "GET", cookie, dbgC); * if ((userGroups != null) && (userGroups.Length > 0)) * foreach (emUserGroup g in userGroups) * if ((!finalGrps.Contains(g.group_id)) && (!grpIdsRemove.Contains(g.group_id))) * finalGrps.Add(g.group_id); * * if (!finalGrps.Contains(baseGrpId))//Mantém o grupo base * finalGrps.Add(baseGrpId); * * finalGrps.Remove("0");//Remove o grupo "zero" pois a API não o aceita * * lastStep = "Update user info"; * * //Atualiza as informações do usuário * //A atualização somente dos grupos * //JSON.JsonWebRequest<emUserCreate[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=contactUpdate&cid=" + userId + "&groups_id=" + String.Join(",", finalGrps) + "&language=en_US&output=json"), null, "", null, "GET", cookie, dbgC); * * emUserCreate[] userUpdate = JSON.JsonWebRequest<emUserCreate[]>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/1.0/?apikey=" + apiKey + "&method=contactUpdate&cid=" + userId + "&name=" + HttpUtility.UrlEncode(package.fullName.fullName) + "&email=" + email + "&groups_id=" + String.Join(",", finalGrps) + "&language=en_US&" + userExtraData + "&output=json"), null, "", null, "GET", cookie, dbgC); * if ((userUpdate != null) && (userUpdate.Length > 0) && (userUpdate[0].code != 0)) * { * processLog.AppendLine("Error updating user info: " + userUpdate[0].message); * } * else * { * processLog.AppendLine("User updated"); * } * * try * { * lastStep = "Groups info"; * * //Texto informativo com grupos do usuário * List<String> grpName = new List<String>(); * if ((groups != null) && (groups.Length > 0)) * foreach (emGroup g in groups) * if (finalGrps.Contains(g.id) && (!grpName.Contains(g.name))) * grpName.Add(g.name); * * processLog.AppendLine("User groups: " + (grpName.Count == 0 ? "None" : String.Join(", ", grpName))); * * grpName.Clear(); * grpName = null; * * } * catch { } * * try * { * * lastStep = "End"; * * finalGrps.Clear(); * finalGrps = null; * * grpIds.Clear(); * grpIds = null; * * Array.Clear(groups, 0, groups.Length); * groups = null; * * Array.Clear(userGroups, 0, userGroups.Length); * userGroups = null; * } * catch { }*/ } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process deploy (" + lastStep + "): " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, "Last step: " + lastStep); } finally { Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString()); processLog.Clear(); processLog = null; } }
public override void ProcessImportAfterDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { String lastStep = "CheckInputConfig"; if (!CheckInputConfig(config, true, Log)) { return; } StringBuilder processLog = new StringBuilder(); StringBuilder debugLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; SeniorAPI api = new SeniorAPI(config["username"].ToString(), config["password"].ToString(), config["numemp"].ToString(), new Uri(config["server_uri"].ToString())); XML.DebugMessage dbgC = new XML.DebugMessage(delegate(String data, String debug) { debugLog.AppendLine("######"); debugLog.AppendLine("## JSON Debug message: " + data); debugLog.AppendLine(debug); }); try { String importID = "ImpAfDep-" + Guid.NewGuid().ToString(); lastStep = "Checa CPF no pacote"; String cpf = ""; //Busca o e-mail nas propriedades específicas desto usuário foreach (PluginConnectorBasePackageData dt in package.entiyData) { if (dt.dataName.ToLower() == "numcpf" && !String.IsNullOrEmpty(dt.dataValue.ToLower())) { cpf = dt.dataValue; } } //Busca o e-mail nas propriedades específicas deste plugin if ((cpf == null) || (cpf == "")) { foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (dt.dataName.ToLower() == "numcpf" && !String.IsNullOrEmpty(dt.dataValue.ToLower())) { cpf = dt.dataValue; } } } //Se não encontrou o e-mail testa nas propriedades maracas como ID if ((cpf == null) || (cpf == "")) { foreach (PluginConnectorBasePackageData dt in package.ids) { if (dt.dataName.ToLower() == "numcpf" && !String.IsNullOrEmpty(dt.dataValue.ToLower())) { cpf = dt.dataValue; } } } //Se não encontrou o e-mail testa nas propriedades gerais if ((cpf == null) || (cpf == "")) { foreach (PluginConnectorBasePackageData dt in package.properties) { if (dt.dataName.ToLower() == "numcpf" && !String.IsNullOrEmpty(dt.dataValue.ToLower())) { cpf = dt.dataValue; } } } #if DEBUG try { String jData = JSON.Serialize <PluginConnectorBaseDeployPackage>(package); if (package.password != "") { jData = jData.Replace(package.password, "Replaced for user security"); } Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "Package data", jData); } catch { } #endif if (cpf == "") { String jData = ""; try { jData = JSON.Serialize <PluginConnectorBaseDeployPackage>(package); if (package.password != "") { jData = jData.Replace(package.password, "Replaced for user security"); } } catch { } logType = PluginLogType.Error; processLog.AppendLine("CPF (numCpf) not found in properties list. " + jData); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "CPF (numCpf) not found in properties list", jData); return; } lastStep = "Resgata informações do colaborador"; List <Dictionary <String, String> > users = api.GetUserData(cpf, dbgC); if (users == null) { throw new Exception("User data is empty"); } foreach (Dictionary <String, String> u in users) { String cNumCad = "";//Data de admissao if (u.ContainsKey("numCad")) { cNumCad = u["numCad"]; } else if (u.ContainsKey("numcad")) { cNumCad = u["numcad"]; } PluginConnectorBaseImportPackageUser packageImp = new PluginConnectorBaseImportPackageUser(importID); try { foreach (String key in u.Keys) { if (key.ToLower() == "numcpf") { packageImp.AddProperty(key, u[key].Replace("-", "").Replace(".", "").Replace(" ", ""), "string"); } else { packageImp.AddProperty(key, u[key], "string"); } } Dictionary <String, Dictionary <String, String> > cData = GetComplementatyData(api, u, dbgC); if (cData.ContainsKey(cNumCad)) { foreach (String key in cData[cNumCad].Keys) { if (key.ToLower() == "numcpf") { packageImp.AddProperty(key, cData[cNumCad][key].Replace("-", "").Replace(".", "").Replace(" ", ""), "string"); } else { packageImp.AddProperty(key, cData[cNumCad][key], "string"); } } } } catch (Exception ex2) { processLog.AppendLine("Error: " + ex2.Message); } finally { processLog.AppendLine("Import (after deploy) package generated:"); processLog.AppendLine("\tImport ID: " + importID); processLog.AppendLine("\tPackage ID: " + packageImp.pkgId); processLog.AppendLine(""); processLog.AppendLine("Package data:"); processLog.AppendLine(JSON.Serialize(packageImp)); ImportPackageUser(packageImp); } } } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error processing import (" + lastStep + "): " + ex.Message); if (ex is SafeTrend.Xml.ResultEmptyException) { Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Network erro or API lock error importing user data", ex.Message + Environment.NewLine + debugLog.ToString()); } try { Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error processing import after deploy: " + ex.Message, debugLog.ToString()); } catch { Log2(this, PluginLogType.Error, 0, 0, "Error processing import after deploy: " + ex.Message, debugLog.ToString()); } } finally { #if DEBUG processLog.AppendLine(debugLog.ToString()); Log2(this, PluginLogType.Debug, 0, 0, "Import debug log", debugLog.ToString()); Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "Import debug log", debugLog.ToString()); #else if (logType != PluginLogType.Information) { processLog.AppendLine(debugLog.ToString()); } #endif Log2(this, logType, package.entityId, package.identityId, "Import executed", processLog.ToString()); processLog.Clear(); processLog = null; debugLog.Clear(); debugLog = null; } }
public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { String lastStep = "CheckInputConfig"; if (!CheckInputConfig(config, true, Log)) { return; } StringBuilder processLog = new StringBuilder(); StringBuilder debugLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; SeniorAPI api = new SeniorAPI(config["username"].ToString(), config["password"].ToString(), config["numemp"].ToString(), new Uri(config["server_uri"].ToString())); XML.DebugMessage dbgC = new XML.DebugMessage(delegate(String data, String debug) { debugLog.AppendLine("######"); debugLog.AppendLine("## [" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] JSON Debug message: " + data); debugLog.AppendLine(debug); }); try { lastStep = "Resgata os colaboradores contratados nos últimos 365 dias"; List <Dictionary <String, String> > users = api.GetUsers(dbgC); if (users == null) { throw new Exception("User data is empty"); } foreach (Dictionary <String, String> u in users) { StringBuilder userDebugLog = new StringBuilder(); //userDebugLog.AppendLine(debugLog.ToString()); try { userDebugLog.AppendLine("######"); userDebugLog.AppendLine("### User Data"); userDebugLog.AppendLine(JSON.Serialize <Dictionary <String, String> >(u)); } catch { } userDebugLog.AppendLine(""); String cNumCad = "";//Data de admissao if (u.ContainsKey("numCad")) { cNumCad = u["numCad"]; } else if (u.ContainsKey("numcad")) { cNumCad = u["numcad"]; } PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId); userDebugLog.AppendLine("######"); userDebugLog.AppendLine("### Package id: " + package.pkgId); foreach (String key in u.Keys) { if (key.ToLower() == "numcpf") { package.AddProperty(key, u[key].Replace("-", "").Replace(".", "").Replace(" ", ""), "string"); } else { package.AddProperty(key, u[key], "string"); } } userDebugLog.AppendLine(""); XML.DebugMessage userDbgC = new XML.DebugMessage(delegate(String data, String debug) { userDebugLog.AppendLine("######"); userDebugLog.AppendLine("## [" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] JSON Debug message: " + data); userDebugLog.AppendLine(debug); }); Dictionary <String, Dictionary <String, String> > cData = GetComplementatyData(api, u, userDbgC); if (cData.ContainsKey(cNumCad)) { foreach (String key in cData[cNumCad].Keys) { if (key.ToLower() == "numcpf") { package.AddProperty(key, cData[cNumCad][key].Replace("-", "").Replace(".", "").Replace(" ", ""), "string"); } else { package.AddProperty(key, cData[cNumCad][key], "string"); } } } #if DEBUG Log2(this, PluginLogType.Debug, 0, 0, "Import debug log for pachage " + package.pkgId, userDebugLog.ToString()); #endif ImportPackageUser(package); } } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process import (" + lastStep + "): " + ex.Message); if (ex is SafeTrend.Xml.ResultEmptyException) { Log2(this, PluginLogType.Error, 0, 0, "Network erro or API lock error importing user data", ex.Message + Environment.NewLine + "Last step: " + lastStep); } else { Log2(this, PluginLogType.Error, 0, 0, "Error on process import: " + ex.Message, "Last step: " + lastStep); } } finally { #if DEBUG Log2(this, PluginLogType.Debug, 0, 0, "Import debug log", debugLog.ToString()); #endif if (logType != PluginLogType.Information) { processLog.AppendLine(debugLog.ToString()); } Log2(this, logType, 0, 0, "Import executed", processLog.ToString()); processLog.Clear(); processLog = null; debugLog.Clear(); debugLog = null; } }
public void DebugLog(object sender, PluginLogType type, long entityId, long identityId, string text, string additionalData) { #if DEBUG Log2(sender, type, entityId, identityId, text, additionalData); #endif }
public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { if (!CheckInputConfig(config, true, Log)) { return; } StringBuilder processLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { Uri serverUri = new Uri(config["server_uri"].ToString()); CookieContainer cookie = new CookieContainer(); cPanelLogin cPlogin = JSON.JsonWebRequest <cPanelLogin>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/login/?login_only=1"), "user="******"username"].ToString() + "&pass="******"password"].ToString(), "application/x-www-form-urlencoded", null, "POST", cookie); if (cPlogin.status != 1) { throw new Exception("error on login: "******"username"].ToString() + ":" + config["password"].ToString(); authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); Dictionary <string, string> headers = new Dictionary <string, string>(); headers.Add("Authorization", "Basic " + authInfo); //Lista as zonas DNS para verificar se os e-mails a serem importados fazem parte das zonas disponíveis //Object accounts = JSON.JsonWebRequest<Object>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + login.security_token + "/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_func=listzones&cpanel_jsonapi_module=Dns"), "", "application/x-www-form-urlencoded", headers, "GET"); /*if (accounts.cpanelresult == null) * { * Log(this, PluginLogType.Error, "Unexpected erro on get cPannel user list"); * } * * if (accounts.cpanelresult.error != null) * { * Log(this, PluginLogType.Error, "Error on get cPannel users list: " + accounts.cpanelresult.error); * return; * } * * * foreach (cPannelResultUserData u in accounts.cpanelresult.data) * { * * } */ String login = package.login; String email = package.login; String container = package.container; foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (dt.dataName.ToLower() == "login") { login = dt.dataValue; } else if (dt.dataName.ToLower() == "email") { email = dt.dataValue; } } if (login == "") { login = package.login; } if (login == "") { logType = PluginLogType.Error; processLog.AppendLine("IAM Login not found in properties list"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Login not found in properties list", ""); return; } if (email == "") { logType = PluginLogType.Error; processLog.AppendLine("IAM E-mail not found in properties list"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM E-mail not found in properties list", ""); return; } if (container == "") { container = "IAMUsers"; } cPanelResultBase accounts = JSON.JsonWebRequest <cPanelResultBase>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + cPlogin.security_token + "/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_func=listpopswithdisk&cpanel_jsonapi_module=Email&api2_paginate=1&api2_paginate_size=100000&api2_paginate_start=1&api2_sort=1&api2_sort_column=user&api2_sort_method=alphabet&api2_sort_reverse=0&api2_filter=1&api2_filter_type=contains&api2_filter_column=email&api2_filter_term=" + HttpUtility.UrlEncode(email)), "", "application/x-www-form-urlencoded", headers, "GET"); if (accounts.cpanelresult == null) { logType = PluginLogType.Error; processLog.AppendLine("Unexpected error on get cPannel user list"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Unexpected error on get cPannel user list", ""); return; } if (accounts.cpanelresult.error != null) { logType = PluginLogType.Error; processLog.AppendLine("Error on get cPannel users list: " + accounts.cpanelresult.error); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on get cPannel users list: " + accounts.cpanelresult.error, ""); return; } if (accounts.cpanelresult.data.Count == 0) { if (package.password == "") { package.password = IAM.Password.RandomPassword.Generate(16); processLog.AppendLine("User not found in AD and IAM Password not found in properties list, creating a random password (" + package.password + ")"); } if ((package.locked) || (package.temp_locked)) { //O cPannel não permite o bloqueio da conta, a forma encontrada de bloquea-la é trocando a senha package.password = IAM.Password.RandomPassword.Generate(16); processLog.AppendLine("User locked, password temporarily changed to a random password " + package.password); } String[] maisParts = email.Split("@".ToCharArray(), 2); cPanelResultBase retNewUser = JSON.JsonWebRequest <cPanelResultBase>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + cPlogin.security_token + "/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_module=Email&cpanel_jsonapi_func=addpop&email=" + maisParts[0] + "&password="******""a=250&domain=" + maisParts[1]), "", "application/x-www-form-urlencoded", headers, "GET"); if (retNewUser.cpanelresult == null) { logType = PluginLogType.Error; processLog.AppendLine("Unexpected error on add user on cPannel"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Unexpected error on add user on cPannel", ""); return; } if (retNewUser.cpanelresult.error != null) { logType = PluginLogType.Error; processLog.AppendLine("Error on add user on cPannel: " + retNewUser.cpanelresult.error); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on add user on cPannel: " + retNewUser.cpanelresult.error, ""); return; } if (retNewUser.cpanelresult.data.Count == 0) { logType = PluginLogType.Error; processLog.AppendLine("Unexpected error on add user on cPannel"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Unexpected error on add user on cPannel", ""); return; } if (retNewUser.cpanelresult.data[0].result != "1") { logType = PluginLogType.Error; processLog.AppendLine("Error on add user on cPannel: " + retNewUser.cpanelresult.data[0].reason); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on add user on cPannel: " + retNewUser.cpanelresult.data[0].reason, ""); return; } processLog.AppendLine("User added"); } else { //Usuário antigo, somente atualiza //cPannelResultData userData = accounts.cpanelresult.data[0]; if ((package.locked) || (package.temp_locked)) { //O cPannel não permite o bloqueio da conta, a forma encontrada de bloquea-la é trocando a senha package.password = IAM.Password.RandomPassword.Generate(16); processLog.AppendLine("User locked, password temporarily changed to a random password " + package.password); } if (!String.IsNullOrWhiteSpace(package.password)) { String[] maisParts = email.Split("@".ToCharArray(), 2); cPanelResultBase changePwd = JSON.JsonWebRequest <cPanelResultBase>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + cPlogin.security_token + "/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_module=Email&cpanel_jsonapi_func=passwdpop&email=" + maisParts[0] + "&domain=" + maisParts[1] + "&password="******"", "application/x-www-form-urlencoded", headers, "GET"); if (changePwd.cpanelresult == null) { logType = PluginLogType.Error; processLog.AppendLine("Unexpected error on add user on cPannel"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Unexpected error on add user on cPannel", ""); return; } if (changePwd.cpanelresult.error != null) { logType = PluginLogType.Error; processLog.AppendLine("Error on add user on cPannel: " + changePwd.cpanelresult.error); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on add user on cPannel: " + changePwd.cpanelresult.error, ""); return; } if (changePwd.cpanelresult.data.Count == 0) { logType = PluginLogType.Error; processLog.AppendLine("Unexpected error on add user on cPannel"); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Unexpected error on add user on cPannel", ""); return; } if (changePwd.cpanelresult.data[0].result != "1") { logType = PluginLogType.Error; processLog.AppendLine("Error on add user on cPannel: " + changePwd.cpanelresult.data[0].reason); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on add user on cPannel: " + changePwd.cpanelresult.data[0].reason, ""); return; } } NotityChangeUser(this, package.entityId); if (!String.IsNullOrWhiteSpace(package.password)) { processLog.AppendLine("User updated with password"); } else { processLog.AppendLine("User updated without password"); } } processLog.AppendLine("User locked? " + (package.locked ? "true" : "false")); } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process deploy: " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, ""); } finally { Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString()); processLog.Clear(); processLog = null; } }
public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { if (!CheckInputConfig(config, true, Log)) { return; } String server = config["server"].ToString(); String username = config["username"].ToString(); String password = config["password"].ToString(); StringBuilder processLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(server, username, password); connectionInfo.Timeout = new TimeSpan(0, 1, 0); using (SshClient client = new SshClient(connectionInfo)) { try { client.Connect(); } catch (Exception ex) { throw new Exception("Erro on connect SSH", ex); } String prefix = "echo '" + config["password"].ToString() + "' | sudo "; if (config.ContainsKey("use_prefix")) { try { Boolean up = Boolean.Parse(config["use_prefix"].ToString()); if (!up) { prefix = ""; } } catch { } } List <UserData> users = GetList(client, config, package.login); UserData selectedUser = null; foreach (UserData u in users) { if (u.Username.ToLower() == package.login.ToLower()) { selectedUser = u; } } if (selectedUser != null) { //Usuário existente } else { //Não existe, cria //useradd -G {group-name} username //Cria grupo genérico para o IM SshCommand grpAdd = client.RunCommand("groupadd IAMUsers "); if (grpAdd.ExitStatus != 0) { if (grpAdd.Error.ToLower().IndexOf("already exists") == -1) { logType = PluginLogType.Error; processLog.AppendLine("Error creating IAMUsers group: " + grpAdd.Error.Trim("\r\n".ToCharArray())); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error creating IAMUsers group", grpAdd.Error.Trim("\r\n".ToCharArray())); return; } } SshCommand cmdAdd = client.RunCommand("useradd -G IAMUsers " + package.login); if (cmdAdd.ExitStatus != 0) { logType = PluginLogType.Error; processLog.AppendLine("Error creating users: " + cmdAdd.Error.Trim("\r\n".ToCharArray())); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error creating users", cmdAdd.Error.Trim("\r\n".ToCharArray())); return; } processLog.AppendLine("User added"); } if (package.password != "") { String md5Pwd = ""; using (MD5 hAlg = MD5.Create()) md5Pwd = ComputeHash(hAlg, package.password); SshCommand cmdChangePwd = client.RunCommand("echo '" + package.login + ":" + package.password + "' | chpasswd"); if (cmdChangePwd.ExitStatus != 0) { logType = PluginLogType.Error; processLog.AppendLine("Error on set user password, check the password complexity rules"); processLog.AppendLine(cmdChangePwd.Error.Trim("\r\n".ToCharArray())); String sPs = ""; try { PasswordStrength ps = CheckPasswordStrength(package.password, package.fullName.fullName); sPs += "Length = " + package.password.Length + Environment.NewLine; sPs += "Contains Uppercase? " + ps.HasUpperCase + Environment.NewLine; sPs += "Contains Lowercase? " + ps.HasLowerCase + Environment.NewLine; sPs += "Contains Symbol? " + ps.HasSymbol + Environment.NewLine; sPs += "Contains Number? " + ps.HasDigit + Environment.NewLine; sPs += "Contains part of the name/username? " + ps.HasNamePart + Environment.NewLine; processLog.AppendLine(sPs); } catch { } Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on set user password, check the password complexity rules", cmdChangePwd.Error.Trim("\r\n".ToCharArray()) + Environment.NewLine + sPs); return; } } //Lock and unlock account //usermod -L //usermod -U processLog.AppendLine("User locked? " + (package.locked || package.temp_locked ? "true" : "false")); SshCommand userLock = client.RunCommand("usermod " + (package.locked || package.temp_locked ? "-L " : "-U ") + package.login); if (userLock.ExitStatus != 0) { logType = PluginLogType.Error; processLog.AppendLine("Error " + (package.locked || package.temp_locked ? "locking" : "unlocking") + " user: "******"\r\n".ToCharArray())); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error " + (package.locked || package.temp_locked ? "locking" : "unlocking") + " user", userLock.Error.Trim("\r\n".ToCharArray())); return; } //Executa as ações do RBAC if ((package.pluginAction != null) && (package.pluginAction.Count > 0)) { List <GroupData> groups = GetUserGroups(client, config); foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction) { try { processLog.AppendLine("Role: " + act.roleName + " (" + act.actionType.ToString() + ") " + act.ToString()); switch (act.actionKey.ToLower()) { case "group": GroupData findGroup = groups.Find(g => (g.Groupname == act.actionValue)); GroupData findUserInGroup = groups.Find(g => (g.Groupname == act.actionValue && g.Users.Contains(package.login))); if ((act.actionType == PluginActionType.Add) && (findUserInGroup == null)) { if (findGroup == null) { //Not found, add group SshCommand grpAdd = client.RunCommand("groupadd " + act.actionValue); if (grpAdd.ExitStatus != 0) { if (grpAdd.Error.ToLower().IndexOf("already exists") == -1) { logType = PluginLogType.Error; processLog.AppendLine("Error creating " + act.actionValue + " group: " + grpAdd.Error.Trim("\r\n".ToCharArray())); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error creating " + act.actionValue + " group", grpAdd.Error.Trim("\r\n".ToCharArray())); continue; } } } SshCommand userGrpAdd = client.RunCommand("usermod -a -G " + act.actionValue + " " + package.login); if (userGrpAdd.ExitStatus != 0) { logType = PluginLogType.Error; processLog.AppendLine("Error adding user on group " + act.actionValue + ": " + userGrpAdd.Error.Trim("\r\n".ToCharArray())); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error adding user on group " + act.actionValue, userGrpAdd.Error.Trim("\r\n".ToCharArray())); continue; } else { processLog.AppendLine("User added in group " + act.actionValue + " by role " + act.roleName); } } else if ((act.actionType == PluginActionType.Remove) && (findUserInGroup != null)) { SshCommand userGrpDel = client.RunCommand("gpasswd -d " + package.login + " " + act.actionValue); if (userGrpDel.ExitStatus != 0) { logType = PluginLogType.Error; processLog.AppendLine("Error removing user on group " + act.actionValue + ": " + userGrpDel.Error.Trim("\r\n".ToCharArray())); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error removing user on group " + act.actionValue, userGrpDel.Error.Trim("\r\n".ToCharArray())); continue; } else { processLog.AppendLine("User removed from group " + act.actionValue + " by role " + act.roleName); } } break; default: processLog.AppendLine("Action not recognized: " + act.actionKey); break; } } catch (Exception ex) { processLog.AppendLine("Error on execute action (" + act.actionKey + "): " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on execute action (" + act.actionKey + "): " + ex.Message, ""); } } } client.Disconnect(); NotityChangeUser(this, package.entityId); if (package.password != "") { processLog.AppendLine("User updated with password"); } else { processLog.AppendLine("User updated without password"); } } } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process deploy: " + ex.Message); Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, ""); } finally { Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString()); processLog.Clear(); processLog = null; } }
public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping) { if (!CheckInputConfig(config, true, Log)) { return; } DirectoryInfo importDir = null;; try { importDir = new DirectoryInfo(Path.Combine(config["import_folder"].ToString(), "out")); if (!importDir.Exists) { importDir.Create(); } } catch (Exception ex) { Log2(this, PluginLogType.Error, 0, 0, "Erro ao criar o diretório de importação (" + config["import_folder"].ToString() + "\\Out\\)", ex.Message); return; } FileInfo f = new FileInfo(Path.Combine(importDir.FullName, "export" + DateTime.Now.ToString("yyyyMMddHHmmss-ffffff") + ".xlsx")); if (!f.Directory.Exists) { f.Directory.Create(); } String table = "Export " + DateTime.Now.ToString("HHmmss"); String lock_column = (config.ContainsKey("lock_column") ? config["lock_column"].ToString().ToLower() : null); String locked_value = (config.ContainsKey("locked_value") ? config["locked_value"].ToString().ToLower() : null); String unlocked_value = (config.ContainsKey("unlocked_value") ? config["unlocked_value"].ToString().ToLower() : null); OdbcDB db = null; StringBuilder processLog = new StringBuilder(); PluginLogType logType = PluginLogType.Information; try { List <String> columnNames = new List <String>(); foreach (PluginConnectorBaseDeployPackageMapping m in fieldMapping) { if (!columnNames.Contains(m.dataName)) { columnNames.Add(m.dataName); } } if ((!String.IsNullOrEmpty(lock_column)) && (!columnNames.Contains(lock_column))) { columnNames.Add(lock_column); } db = new OdbcDB(f); db.createAndOpenDB(table, columnNames); List <String> prop = new List <String>(); String login = package.login; //Resgata a restutura da tabela de destino DataTable dtInsertSchema = db.GetSchema(table); table = dtInsertSchema.TableName; //Monta o where OleDbParameterCollection par = OdbcDB.GetSqlParameterObject(); //Monta todos os campos que serão inseridos/atualizados Dictionary <String, String> data = new Dictionary <String, String>(); foreach (DataColumn dc in dtInsertSchema.Columns) { if (!data.ContainsKey(dc.ColumnName.ToLower())) { data.Add(dc.ColumnName.ToLower(), null); } } if (data.ContainsKey("locked")) { data["locked"] = (package.locked || package.temp_locked ? "1" : "0"); } DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "lock_column = " + (String.IsNullOrEmpty(lock_column) ? "empty" : lock_column), ""); DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "locked_value = " + (String.IsNullOrEmpty(locked_value) ? "empty" : locked_value), ""); DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "unlocked_value = " + (String.IsNullOrEmpty(unlocked_value) ? "empty" : unlocked_value), ""); if ((lock_column != null) && (data.ContainsKey(lock_column))) { if ((package.locked || package.temp_locked) && (!String.IsNullOrEmpty(locked_value))) { data[lock_column] = locked_value; } else if ((!package.locked && !package.temp_locked) && (!String.IsNullOrEmpty(unlocked_value))) { data[lock_column] = unlocked_value; } else { data[lock_column] = (package.locked || package.temp_locked ? "1" : "0"); } DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "data[lock_column] = " + data[lock_column], ""); } String password_column = ""; foreach (PluginConnectorBaseDeployPackageMapping m in fieldMapping) { if (m.isPassword && data.ContainsKey(m.dataName)) { data[m.dataName] = package.password; password_column = m.dataName; } else if (m.isLogin && data.ContainsKey(m.dataName)) { data[m.dataName] = package.login; } else if (m.isName && data.ContainsKey(m.dataName)) { data[m.dataName] = package.fullName.fullName; } } /*if (login_column != null && data.ContainsKey(login_column)) * data[login_column] = package.login; * * if (password_column != null && data.ContainsKey(password_column)) * data[password_column] = package.password; * * if (name_column != null && data.ContainsKey(name_column)) * data[name_column] = package.fullName.fullName;*/ foreach (PluginConnectorBasePackageData dt in package.importsPluginData) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "1. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("1. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } foreach (PluginConnectorBasePackageData dt in package.pluginData) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "2. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("2. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } foreach (PluginConnectorBasePackageData dt in package.properties) { if (data.ContainsKey(dt.dataName.ToLower()) && data[dt.dataName.ToLower()] == null) { data[dt.dataName.ToLower()] = dt.dataValue; //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "3. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue, ""); #if DEBUG processLog.AppendLine("3. data[" + dt.dataName.ToLower() + "] = " + dt.dataValue); #endif } } foreach (String k in data.Keys) { //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "4. data[" + k + "] = " + data[k], ""); #if DEBUG processLog.AppendLine("4. data[" + k + "] = " + data[k]); #endif } LogEvent dbExecLog = new LogEvent(delegate(Object sender, PluginLogType type, String text) { processLog.AppendLine(text); }); //Não existe, cria if ((data.ContainsKey(password_column)) && (package.password == "")) { package.password = IAM.Password.RandomPassword.Generate(16); data[password_column] = package.password; processLog.AppendLine("User not found in AD and IAM Password not found in properties list, creating a random password (" + package.password + ")"); } //Limpa os parâmetros par.Clear(); List <String> c1 = new List <string>(); List <String> c2 = new List <string>(); foreach (DataColumn dc in dtInsertSchema.Columns) { if (data.ContainsKey(dc.ColumnName.ToLower())) { if (!String.IsNullOrWhiteSpace(data[dc.ColumnName.ToLower()])) { if (dc.DataType.Equals(typeof(String))) { String txt = Corte((data[dc.ColumnName.ToLower()] != null ? data[dc.ColumnName.ToLower()] : ""), dc.MaxLength); par.Add("@" + dc.ColumnName, GetDBType(dc.DataType), txt.Length).Value = txt; } else { par.Add("@" + dc.ColumnName, GetDBType(dc.DataType)).Value = data[dc.ColumnName.ToLower()]; } c1.Add(dc.ColumnName); c2.Add("@" + dc.ColumnName); } } } foreach (OleDbParameter p in par) { //DebugLog(this, PluginLogType.Debug, package.entityId, package.identityId, "6. par[" + p.ParameterName + "] = " + p.Value, ""); #if DEBUG processLog.AppendLine("6. par[" + p.ParameterName + "] = " + p.Value); #endif } String insert = "insert into [" + table + "] (" + String.Join(",", c1) + ") values (" + String.Join(",", c2) + ")"; db.OnLog += dbExecLog; db.ExecuteNonQuery(insert, CommandType.Text, par); db.OnLog -= dbExecLog; NotityChangeUser(this, package.entityId); processLog.AppendLine("User added"); /* * //Executa as ações do RBAC * if ((package.pluginAction != null) && (package.pluginAction.Count > 0)) * { * foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction) * try * { * switch (act.actionKey.ToLower()) * { * case "procedure": * String sql1 = act.actionValue.Replace("{login}", package.login).Replace("{full_name}", package.fullName.fullName); * db.ExecuteNonQuery(sql1, CommandType.StoredProcedure, null); * break; * * case "sql": * String sql2 = act.actionValue.Replace("{login}", package.login).Replace("{full_name}", package.fullName.fullName); * db.ExecuteNonQuery(sql2, CommandType.Text, null); * break; * * default: * processLog.AppendLine("Action not recognized: " + act.actionKey); * Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "Action not recognized: " + act.actionKey, ""); * break; * } * } * catch (Exception ex) * { * processLog.AppendLine("Error on execute action (" + act.actionKey + "): " + ex.Message); * Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on execute action (" + act.actionKey + "): " + ex.Message, ""); * } * }*/ } catch (Exception ex) { logType = PluginLogType.Error; processLog.AppendLine("Error on process deploy: " + ex.Message); String debugInfo = JSON.Serialize2(new { package = package, fieldMapping = fieldMapping }); if (package.password != "") { debugInfo = debugInfo.Replace(package.password, "Replaced for user security"); } Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, debugInfo); } finally { if (db != null) { db.Dispose(); } Log2(this, logType, package.entityId, package.identityId, "Deploy executed", processLog.ToString()); processLog.Clear(); processLog = null; } }