Пример #1
0
        public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            return;

            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }


            DirectoryInfo importDir = null;;

            try
            {
                importDir = new DirectoryInfo(config["import_folder"].ToString());
                if (!importDir.Exists)
                {
                    throw new DirectoryNotFoundException();
                }
            }
            catch (Exception ex)
            {
                Log(this, PluginLogType.Error, "Erro ao localizar o diretório de importação (" + config["import_folder"].ToString() + "): " + ex.Message);
                return;
            }

            FileInfo f = new FileInfo(Path.Combine(importDir.FullName, "export" + DateTime.Now.ToString("yyyyMMddHHmmss-ffffff") + ".txt"));

            if (!f.Directory.Exists)
            {
                f.Directory.Create();
            }

            using (FileStream fs = f.Open(FileMode.Create))
                using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
                {
                    foreach (PluginConnectorBasePackageData dt in package.pluginData)
                    {
                        w.WriteLine(dt.dataName + "," + dt.dataType + "," + dt.dataValue);
                    }

                    w.Flush();
                    w.Close();
                    fs.Close();
                }
        }
Пример #2
0
        /// <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;
            }
        }
Пример #3
0
        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;
            }
        }
Пример #4
0
        public override void ProcessDelete(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }


            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);

                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 == "")
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Login not found in properties list", "");
                    return;
                }

                if (email == "")
                {
                    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)
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Unexpected error on get cPannel user list", "");
                    return;
                }

                if (accounts.cpanelresult.error != null)
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on get cPannel users list: " + accounts.cpanelresult.error, "");
                    return;
                }

                if (accounts.cpanelresult.data.Count == 0)
                {
                    Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "User not found", "");
                    return;
                }

                //Usuário antigo, somente atualiza
                //cPannelResultData userData = accounts.cpanelresult.data[0];

                throw new NotImplementedException();

                NotityDeletedUser(this, package.entityId, package.identityId);

                Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User deleted", "");
            }
            catch (Exception ex)
            {
                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, "");
            }
        }
Пример #5
0
        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="******"&quota=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;
            }
        }
Пример #6
0
        public override void ProcessDelete(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            try
            {
                String        _dnBase = "";
                List <String> prop    = new List <String>();

                LDAP ldap = new LDAP(config["ldap_server"].ToString(), config["username"].ToString(), config["password"].ToString(), _dnBase);


                LDAP.DebugLog reg = new LDAP.DebugLog(delegate(String text)
                {
                    Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "LDAP log: " + text, "");
                });

                ldap.Log += reg;

                try
                {
                    ldap.Bind();
                }
                catch (Exception ex)
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on connect to ActiveDirectory: " + ex.Message, "");
                    ldap = null;
                    return;
                }

                String login     = package.login;
                String container = package.container;

                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 == "")
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Login not found in properties list", "");
                    return;
                }

                if (container == "")
                {
                    container = "IAMUsers";
                }

                DirectoryEntry         user = null;
                SearchResultCollection res  = ldap.Find(login);
                DirectoryEntry         ct   = ldap.DirectoryEntryRoot;

                if ((container != null) && (container != ""))
                {
                    ct = ldap.AddContainerTree(container);
                }

                if (res.Count == 0) //User not found
                {
                    Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "User not found in AD", "");
                    return;
                }

                ldap.DeleteObject(res[0].GetDirectoryEntry());

                NotityDeletedUser(this, package.entityId, package.identityId);

                Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User deleted", "");
            }
            catch (Exception ex)
            {
                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process delete: " + ex.Message, "");
            }
        }
Пример #7
0
        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;
            }
        }
Пример #8
0
        public override void ProcessDelete(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            String connectionstring = config["connectionstring"].ToString();
            String table            = config["table"].ToString();
            String deploy_filter    = config["deploy_filter"].ToString();
            String login_column     = (config.ContainsKey("login_column") ? config["login_column"].ToString().ToLower() : null);
            String name_column      = (config.ContainsKey("name_column") ? config["name_column"].ToString().ToLower() : null);
            String password_column  = (config.ContainsKey("password_column") ? config["password_column"].ToString().ToLower() : null);

            OdbcDB db = null;

            try
            {
                db = new OdbcDB(connectionstring);
                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>();

                //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.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)
                    {
                        Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Deploy filter column data of '" + k + "' not found", "");
                        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);
                    }
                }


                //Verifica se o registro existe
                DataTable dtReg = db.ExecuteDataTable("select * from " + table + " where " + String.Join(" and ", f1), CommandType.Text, par);
                if (dtReg == null)
                {
                    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)
                {
                    Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "User not found", "");
                    return;
                }


                String update = "delete from " + table + " where " + String.Join(" and ", f1);

                db.ExecuteNonQuery(update, CommandType.Text, par);

                NotityDeletedUser(this, package.entityId, package.identityId);

                Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User deleted", "");
            }
            catch (Exception ex)
            {
                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, "");
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Пример #9
0
        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;
            }
        }
Пример #10
0
        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&params=" + 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;
            }
        }
Пример #11
0
        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;
            }
        }
Пример #12
0
        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;
            }
        }
Пример #13
0
        private Int32 _Deploy(Int64 entityId, Int64 resourcePluginId)
        {
            //Busca todos os plugins e recursos a serem publicados
            DataTable dtPlugins = null;
            Dictionary <Int64, LicenseControl> licControl = null;
            DataTable dtEnt        = null;
            Int32     packageCount = 0;

            StringBuilder deployLog = new StringBuilder();

            try
            {
                dtPlugins = db.Select("select r.context_id, p.id, p.scheme, p.uri, p.assembly, p.create_date, rp.id resource_plugin_id, rp.deploy_individual_package, r.id resource_id, r.proxy_id, p1.name as proxy_name, p1.id proxy_id, p1.enterprise_id, rp.deploy_after_login, rp.password_after_login, rp.deploy_process, rp.deploy_all, rp.deploy_password_hash, rp.use_password_salt, rp.password_salt_end, rp.password_salt from plugin p with(nolock)  inner join resource_plugin rp with(nolock) on rp.plugin_id = p.id  inner join [resource] r on r.id = rp.resource_id inner join proxy p1 on r.proxy_id = p1.id  where " + (resourcePluginId > 0 ? " rp.id = " + resourcePluginId + " and " : "") + " r.enabled = 1 and rp.enabled = 1 and rp.enable_deploy = 1 order by rp.[order]");
                if ((dtPlugins == null) || (dtPlugins.Rows.Count == 0))
                {
                    if ((entityId > 0) || (resourcePluginId > 0))
                    {
                        throw new Exception("0 plugin to process");
                    }

                    //TextLog.Log(moduleSender, "\t0 plugin to process");
                    DebugLog(entityId, "0 plugin to process");
                    return(0);
                }

                DebugLog(entityId, dtPlugins.Rows.Count + " plugin to process");

                licControl = new Dictionary <long, LicenseControl>();

                String rolesText = "";

                //Lista todos os plugins e resources habilitados
                foreach (DataRow dr in dtPlugins.Rows)
                {
                    Boolean individualPackage = (Boolean)dr["deploy_individual_package"];

                    deployLog = new StringBuilder();

                    DebugLog(entityId, "proxy_name = " + dr["proxy_name"].ToString() + ", plugin = " + dr["uri"].ToString() + ", deploy_all? " + dr["deploy_all"].ToString());

                    ProxyConfig config = new ProxyConfig(true);
                    config.GetDBCertConfig(db.Connection, Int64.Parse(dr["enterprise_id"].ToString()), dr["proxy_name"].ToString());

                    DirectoryInfo proxyDir = new DirectoryInfo(Path.Combine(outDirBase.FullName, dr["proxy_id"].ToString() + "_" + dr["proxy_name"].ToString() + "\\" + Path.GetFileNameWithoutExtension(dr["assembly"].ToString()) + "\\rp" + dr["resource_plugin_id"].ToString()));

                    List <PluginConnectorBaseDeployPackage> packageList = new List <PluginConnectorBaseDeployPackage>();
                    List <Int64> roles = new List <Int64>();

                    Int64 enterpriseId = (Int64)dr["enterprise_id"];

                    LicenseControl lic = null;
                    if (!licControl.ContainsKey(enterpriseId))
                    {
                        lic = LicenseChecker.GetLicenseData(db.Connection, null, enterpriseId);
                        licControl.Add(enterpriseId, lic);
                    }
                    else
                    {
                        lic = licControl[enterpriseId];
                    }

                    if (!lic.Valid)
                    {
                        if (!lic.Notified)
                        {
                            db.AddUserLog(LogKey.Licence_error, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], (Int64)dr["enterprise_id"], 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "License error: " + lic.Error);
                        }
                        lic.Notified = true;
                        continue;
                    }


                    if (!(Boolean)dr["deploy_all"])
                    {
                        //Busca os "roles" top
                        String rolesSQL = "select rpr.* from resource_plugin_role rpr with(nolock) inner join resource_plugin rp on rpr.resource_plugin_id = rp.id where rp.resource_id =  " + dr["resource_id"].ToString() + " and rp.plugin_id = " + dr["id"];
                        DebugLog(entityId, "Role SQL = " + rolesSQL);

                        DataTable dtRoles = db.Select(rolesSQL);
                        if (dtRoles == null)
                        {
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                            continue;
                        }

                        List <String> roleNames = new List <String>();

                        //Busca toda a arvore de "roles" a se buscar
                        foreach (DataRow drR in dtRoles.Rows)
                        {
                            DataTable dtR = db.Select("select * from dbo.fn_selectRoleTree(" + drR["role_id"] + ")");
                            if (dtR == null)
                            {
                                continue;
                            }

                            foreach (DataRow drRT in dtR.Rows)
                            {
                                if (!roles.Contains((Int64)drRT["role_id"]))
                                {
                                    roleNames.Add(drRT["name"].ToString());
                                    roles.Add((Int64)drRT["role_id"]);
                                }
                            }
                        }

                        if (roles.Count == 0)
                        {
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Not found roles x identities to deploy");
                            continue;
                        }

                        //Para efeitos de log captura o nome dos roles
                        rolesText = String.Join(", ", roleNames);

                        dtRoles.Clear();
                        dtRoles = null;
                    }

                    //Seleciona todas as entidades do mesmo contexto
                    //Esta listagem considera somente as entidades pertencentes aos plugins de entrada
                    String sql = "select e.id, e.last_login, e.change_password, i.id identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join [resource_plugin] rp with(nolock) on i.resource_plugin_id = rp.id where i.deleted = 0 and e.deleted = 0 {0} and e.context_id = " + dr["context_id"] + (entityId > 0 ? " and e.id = " + entityId : "") + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by e.id, e.last_login, e.change_password, i.id";

                    if (!(Boolean)dr["deploy_all"])
                    {
                        sql = "select e.id, e.last_login, e.change_password, i.id identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join [resource_plugin] rp with(nolock) on i.resource_plugin_id = rp.id inner join identity_role ir with(nolock) on ir.identity_id = i.id  inner join (select rpr.role_id from	resource_plugin_role rpr with(nolock) inner join resource_plugin rp with(nolock) on rp.id = rpr.resource_plugin_id inner join resource r with(nolock) on r.id = rp.resource_id where r.id = "+ dr["resource_id"].ToString() + ") ro on ro.role_id =  ir.role_id where i.deleted = 0 and e.deleted = 0 {0} and ir.role_id in (" + String.Join(",", roles) + ")" + (entityId > 0 ? " and e.id = " + entityId : "") + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) and e.context_id = " + dr["context_id"] + " group by e.id, e.last_login, e.change_password, i.id";
                    }

                    DebugLog(entityId, String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));

                    //Lista todas as entidades e identidades para exportar
                    dtEnt = db.Select(String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));
                    if (dtEnt == null)
                    {
                        DebugLog(entityId, "SQL result is empty");
                        db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                        continue;
                    }

                    if (dtEnt.Rows.Count == 0)
                    {
                        DebugLog(entityId, "SQL result is empty, trying with all plugins");
                        DebugLog(entityId, String.Format(sql, ""));

                        //Lista todas as entidades e identidades para exportar
                        dtEnt = db.Select(String.Format(sql, ""));
                        if (dtEnt == null)
                        {
                            DebugLog(entityId, "SQL result is empty");
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                            continue;
                        }
                    }
                    sql = null;


                    if ((dtEnt.Rows.Count == 0) && ((Boolean)dr["deploy_all"]))
                    {
                        DebugLog(entityId, "SQL result is empty with all plugins, trying with only entity data");

                        sql = "select e.id, e.last_login, e.change_password, cast(0 as bigint) identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id cross join [resource_plugin] rp with(nolock) where e.deleted = 0 {0} and e.context_id = " + dr["context_id"] + (entityId > 0 ? " and e.id = " + entityId : "") + "  group by e.id, e.last_login, e.change_password";

                        DebugLog(entityId, String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));

                        //Lista todas as entidades e identidades para exportar
                        dtEnt = db.Select(String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));
                        if (dtEnt == null)
                        {
                            DebugLog(entityId, "SQL result is empty");
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                            continue;
                        }
                    }
                    sql = null;

                    DebugLog(entityId, "SQL result count " + dtEnt.Rows.Count);

                    if ((dtEnt.Rows.Count > 0) && (entityId == 0))
                    {
                        deployLog.AppendLine("Starting check to deploy " + dtEnt.Rows.Count + " identities for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users"));
                    }

                    Int32 total        = dtEnt.Rows.Count;
                    Int32 licError     = 0;
                    Int32 loguedIgnore = 0;
                    Int32 deploy       = 0;

                    //db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Deploy with " + dtEnt.Rows.Count + " identities for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users"));
                    foreach (DataRow drE in dtEnt.Rows)
                    {
                        //Checagens de licenciamento
                        lic.Count++;

                        if ((lic.Entities > 0) && (lic.Count > lic.Entities))
                        {
                            db.AddUserLog(LogKey.Licence_error, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "License error: License limit (" + lic.Entities + " entities) exceeded");
                            licError++;
                            continue;
                        }

                        try
                        {
                            if (((Boolean)dr["deploy_after_login"]) && (drE["last_login"] == DBNull.Value))
                            {
                                db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "User NOT addedd in deploy package because the user is not logged in yet");
                                loguedIgnore++;
                                continue;
                            }

                            //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "Identity addedd in deploy package");

                            PluginConnectorBaseDeployPackage newPkg = DeployPackage.GetPackage(db, (Int64)dr["proxy_id"], (Int64)dr["resource_plugin_id"], (Int64)drE["id"], (Int64)drE["identity_id"], (Boolean)dr["password_after_login"], (drE["change_password"] == DBNull.Value ? null : (DateTime?)drE["change_password"]), (dr["deploy_password_hash"] == DBNull.Value ? "none" : dr["deploy_password_hash"].ToString()), (Boolean)dr["use_password_salt"], (Boolean)dr["password_salt_end"], dr["password_salt"].ToString());
                            packageList.Add(newPkg);

                            deploy++;

#if DEBUG
                            try
                            {
                                db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Debug, 0, enterpriseId, 0, (Int64)dr["resource_id"], (Int64)dr["id"], newPkg.entityId, newPkg.identityId, "Package generated: " + newPkg.pkgId, SafeTrend.Json.JSON.Serialize <PluginConnectorBaseDeployPackage>(newPkg));
                            }
                            catch { }
#endif

                            packageCount++;
                        }
                        catch (Exception ex)
                        {
                            db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "Erro on deploy user: "******"Total identities: " + total);
                    deployLog.AppendLine("Ignored by licence check: " + licError);
                    deployLog.AppendLine("Ignored by first login rule: " + loguedIgnore);
                    deployLog.AppendLine("Published: " + deploy);

                    db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Deploy package generated for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users"), deployLog.ToString());
                }

                db.closeDB();
                db.Dispose();
            }
            catch (Exception ex)
            {
                DebugLog(entityId, "Erro on Deploy: " + ex.Message);
                throw ex;
            }
            finally
            {
                deployLog.Clear();
                deployLog = null;

                if (dtPlugins != null)
                {
                    dtPlugins.Clear();
                }
                dtPlugins = null;

                if (dtEnt != null)
                {
                    dtEnt.Clear();
                }
                dtEnt = null;

                if (licControl != null)
                {
                    try
                    {
                        List <Int64> k = new List <Int64>();
                        k.AddRange(licControl.Keys);

                        foreach (Int64 l in k)
                        {
                            if (licControl[l] != null)
                            {
                                licControl[l].Dispose();
                                licControl[l] = null;
                            }
                        }

                        k.Clear();
                    }
                    catch { }
                }
                licControl = null;
            }

            return(packageCount);
        }
Пример #14
0
        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;
            }
        }
Пример #15
0
        static void Main(string[] args)
        {
            /*
             ###########################################################
             ##  This is an Sample test of Plugins
             ##  This methods are implemented of Proxy Architheture
             ###########################################################
             */

            //Deploy

            //Mapping of fields
            List <PluginConnectorBaseDeployPackageMapping> fieldMapping = new List <PluginConnectorBaseDeployPackageMapping>();

            fieldMapping.Add(new PluginConnectorBaseDeployPackageMapping("Email", "string", false, false, false));
            fieldMapping.Add(new PluginConnectorBaseDeployPackageMapping("Nome_Compl", "string", false, false, false));
            fieldMapping.Add(new PluginConnectorBaseDeployPackageMapping("CPF", "string", false, false, false));
            fieldMapping.Add(new PluginConnectorBaseDeployPackageMapping("Setor", "string", false, false, false));


            PluginConnectorBaseDeployPackage pkg = new PluginConnectorBaseDeployPackage();

            pkg.container  = "BaseContainer";
            pkg.entityId   = 10;
            pkg.fullName   = new FullName("Helvio Junior");
            pkg.identityId = 11;
            pkg.locked     = false;
            pkg.login      = "******";
            pkg.password   = "******";
            pkg.pluginData = new List <PluginConnectorBasePackageData>();
            pkg.pluginData.Add(new PluginConnectorBasePackageData("Email", "*****@*****.**", "string"));
            pkg.properties.Add(new PluginConnectorBasePackageData("Nome_Compl", "Helvio Junior", "string"));
            pkg.pluginAction.Add(new PluginConnectorBaseDeployPackageAction(PluginActionType.Add, "Test Role", "group", "Teste_direct"));



            //Config definition
            //This config depends on Plugin Config requirements
            Dictionary <String, Object> config = new Dictionary <String, Object>();

            config.Add("sample1", "sample_value");
            config.Add("sample2", "sample_value");
            config.Add("sample3", "sample_value");

            //Sample of config to use at LDAP
            config.Add("ldap_server", "ldap_ip_address");
            config.Add("username", "ldap_user");
            config.Add("password", "ldap_password");


            ActiveDirectory.ActiveDirectoryPlugin pg = new ActiveDirectory.ActiveDirectoryPlugin();
            pg.Log               += new IAM.PluginInterface.LogEvent(pg_Log);
            pg.Log2              += new LogEvent2(pg_Log2);
            pg.NotityChangeUser  += new NotityChangeUserEvent(pg_NotityChangeUser);
            pg.ImportPackageUser += new ImportPackageUserEvent(pg_ImportPackageUser);

            //Process Import of all users from Plugin
            pg.ProcessImport("CacheID", "ImporID", config, fieldMapping);

            //Process Deploy of Package
            pg.ProcessDeploy("CacheID", pkg, config, fieldMapping);

            //Process Import from the same user of an deployed User
            pg.ProcessImportAfterDeploy("CacheID", pkg, config, fieldMapping);
        }
Пример #16
0
        public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            StringBuilder logText = new StringBuilder();

            try
            {
                WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                logText.AppendLine("Current user: "******"Has administrative right: " + pricipal.IsInRole(WindowsBuiltInRole.Administrator));
            }
            catch { }

            try
            {
                if (package.login.Length > 20)
                {
                    throw new Exception("Maximum size of login name reached, this method support up to 20 characters.");
                }

                LocalWindows lWin = new LocalWindows(config["server"].ToString(), config["username"].ToString(), config["password"].ToString());

                try
                {
                    lWin.Bind();
                }
                catch (Exception ex)
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on connect to Windows '" + config["server"].ToString() + "': " + ex.Message + (ex.InnerException != null ? ex.InnerException.Message : ""), "");
                    lWin = null;
                    return;
                }


                logText.AppendLine("Successfully connected on " + config["server"].ToString());


                String login = package.login;

                if (login == "")
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Login not found in properties list", "");
                    return;
                }

                logText.AppendLine("Trying to find user '" + package.login + "'...");
                DirectoryEntry user = lWin.FindUser(package.login);

                if (user == null)
                {
                    logText.AppendLine("User not found, creating...");

                    //Usuário não encontrado, cria
                    if (package.password == "")
                    {
                        package.password = IAM.Password.RandomPassword.Generate(16);
                        Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "User not found in AD and IAM Password not found in properties list, creating a random password (" + package.password + ")", "");
                    }

                    //Primeira senha define uma randômica de 20 caracteres para passar o sistema de complexidade e não apresentar erro
                    //nos próximos passos será tentato trocar a senha
                    lWin.AddUser(package.login, IAM.Password.RandomPassword.Generate(20));
                    user = lWin.FindUser(package.login);

                    Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User added", "");
                }
                else
                {
                    logText.AppendLine("User founded");
                }

                logText.AppendLine("User path: " + user.Path);

                try
                {
                    UserFlags ctrl = (UserFlags)user.InvokeGet("userFlags");

                    //Limpa as flags que serão verificadas por este sistema
                    if ((ctrl & UserFlags.ACCOUNTDISABLE) == UserFlags.ACCOUNTDISABLE)
                    {
                        ctrl -= UserFlags.ACCOUNTDISABLE;
                    }

                    if ((package.locked) || (package.temp_locked))
                    {
                        ctrl = (UserFlags)((Int32)ctrl + UserFlags.ACCOUNTDISABLE);
                    }

                    logText.AppendLine("Setting user flags...");
                    user.Invoke("Put", new object[] { "UserFlags", (Int32)ctrl });
                    user.CommitChanges();
                }
                catch (Exception ex)
                {
                    logText.AppendLine("Error applying user flags: " + ex.Message);
                    user = lWin.FindUser(package.login);
                }

                try
                {
                    logText.AppendLine("Setting user password...");
                    if (!String.IsNullOrWhiteSpace(package.password))
                    {
                        user.Invoke("SetPassword", new Object[] { package.password });
                    }

                    user.CommitChanges();
                }
                catch (Exception ex)
                {
                    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", ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : "") + Environment.NewLine + sPs);
                    return;
                }



                try
                {
                    logText.AppendLine("Setting user access...");
                    //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 "group":
                                    if (act.actionType == PluginActionType.Add)
                                    {
                                        String grpCN = lWin.FindOrCreateGroup(act.actionValue);
                                        if (lWin.AddUserToGroup(user.Name, grpCN))
                                        {
                                            Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User added in group " + act.actionValue + " by role " + act.roleName, "");
                                        }
                                    }
                                    else if (act.actionType == PluginActionType.Remove)
                                    {
                                        String grpCN = lWin.FindOrCreateGroup(act.actionValue);
                                        if (lWin.RemoveUserFromGroup(user.Name, grpCN))
                                        {
                                            Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User removed from group " + act.actionValue + " by role " + act.roleName, "");
                                        }
                                    }
                                    break;

                                default:
                                    Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "Action not recognized: " + act.actionKey, "");
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                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 != "")
                {
                    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)
            {
                logText.AppendLine("Error: " + ex.Message);
                if (ex.InnerException != null)
                {
                    logText.AppendLine(ex.InnerException.Message);
                }
                logText.AppendLine("");
                logText.AppendLine("");
                logText.AppendLine("");

                logText.AppendLine("### Package details");
                String debugInfo = JSON.Serialize2(new { package = package, fieldMapping = fieldMapping });
                if (package.password != "")
                {
                    debugInfo = debugInfo.Replace(package.password, "Replaced for user security");
                }

                logText.AppendLine(debugInfo);

                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, logText.ToString());
                logText = null;
            }
        }
Пример #17
0
        //public static PluginConnectorBaseDeployPackage GetPackage(IAMDatabase db, Int64 proxyId, Int64 resourceId, Int64 pluginId, Int64 entityId, Int64 identityId, Boolean passwordAfterLogin, DateTime? lastChangePassword, String deploy_password_hash)
        public static PluginConnectorBaseDeployPackage GetPackage(IAMDatabase db, Int64 proxyId, Int64 resourcePluginId, Int64 entityId, Int64 identityId, Boolean passwordAfterLogin, DateTime?lastChangePassword, String deploy_password_hash, Boolean useSalt, Boolean saltOnEnd, String salt)
        {
            PluginConnectorBaseDeployPackage pkg = new PluginConnectorBaseDeployPackage();

            List <String> deployInfo = new List <string>();//"Identity addedd in deploy package with ";
            String        deployText = "";

            deployText = "Package ID: " + pkg.pkgId + Environment.NewLine;

            try
            {
                String sql = "select e.*, c.enterprise_id, rp.plugin_id, i.id identity_id, i.temp_locked, c.name context_name, e1.name enterprise_name, block_inheritance = case when exists (select 1 from identity_block_inheritance bi with(nolock) where bi.identity_id = i.id) then cast(1 as bit) else cast(0 as bit) end from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join resource_plugin rp with(nolock) on rp.id = i.resource_plugin_id inner join enterprise e1 with(nolock) on c.enterprise_id = e1.id where e.id = " + entityId + " and i.id = " + identityId;

                if (identityId == 0)
                {
                    sql = "select e.*, c.enterprise_id, rp.plugin_id, cast(0 as bigint) identity_id, cast(0 as bit) as temp_locked, c.name context_name, e1.name enterprise_name, cast(0 as bit) as block_inheritance from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id cross join resource_plugin rp with(nolock) inner join enterprise e1 with(nolock) on c.enterprise_id = e1.id where e.id = " + entityId;
                }

                DataTable dtEnt = db.Select(sql);
                if ((dtEnt == null) || (dtEnt.Rows.Count == 0))
                {
                    throw new Exception("Entity/Identity not found");
                }

                //DataTable dtPlugin = db.Select("select p.* from plugin p where p.id = " + pluginId);
                DataTable dtPlugin = db.Select("select distinct p.*, rp.resource_id from plugin p inner join resource_plugin rp on rp.plugin_id = p.id inner join resource r on rp.resource_id = r.id inner join entity e on e.context_id = r.context_id where rp.id = " + resourcePluginId + " and e.id = " + entityId);
                if ((dtPlugin == null) || (dtPlugin.Rows.Count == 0))
                {
                    throw new Exception("Plugin not found or not linked in the same context of entity");
                }

                if ((Boolean)dtEnt.Rows[0]["block_inheritance"])
                {
                    throw new Exception("Inheritance blocked");
                }

                Int64 resourceId = (Int64)dtPlugin.Rows[0]["resource_id"];
                Int64 pluginId   = (Int64)dtPlugin.Rows[0]["id"];

                //Define as pripriedades gerais
                pkg.registryId         = dtEnt.Rows[0]["id"] + "-" + DateTime.Now.ToString("yyyyMMddHHmmss");
                pkg.entityId           = entityId;
                pkg.identityId         = identityId;
                pkg.fullName           = new FullName(dtEnt.Rows[0]["full_name"].ToString());
                pkg.login              = dtEnt.Rows[0]["login"].ToString();
                pkg.lastChangePassword = (lastChangePassword.HasValue ? lastChangePassword.Value.ToString("o") : null);


                pkg.locked             = (Boolean)dtEnt.Rows[0]["locked"];
                pkg.temp_locked        = (Boolean)dtEnt.Rows[0]["temp_locked"];
                pkg.mustChangePassword = (Boolean)dtEnt.Rows[0]["must_change_password"];
                pkg.deleted            = (Boolean)dtEnt.Rows[0]["deleted"];

                pkg.enterprise = dtEnt.Rows[0]["enterprise_name"].ToString();
                pkg.context    = dtEnt.Rows[0]["context_name"].ToString();

                if ((Boolean)dtEnt.Rows[0]["deleted"])
                {
                    db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "Deploy to delete identity");
                }

                //Container
                pkg.container = "";
                try
                {
                    DataTable dtUserContainer = db.Select("select top 1 c.* from [container] c with(nolock) inner join entity_container ec with(nolock) on c.id = ec.container_id where ec.entity_id = " + entityId);
                    if ((dtUserContainer != null) && (dtUserContainer.Rows.Count > 0))
                    {
                        List <String> path = new List <string>();
                        path.Add(dtUserContainer.Rows[0]["name"].ToString());

                        if ((Int64)dtUserContainer.Rows[0]["parent_id"] > 0)
                        {
                            DataTable dtContainers = db.Select("select c.* from container c with(nolock)");
                            if ((dtContainers != null) || (dtContainers.Rows.Count > 0))
                            {
                                Func <Int64, Boolean> chields = null;
                                chields = new Func <Int64, Boolean>(delegate(Int64 root)
                                {
                                    foreach (DataRow dr in dtContainers.Rows)
                                    {
                                        if (((Int64)dr["id"] == root))
                                        {
                                            path.Add(dr["name"].ToString());
                                            chields((Int64)dr["parent_id"]);
                                            break;
                                        }
                                    }

                                    return(true);
                                });

                                chields((Int64)dtUserContainer.Rows[0]["parent_id"]);
                            }
                        }

                        path.Reverse();
                        pkg.container = "\\" + String.Join("\\", path);
                    }
                }
                catch { }

                //Senha
                pkg.password = "";
                if ((dtEnt.Rows[0]["password"] != DBNull.Value) && (dtEnt.Rows[0]["password"].ToString().Trim() != ""))
                {
                    //Este recurso x plugin só permite o deploy da SENHA após o primeiro login
                    if ((!passwordAfterLogin) || ((passwordAfterLogin) && (dtEnt.Rows[0]["last_login"] != DBNull.Value)))
                    {
                        try
                        {
                            String pwd = "";
                            using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, (Int64)dtEnt.Rows[0]["enterprise_id"]))
                                using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(dtEnt.Rows[0]["password"].ToString())))
                                    pwd = Encoding.UTF8.GetString(cApi.clearData);

                            //Verifica se usará SALT
                            if (useSalt)
                            {
                                if (!String.IsNullOrWhiteSpace(salt))
                                {
                                    if (saltOnEnd)
                                    {
                                        deployInfo.Add("password + SALT");
                                        pwd = pwd + salt.Trim();
                                    }
                                    else
                                    {
                                        deployInfo.Add("SALT + password");
                                        pwd = salt.Trim() + pwd;
                                    }
                                }
                                else
                                {
                                    deployInfo.Add("salt is empty");
                                }
                            }
                            else
                            {
                                deployInfo.Add("no salt");
                            }

                            if (!String.IsNullOrEmpty(deploy_password_hash))
                            {
                                switch (deploy_password_hash.ToLower())
                                {
                                case "md5":
                                    using (MD5 hAlg = MD5.Create())
                                        pkg.password = ComputeHash(hAlg, pwd).ToUpper();
                                    pkg.hash_alg = HashAlg.MD5;
                                    deployInfo.Add("MD5 password");
                                    break;

                                case "sha1":
                                    using (SHA1 hAlg = SHA1.Create())
                                        pkg.password = ComputeHash(hAlg, pwd).ToUpper();
                                    pkg.hash_alg = HashAlg.SHA1;
                                    deployInfo.Add("SHA1 password");
                                    break;

                                case "sha256":
                                    using (SHA256 hAlg = SHA256.Create())
                                        pkg.password = ComputeHash(hAlg, pwd).ToUpper();
                                    pkg.hash_alg = HashAlg.SHA256;
                                    deployInfo.Add("SHA256 password");
                                    break;

                                case "sha512":
                                    using (SHA512 hAlg = SHA512.Create())
                                        pkg.password = ComputeHash(hAlg, pwd).ToUpper();
                                    pkg.hash_alg = HashAlg.SHA512;
                                    deployInfo.Add("SHA512 password");
                                    break;

                                default:
                                    //Nenhum algoritmo de hash
                                    pkg.password = pwd;
                                    pkg.hash_alg = HashAlg.None;
                                    deployInfo.Add("clear text password");
                                    break;
                                }
                            }
                            else
                            {
                                pkg.password = pwd;
                                pkg.hash_alg = HashAlg.None;
                                deployInfo.Add("clear text password");
                            }


                            deployText += "User password added in deploy" + Environment.NewLine;
                            //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password added in deploy");
                        }
                        catch (Exception ex)
                        {
                            deployInfo.Add("no password");
                            deployText += "User password not deployed because a erro on decrypt password: "******"Deploy", UserLogLevel.Warning, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password not deployed because a erro on decrypt password: "******"no password");
                        deployText += "User password not deployed because the user is not logged in yet" + Environment.NewLine;
                        //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Debug, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password not deployed because the user is not logged in yet");
                    }
                }
                else
                {
                    deployInfo.Add("no password");
                    deployText += "User password is empty and not deployed" + Environment.NewLine;
                    //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Debug, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password is empty and not deployed");
                }


                //Busca todas as propriedades com o mapping deste plugin, porém com dados vindos exclusivos da entidade
                DataTable dtEntField = db.Select("select pf.data_name, efe.value, pf.data_type from entity_field efe inner join entity e on efe.entity_id = e.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id =  " + resourcePluginId + ") pf on pf.field_id = efe.field_id where e.id =  " + pkg.entityId + " group by pf.data_name, efe.value, pf.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        if (!pkg.entiyData.Exists(d => (d.dataName == drEf["data_name"].ToString())))
                        {
                            pkg.entiyData.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                        }
                    }
                }


                //Busca todas as propriedades com o mapping deste plugin, porém com dados vindos dos plugins de entrada
                //Exclui os itens de nome e senha por ja terem sido colocados acima
                dtEntField = db.Select("select pf.data_name, ife.value, pf.data_type, rp.priority from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on i.resource_plugin_id = rp.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id =  " + resourcePluginId + ") pf on pf.field_id = ife.field_id where rp.enable_import = 1 and i.entity_id =  " + pkg.entityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by pf.data_name, ife.value, pf.data_type, rp.priority order by rp.priority desc, pf.data_name");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        if (!pkg.importsPluginData.Exists(d => (d.dataName == drEf["data_name"].ToString())))
                        {
                            pkg.importsPluginData.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                        }
                    }
                }

                //Busca todas as propriedades vinculadas a este identity
                //Exclui os itens de nome e senha por ja terem sido colocados acima
                dtEntField = db.Select("select m.data_name, ife.value, f.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on rp.id = i.resource_plugin_id and ife.field_id <> rp.name_field_id inner join resource r on r.context_id = e.context_id and rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.field_id = ife.field_id and m.is_password = 0 inner join field f on ife.field_id = f.id where i.entity_id =  " + pkg.entityId + " and i.id = " + identityId + " group by m.data_name, ife.value, f.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        pkg.pluginData.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                    }
                }

                //Busca todas as propriedades vinculadas aos outras identity
                //Exclui os itens de nome e senha por ja terem sido colocados acima
                dtEntField = db.Select("select m.data_name, ife.value, f.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on rp.id = i.resource_plugin_id and ife.field_id <> rp.name_field_id inner join resource r on r.context_id = e.context_id and rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.field_id = ife.field_id and m.is_password = 0 inner join field f on ife.field_id = f.id where i.entity_id =  " + pkg.entityId + " and i.id <> " + identityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by m.data_name, ife.value, f.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        pkg.properties.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                    }
                }

                //Busca todas as propriedades (independente do identity) usando o mapping deste plugin
                //Exclui o senha por ja tere sido colocado acima
                dtEntField = db.Select("select pf.data_name, ife.value, pf.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id = " + resourcePluginId + ") pf on pf.field_id = ife.field_id where i.entity_id =  " + pkg.entityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by pf.data_name, ife.value, pf.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        pkg.properties.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                    }
                }


                //Busca todas as propriedades da tabela entity_field (exclusiva para dados manuais) usando o mapping deste plugin
                //Exclui o senha por ja tere sido colocado acima
                dtEntField = db.Select("select pf.data_name, efe.value, pf.data_type from entity_field efe inner join entity e on efe.entity_id = e.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id = " + resourcePluginId + ") pf on pf.field_id = efe.field_id where efe.entity_id = " + pkg.entityId + "  group by pf.data_name, efe.value, pf.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        pkg.properties.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                    }
                }


                //Busca somente as propriedades marcadas como ID ou Unique property
                //Exclui os itens de nome e senha por ja terem sido colocados acima
                dtEntField = db.Select("select m.data_name, ife.value, f.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on rp.id = i.resource_plugin_id and ife.field_id <> rp.name_field_id inner join resource r on r.context_id = e.context_id and rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.field_id = ife.field_id and m.is_password = 0 and (m.is_unique_property = 1 or m.is_unique_property = 1) inner join field f on ife.field_id = f.id where i.entity_id =  " + pkg.entityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by m.data_name, ife.value, f.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        pkg.ids.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                    }
                }


                //RBAC
                //Ações das roles desta identity para este resource x plugin
                DataTable dtRoleAction = db.Select("select i.id identity_id, r.* from [identity] i inner join [entity] e on e.id = i.entity_id inner join identity_role ir on ir.identity_id = i.id  inner join (select rp.id resource_plugin_id, rp.plugin_id, rp.resource_id, r.name role_name, rpa.id action_id, rpa.role_id, rpa.action_key, rpa.action_add_value, rpa.action_del_value, rpa.additional_data from resource_plugin rp inner join resource_plugin_role rpr on rpr.resource_plugin_id = rp.id inner join resource_plugin_role_action rpa on rpa.resource_plugin_id = rp.id inner join [role] r on r.id = rpa.role_id and r.id = rpr.role_id) r on r.role_id = ir.role_id where r.resource_plugin_id = " + resourcePluginId + " AND e.id = " + entityId);
                if ((dtRoleAction != null) && (dtRoleAction.Rows.Count > 0))
                {
                    foreach (DataRow drR in dtRoleAction.Rows)
                    {
                        pkg.pluginAction.Add(new PluginConnectorBaseDeployPackageAction(PluginActionType.Add, drR["role_name"].ToString(), drR["action_key"].ToString(), drR["action_add_value"].ToString(), (drR["additional_data"] != DBNull.Value ? drR["additional_data"].ToString() : null)));
                        //db.AddUserLog(LogKey.Role_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "Role: " + drR["role_name"].ToString());
                        deployInfo.Add("role " + drR["role_name"].ToString());
                        deployText += "role " + drR["role_name"].ToString() + Environment.NewLine;
                    }
                }

                db.AddUserLog(LogKey.Role_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "Identity addedd in deploy package with: " + String.Join(", ", deployInfo), deployText);
            }
            finally
            {
                if (deployInfo != null)
                {
                    deployInfo.Clear();
                }
                deployInfo = null;

                deployText = "";
            }

            return(pkg);
        }
Пример #18
0
        public override void ProcessDelete(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            try
            {
                LocalWindows lWin = new LocalWindows(config["server"].ToString(), config["username"].ToString(), config["password"].ToString());

                try
                {
                    lWin.Bind();
                }
                catch (Exception ex)
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on connect to Windows '" + config["server"].ToString() + "': " + ex.Message, "");
                    lWin = null;
                    return;
                }


                String login     = package.login;
                String container = package.container;

                if (login == "")
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Login not found in properties list", "");
                    return;
                }

                if (container == "")
                {
                    container = "IAMUsers";
                }

                DirectoryEntry user = lWin.FindUser(package.login);

                if (user == null)
                {
                    Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "User not found", "");
                    return;
                }

                user.Parent.Children.Remove(user);

                NotityDeletedUser(this, package.entityId, package.identityId);

                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)
            {
                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, "");
            }
        }
Пример #19
0
        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;
            }
        }
Пример #20
0
        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;
            }
        }
Пример #21
0
 public override void ProcessImportAfterDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
 {
     //Não implementado
 }
Пример #22
0
        public override void ProcessDelete(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            /*
             * O JIRA permite a axclusão da conta, porém por questões de auditoria dos chamados a conta será somente desabilitada
             */

            try
            {
                GetLoginToken(config);

                setUserGrp(config);

                String login     = package.login;
                String email     = "";
                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 == "")
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Login not found in properties list", "");
                    return;
                }

                if (email == "")
                {
                    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))
                {
                    Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "User not found", "");
                    return;
                }

                //Remove de todos os grupos
                if (oUser.BaseObject != null)
                {
                    List <String> groups = GetUserGroups(config, email);

                    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)
                        {
                            Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on remove user from group '" + usrG + "' " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : ""), "");
                        }
                    }
                }

                //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);

                ChangePassword(config, email, package.password);

                ChangeUser(config, email, package.fullName.fullName + (package.locked || package.temp_locked ? " (deleted)" : ""), email);

                NotityDeletedUser(this, package.entityId, package.identityId);

                Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User deleted", "");
            }
            catch (Exception ex)
            {
                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : ""), "");
            }
        }
Пример #23
0
 public override void ProcessDelete(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
 {
     //Nda
 }
Пример #24
0
        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;
            }
        }