Ejemplo n.º 1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            LoginData login = LoginUser.LogedUser(this);

            if (login == null)
            {
                Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "login2/", false);
            }
            else
            {
                html += "<form id=\"serviceLogin\" name=\"serviceLogin\" method=\"post\" action=\"" + Session["ApplicationVirtualPath"] + "login2/changepassword/\"><div class=\"login_form\">";

                if (Request.HttpMethod == "POST")
                {
                    try
                    {
                        String password  = Tools.Tool.TrataInjection(Request["password"]);
                        String password2 = Request["password2"];
                        if ((password == null) || (password == ""))
                        {
                            error = MessageResource.GetMessage("type_password");
                        }
                        else if ((password2 == null) || (password2 == ""))
                        {
                            error = MessageResource.GetMessage("type_password_confirm");
                        }
                        else if (password != password2)
                        {
                            error = MessageResource.GetMessage("password_not_equal");
                        }
                        else
                        {
                            Int64 enterpriseId = 0;
                            if ((Page.Session["enterprise_data"]) != null && (Page.Session["enterprise_data"] is EnterpriseData) && (((EnterpriseData)Page.Session["enterprise_data"]).Id != null))
                            {
                                enterpriseId = ((EnterpriseData)Page.Session["enterprise_data"]).Id;
                            }

                            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            {
                                UserPasswordStrength       usrCheck = new UserPasswordStrength(db.Connection, login.Id);
                                UserPasswordStrengthResult check    = usrCheck.CheckPassword(password);
                                if (check.HasError)
                                {
                                    if (check.NameError)
                                    {
                                        error = MessageResource.GetMessage("password_name_part");
                                    }
                                    else
                                    {
                                        String txt = "* " + MessageResource.GetMessage("number_char") + ": " + (!check.LengthError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("uppercase") + ":  " + (!check.UpperCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("lowercase") + ": " + (!check.LowerCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("numbers") + ": " + (!check.DigitError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("symbols") + ":  " + (!check.SymbolError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail"));

                                        error = MessageResource.GetMessage("password_complexity") + ": <br />" + txt;
                                    }
                                }
                                else
                                {
                                    DataTable c = db.Select("select * from entity where deleted = 0 and id = " + login.Id);
                                    if ((c != null) && (c.Rows.Count > 0))
                                    {
                                        //Verifica a senha atual
                                        using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId))
                                            using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(c.Rows[0]["password"].ToString())))
                                            {
                                                using (SqlConnection conn1 = IAMDatabase.GetWebConnection())
                                                    using (EnterpriseKeyConfig sk1 = new EnterpriseKeyConfig(conn1, enterpriseId))
                                                        using (CryptApi cApi1 = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(password)))
                                                        {
                                                            DbParameterCollection pPar = new DbParameterCollection();
                                                            String b64 = Convert.ToBase64String(cApi1.ToBytes());
                                                            pPar.Add("@password", typeof(String), b64.Length).Value = b64;

                                                            db.ExecuteNonQuery("update entity set password = @password, change_password = getdate() , recovery_code = null, must_change_password = 0 where id = " + login.Id, CommandType.Text, pPar);
                                                        }

                                                db.AddUserLog(LogKey.User_PasswordChanged, null, "AutoService", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, login.Id, 0, "Password changed through logged user", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");

                                                //Cria o pacote com os dados atualizados deste usuário
                                                //Este processo visa agiliar a aplicação das informações pelos plugins
                                                db.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + login.Id + ")", CommandType.Text, null);

                                                //Mata a sessão
                                                //Session.Abandon();

                                                Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "login2/passwordchanged/", false);
                                            }
                                    }
                                    else
                                    {
                                        error = MessageResource.GetMessage("internal_error");
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Tools.Tool.notifyException(ex);
                        error = MessageResource.GetMessage("internal_error") + ": " + ex.Message;
                    }
                }

                html += "    <ul>";
                html += "        <li>";
                html += "            <p style=\"width:270px;padding:0 0 20px 0;color:#000;\">" + MessageResource.GetMessage("password_expired_text") + "</p>";
                html += "        </li>";
                html += "    <li>";
                html += "        <span class=\"inputWrap\">";
                html += "			<input type=\"password\" id=\"password\" tabindex=\"1\" name=\"password\" value=\"\" style=\"\"  placeholder=\""+ MessageResource.GetMessage("new_password") + "\" onkeyup=\"cas.passwordStrength('#password');\" onfocus=\"$('#password').addClass('focus');\" onblur=\"$('#password').removeClass('focus');\" />";
                html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
                html += "        </span>";
                html += "    </li>";
                html += "    <li>";
                html += "        <span class=\"inputWrap\">";
                html += "			<input type=\"password\" id=\"password2\" tabindex=\"1\" name=\"password2\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("new_password_confirm") + "\" onfocus=\"$('#password2').addClass('focus');\" onblur=\"$('#password2').removeClass('focus');\" />";
                html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password2').focus();\"></span>";
                html += "        </span>";
                html += "    </li>";
                html += "    <li>";
                html += "        <div id=\"passwordStrength\"><span>" + MessageResource.GetMessage("password_strength") + ": " + MessageResource.GetMessage("unknow") + "</span><div class=\"bar\"></div></div>";
                html += "    </li>";

                if (error != "")
                {
                    html += "        <li><div class=\"error-box\">" + error + "</div>";
                }

                html += "        <li>";
                html += "           <span class=\"forgot\"> <a href=\"" + Session["ApplicationVirtualPath"] + "logout/\">" + MessageResource.GetMessage("cancel") + "</a> </span>";
                html += "           <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("change_password") + "</button>";
                html += "        </li>";
                html += "    </ul>";


                html += "</div></form>";

                holderContent.Controls.Add(new LiteralControl(html));
            }
        }
Ejemplo n.º 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;

            try
            {
                Int64  enterpriseID = ((EnterpriseData)Page.Session["enterprise_data"]).Id;
                Int64  entityId     = 0;
                String err          = "";


                String password  = Tools.Tool.TrataInjection(Request["password"]);
                String password2 = Request["password2"];
                if ((password == null) || (password == ""))
                {
                    ret = new WebJsonResponse("", MessageResource.GetMessage("type_password"), 3000, true);
                }
                else if ((password2 == null) || (password2 == ""))
                {
                    ret = new WebJsonResponse("", MessageResource.GetMessage("type_password_confirm"), 3000, true);
                }
                else if (password != password2)
                {
                    ret = new WebJsonResponse("", MessageResource.GetMessage("password_not_equal"), 3000, true);
                }
                else
                {
                    Int64 enterpriseId = 0;
                    if ((Page.Session["enterprise_data"]) != null && (Page.Session["enterprise_data"] is EnterpriseData) && (((EnterpriseData)Page.Session["enterprise_data"]).Id != null))
                    {
                        enterpriseId = ((EnterpriseData)Page.Session["enterprise_data"]).Id;
                    }

                    String code = "";
                    if (Session["entityId"] != null)
                    {
                        entityId = (Int64)Session["entityId"];
                    }

                    if (Session["userCode"] != null)
                    {
                        code = Session["userCode"].ToString();
                    }

                    if ((entityId > 0) && (code != ""))
                    {
                        using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        {
                            UserPasswordStrength       usrCheck = new UserPasswordStrength(db.Connection, entityId);
                            UserPasswordStrengthResult check    = usrCheck.CheckPassword(password);
                            if (check.HasError)
                            {
                                if (check.NameError)
                                {
                                    ret = new WebJsonResponse("", MessageResource.GetMessage("password_name_part"), 3000, true);
                                }
                                else
                                {
                                    String txt = "* " + MessageResource.GetMessage("number_char") + ": " + (!check.LengthError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                    txt += "* " + MessageResource.GetMessage("uppercase") + ":  " + (!check.UpperCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                    txt += "* " + MessageResource.GetMessage("lowercase") + ": " + (!check.LowerCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                    txt += "* " + MessageResource.GetMessage("numbers") + ": " + (!check.DigitError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                    txt += "* " + MessageResource.GetMessage("symbols") + ":  " + (!check.SymbolError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail"));

                                    ret = new WebJsonResponse("", MessageResource.GetMessage("password_complexity") + ": <br />" + txt, 5000, true);
                                }
                            }
                            else
                            {
                                DataTable c = db.Select("select * from entity where deleted = 0 and id = " + entityId + " and recovery_code = '" + code + "'");
                                if ((c != null) && (c.Rows.Count > 0))
                                {
                                    using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId))
                                        using (CryptApi cApi = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(password)))
                                            db.ExecuteNonQuery("update entity set password = '******', recovery_code = null, last_login = getdate(), change_password = getdate(),  must_change_password = 0 where id = " + entityId, CommandType.Text, null);

                                    db.AddUserLog(LogKey.User_PasswordChanged, null, "AutoService", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, entityId, 0, "Password changed through recovery code", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");

                                    //Cria o pacote com os dados atualizados deste usuário
                                    //Este processo vija agiliar a aplicação das informações pelos plugins
                                    db.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + entityId + ")", CommandType.Text, null);


                                    String html = "";
                                    html += "<div class=\"login_form\">";
                                    html += "<ul>";
                                    html += "    <li class=\"title\">";
                                    html += "        <strong>" + MessageResource.GetMessage("password_changed_sucessfully") + "</strong>";
                                    html += "    </li>";
                                    html += "    <li>";
                                    html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">" + MessageResource.GetMessage("password_changed_text") + "</p>";
                                    html += "    </li>";
                                    html += "    <li>";
                                    html += "        <span class=\"forgot\"> <a href=\"/\">" + MessageResource.GetMessage("return_default") + "</a></span>";
                                    html += "    </li>";
                                    html += "</ul>     ";
                                    html += "</div>";

                                    ret = new WebJsonResponse("#recover_container", html);
                                }
                                else
                                {
                                    ret = new WebJsonResponse("", MessageResource.GetMessage("invalid_code"), 3000, true);
                                }
                            }
                        }
                    }
                    else
                    {
                        ret = new WebJsonResponse("", MessageResource.GetMessage("invalid_session"), 3000, true);
                    }
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex);
                throw ex;
            }


            if (ret != null)
            {
                ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Ejemplo n.º 3
0
        private void BuildBackup()
        {
            StringBuilder bkpLog = new StringBuilder();

            IAMDatabase db = null;

            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();


                bkpLog.AppendLine("Listando tabelas da base de dados...");

                DataTable dtS = db.Select("select TABLE_NAME from information_schema.tables where TABLE_TYPE = 'BASE TABLE' order by TABLE_NAME");

                if ((dtS == null) || (dtS.Rows.Count == 0))
                {
                    bkpLog.AppendLine("Listagem de tabelas vazia ou nula");
                    throw new Exception("Table list is null or empty");
                }

                bkpLog.AppendLine(dtS.Rows.Count + " tabelas");


                FileInfo bkpFile = new FileInfo(Path.Combine(Path.Combine(basePath, "Backup"), "bkp-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm") + ".iambkp"));
                if (!bkpFile.Directory.Exists)
                {
                    bkpFile.Directory.Create();
                }

                bkpLog.AppendLine("Criando arquivo de backup: " + bkpFile.FullName);

                using (SqliteBase exportDB = new SqliteBase(bkpFile))
                {
                    foreach (DataRow drSrc in dtS.Rows)
                    {
                        String tableName = drSrc["TABLE_NAME"].ToString();

                        bkpLog.AppendLine("Exportando tabela: " + tableName);
                        Console.WriteLine(tableName);


                        DataTable dtSchema = db.GetSchema(tableName);

                        StringBuilder createCmd = new StringBuilder();

                        createCmd.AppendLine("DROP TABLE IF EXISTS [" + tableName.ToLower() + "];");

                        /*
                         * CREATE TABLE [Events] (
                         * id INTEGER PRIMARY KEY AUTOINCREMENT,
                         * test_id TEXT NOT NULL,
                         * date datetime not null  DEFAULT (datetime('now','localtime')),
                         * event_text TEXT NULL
                         * );*/
                        List <String> columns = new List <string>();

                        bkpLog.AppendLine("Criando estrutura da tabela");
                        try
                        {
                            foreach (DataColumn dc in dtSchema.Columns)
                            {
                                if (dc.DataType.Equals(typeof(Int32)) || dc.DataType.Equals(typeof(Int64)))
                                {
                                    columns.Add("[" + dc.ColumnName + "] INTEGER NULL");
                                }
                                else if (dc.DataType.Equals(typeof(DateTime)))
                                {
                                    columns.Add("[" + dc.ColumnName + "] datetime NULL");
                                }
                                else
                                {
                                    columns.Add("[" + dc.ColumnName + "] TEXT NULL");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            bkpLog.AppendLine("Erro ao listar as colunas da tabela '" + tableName + "': " + ex.Message);
                            TextLog.Log("Backup", "\tErro ao listar as colunas da tabela '" + tableName + "': " + ex.Message);
                            throw ex;
                        }


                        try
                        {
                            createCmd.AppendLine("CREATE TABLE [" + tableName.ToLower() + "] (");

                            createCmd.AppendLine(String.Join(", " + Environment.NewLine, columns));

                            createCmd.AppendLine(");");

                            exportDB.ExecuteNonQuery(createCmd.ToString());
                        }
                        catch (Exception ex)
                        {
                            bkpLog.AppendLine("Erro ao criando tabela '" + tableName + "': " + ex.Message);
                            TextLog.Log("Backup", "\tErro ao criando tabela '" + tableName + "': " + ex.Message);
                            throw ex;
                        }

                        //Copiando dados das tabelas
                        try
                        {
                            bkpLog.AppendLine("Copiando dados");

                            if (tableName.ToLower() == "logs")
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select l.* from [logs] l with(nolock) inner join [entity_timeline] et with(nolock) on et.log_id = l.id");

                                exportDB.BulkCopy(dtSrcData, tableName.ToLower());
                            }
                            else if (tableName.ToLower() == "entity")
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)");

                                exportDB.BulkCopy(dtSrcData, tableName.ToLower());
                            }
                            else
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)");

                                exportDB.BulkCopy(dtSrcData, tableName.ToLower());
                            }
                        }
                        catch (Exception ex)
                        {
                            bkpLog.AppendLine("Erro copiando dados da tabela '" + tableName + "': " + ex.Message);
                            TextLog.Log("Backup", "\tErro copiando dados da tabela '" + tableName + "': " + ex.Message);
                            //throw ex;
                        }
                    }

                    //No final de todo o processo atualiza as senhas como cleartext
                    try
                    {
                        bkpLog.AppendLine("Atualizando as senhas das entidades");
                        DataTable dtEnt = db.ExecuteDataTable("select id from [enterprise] with(nolock)");

                        foreach (DataRow drEnt in dtEnt.Rows)
                        {
                            using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, (Int64)drEnt["id"]))
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select e.id, e.password, c.enterprise_id from [entity] e with(nolock) inner join [context] c with(nolock) on e.context_id = c.id where c.enterprise_id = " + drEnt["id"]);

                                //Atualiza senha em clear text de cada usu[ario
                                foreach (DataRow drUser in dtSrcData.Rows)
                                {
                                    try
                                    {
                                        using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(drUser["password"].ToString())))
                                        {
                                            exportDB.ExecuteNonQuery("update entity set password = '******' where id = " + drUser["id"]);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        bkpLog.AppendLine("Erro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message);
                                        TextLog.Log("Backup", "\tErro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message);
                                        //throw ex;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        bkpLog.AppendLine("Erro atualizando as senhas para cleartext: " + ex.Message);
                        TextLog.Log("Backup", "\tErro atualizando as senhas para cleartext: " + ex.Message);
                        //throw ex;
                    }
                }



                db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Backup realizado com sucesso", bkpLog.ToString());
            }
            catch (Exception ex)
            {
                TextLog.Log("Backup", "\tError building backup: " + ex.Message);
                bkpLog.AppendLine("Error building backup: " + ex.Message);
                try
                {
                    db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Backup finalizado com erro", bkpLog.ToString());
                }
                catch { }
            }
            finally
            {
                if (bkpLog != null)
                {
                    bkpLog = null;
                }

                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Ejemplo n.º 4
0
        static public LoginResult Grant(Page page, String username, String password)
        {
            try
            {
                if ((username == null) || (username.Trim() == "") || (username == password) || (username.Trim() == ""))
                {
                    return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd")));
                }

                Int64 enterpriseId = 0;
                if ((page.Session["enterprise_data"]) != null && (page.Session["enterprise_data"] is EnterpriseData))
                {
                    enterpriseId = ((EnterpriseData)page.Session["enterprise_data"]).Id;
                }

                String svc = page.Request.QueryString["service"].TrimEnd("/".ToCharArray()).Replace("https://", "//").Replace("http://", "//").Trim();

                DbParameterCollection par = new DbParameterCollection();;
                par.Add("@login", typeof(String), username.Length).Value = username;
                par.Add("@svc", typeof(String), svc.Length).Value        = svc;

                using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    DataTable tmp = db.ExecuteDataTable("select distinct l.id, l.alias, l.full_name, l.login, l.enterprise_id, l.password, l.must_change_password, s.id as service_id, c.service_uri, c.grant_ticket, c.long_ticket from vw_entity_logins l inner join cas_service s on l.enterprise_id = s.enterprise_id left join (select * from cas_entity_ticket c1 inner join cas_service s on s.id = c1.service_id) c on l.id = c.entity_id and c.service_uri = @svc where l.deleted = 0 and l.locked = 0 and (l.login = @login or l.value = @login) and s.service_uri = @svc", CommandType.Text, par);

                    if ((tmp != null) && (tmp.Rows.Count > 0))
                    {
                        foreach (DataRow dr in tmp.Rows)
                        {
                            using (SqlConnection conn = IAMDatabase.GetWebConnection())
                                using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(conn, enterpriseId))
                                    using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString())))
                                        if (Encoding.UTF8.GetString(cApi.clearData) == password)
                                        {
                                            //Realiza o login

                                            LoginData l = new LoginData();
                                            l.Alias          = tmp.Rows[0]["alias"].ToString();
                                            l.FullName       = tmp.Rows[0]["full_name"].ToString();
                                            l.Login          = tmp.Rows[0]["login"].ToString();
                                            l.Id             = (Int64)tmp.Rows[0]["id"];
                                            l.EnterpriseId   = (Int64)tmp.Rows[0]["enterprise_id"];
                                            l.CASGrantTicket = CASTicket.Generate();
                                            l.CASLongTicket  = CASTicket.Generate();

                                            if (tmp.Rows[0]["grant_ticket"] != DBNull.Value)
                                            {
                                                l.CASGrantTicket = tmp.Rows[0]["grant_ticket"].ToString();
                                            }

                                            if (tmp.Rows[0]["long_ticket"] != DBNull.Value)
                                            {
                                                l.CASLongTicket = tmp.Rows[0]["long_ticket"].ToString();
                                            }

                                            try
                                            {
                                                page.Response.Cookies.Remove("TGC-SafeID");
                                                page.Response.Cookies.Remove("TGT-SafeID");
                                            }
                                            catch { }

                                            try
                                            {
                                                //Adiciona o cookie do TGC
                                                HttpCookie cookie = new HttpCookie("TGC-SafeID");
                                                //cookie.Domain = page.Request.Url.Host;
                                                cookie.Path  = "/cas";
                                                cookie.Value = l.CASGrantTicket;

                                                DateTime dtNow    = DateTime.Now;
                                                TimeSpan tsMinute = new TimeSpan(30, 0, 0, 0);
                                                cookie.Expires = dtNow + tsMinute;

                                                //Adiciona o cookie
                                                page.Response.Cookies.Add(cookie);
                                            }
                                            catch { }

                                            try
                                            {
                                                //Adiciona o cookie do TGC
                                                HttpCookie cookie = new HttpCookie("TGT-SafeID");
                                                //cookie.Domain = page.Request.Url.Host;
                                                cookie.Path  = "/cas";
                                                cookie.Value = l.CASLongTicket;

                                                DateTime dtNow    = DateTime.Now;
                                                TimeSpan tsMinute = new TimeSpan(30, 0, 0, 0);
                                                cookie.Expires = dtNow + tsMinute;

                                                //Adiciona o cookie
                                                page.Response.Cookies.Add(cookie);
                                            }
                                            catch { }

                                            db.ExecuteNonQuery("update entity set last_login = getdate() where id = " + l.Id, CommandType.Text, null);

                                            if (tmp.Rows[0]["service_uri"] == DBNull.Value)
                                            {
                                                db.ExecuteNonQuery("insert into cas_entity_ticket ([entity_id],[service_id],[grant_ticket],[long_ticket],[create_by_credentials]) VALUES (" + l.Id + ", " + tmp.Rows[0]["service_id"].ToString() + ", '" + l.CASGrantTicket + "', '" + l.CASLongTicket + "',1)", CommandType.Text, null);
                                            }
                                            else
                                            {
                                                db.ExecuteNonQuery("update cas_entity_ticket set grant_ticket = '" + l.CASGrantTicket + "', long_ticket = '" + l.CASLongTicket + "', expire_date = dateadd(day,1,getdate()), create_by_credentials = 1 where entity_id = " + l.Id + " and service_id = " + tmp.Rows[0]["service_id"].ToString(), CommandType.Text, null);
                                            }

                                            db.AddUserLog(LogKey.User_Logged, null, "CAS", UserLogLevel.Info, 0, 0, 0, 0, 0, l.Id, 0, MessageResource.GetMessage("user_logged") + " " + Tools.Tool.GetIPAddress(), "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");

                                            return(new LoginResult(true, "User OK", (Boolean)tmp.Rows[0]["must_change_password"], l));

                                            break;
                                        }
                                        else
                                        {
                                            db.AddUserLog(LogKey.User_WrongPassword, null, "CAS", UserLogLevel.Info, 0, 0, 0, 0, 0, (Int64)tmp.Rows[0]["id"], 0, MessageResource.GetMessage("user_wrong_password") + " " + Tools.Tool.GetIPAddress(), "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
                                        }
                        }

                        return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd")));
                    }
                    else
                    {
                        db.AddUserLog(LogKey.User_WrongUserAndPassword, null, "CAS", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, MessageResource.GetMessage("user_wrong_password") + " " + Tools.Tool.GetIPAddress(), "{ \"username\":\"" + username.Replace("'", "").Replace("\"", "") + "\", \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
                        return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd")));
                    }
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex, page);
                return(new LoginResult(false, "Internal error"));
            }
            finally
            {
            }
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
0
        public void Commit()
        {
            //Grava as informações no banco de dados
            SqlTransaction trans = db.Connection.BeginTransaction();

            try
            {
                //Cria a empresa
                DbParameterCollection par = new DbParameterCollection();
                par.Add("@name", typeof(String), this.name.Length).Value = this.name;
                par.Add("@fqdn", typeof(String), this.fqdn.Length).Value = this.fqdn;
                par.Add("@server_pkcs12_cert", typeof(String), this.ServerPKCS12Cert.Length).Value = this.ServerPKCS12Cert;
                par.Add("@server_cert", typeof(String), this.ServerCert.Length).Value = this.ServerCert;
                par.Add("@client_pkcs12_cert", typeof(String), this.ClientPKCS12Cert.Length).Value = this.ClientPKCS12Cert;
                par.Add("@language", typeof(String), this.language.Length).Value = this.language;
                par.Add("@auth_plugin", typeof(String)).Value = "auth://iam/plugins/internal";

                Int64 enterpriseId = db.ExecuteScalar <Int64>("sp_new_enterprise", CommandType.StoredProcedure, par, trans);


                //Insere os campos padrões da empresa
                par = new DbParameterCollection();
                par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId;
                par.Add("@field_name", typeof(String)).Value   = "Nome";
                par.Add("@data_type", typeof(String)).Value    = "String";
                par.Add("@public", typeof(Boolean)).Value      = false;
                par.Add("@user", typeof(Boolean)).Value        = false;

                DataTable dtField     = db.ExecuteDataTable("[sp_new_field]", CommandType.StoredProcedure, par, trans);
                Int64     nameFieldId = (Int64)dtField.Rows[0]["id"];

                par = new DbParameterCollection();
                par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId;
                par.Add("@field_name", typeof(String)).Value   = "Login";
                par.Add("@data_type", typeof(String)).Value    = "String";
                par.Add("@public", typeof(Boolean)).Value      = false;
                par.Add("@user", typeof(Boolean)).Value        = false;
                dtField = db.ExecuteDataTable("[sp_new_field]", CommandType.StoredProcedure, par, trans);
                Int64 loginFieldId = (Int64)dtField.Rows[0]["id"];

                par = new DbParameterCollection();
                par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId;
                par.Add("@field_name", typeof(String)).Value   = "E-mail";
                par.Add("@data_type", typeof(String)).Value    = "String";
                par.Add("@public", typeof(Boolean)).Value      = false;
                par.Add("@user", typeof(Boolean)).Value        = false;
                db.ExecuteNonQuery("[sp_new_field]", CommandType.StoredProcedure, par, trans);

                par = new DbParameterCollection();
                par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId;
                par.Add("@field_name", typeof(String)).Value   = "Senha";
                par.Add("@data_type", typeof(String)).Value    = "String";
                par.Add("@public", typeof(Boolean)).Value      = false;
                par.Add("@user", typeof(Boolean)).Value        = false;
                db.ExecuteNonQuery("[sp_new_field]", CommandType.StoredProcedure, par, trans);


                //Cria o contexto
                par = new DbParameterCollection();
                par.Add("@enterprise_id", typeof(Int64)).Value      = enterpriseId;
                par.Add("@name", typeof(String), 7).Value           = "Default";
                par.Add("@password_rule", typeof(String), 15).Value = "default[123456]";
                par.Add("@pwd_length", typeof(Int32)).Value         = 8;
                par.Add("@pwd_upper_case", typeof(Boolean)).Value   = true;
                par.Add("@pwd_lower_case", typeof(Boolean)).Value   = true;
                par.Add("@pwd_digit", typeof(Boolean)).Value        = true;
                par.Add("@pwd_symbol", typeof(Boolean)).Value       = true;
                par.Add("@pwd_no_name", typeof(Boolean)).Value      = true;

                Int64 contextId = db.ExecuteScalar <Int64>("sp_new_context", CommandType.StoredProcedure, par, trans);


                //Cria a role de sistema de administrador desta empresa
                par = new DbParameterCollection();
                par.Add("@enterprise_id", typeof(Int64)).Value      = enterpriseId;
                par.Add("@name", typeof(String)).Value              = "Enterprise Admin";
                par.Add("@system_admin", typeof(Boolean)).Value     = false;
                par.Add("@enterprise_admin", typeof(Boolean)).Value = true;

                Int64 sysRoleId = db.ExecuteScalar <Int64>("sp_new_sys_role", CommandType.StoredProcedure, par, trans);


                //Cria o usuário administrador
                par = new DbParameterCollection();
                par.Add("@context_id", typeof(Int64)).Value = contextId;
                par.Add("@alias", typeof(String)).Value     = "Admin";
                par.Add("@login", typeof(String)).Value     = "admin";
                par.Add("@full_name", typeof(String)).Value = "Admin";

                using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId, trans))
                    using (CryptApi cApi = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes("123456")))
                        par.Add("@password", typeof(String)).Value = Convert.ToBase64String(cApi.ToBytes());

                Int64 entityId = db.ExecuteScalar <Int64>("sp_new_entity", CommandType.StoredProcedure, par, trans);


                //Vincula o usuário na role de sistema como enterprise admin
                db.ExecuteNonQuery("insert into sys_entity_role (entity_id, role_id) values(" + entityId + "," + sysRoleId + ")", CommandType.Text, null, trans);

                //Cria informação na tabela entity_field para o usuário poder aparecer nas consultas
                db.ExecuteNonQuery("insert into entity_field (entity_id, field_id, value) values(" + entityId + "," + nameFieldId + ",'Admin')", CommandType.Text, null, trans);
                db.ExecuteNonQuery("insert into entity_field (entity_id, field_id, value) values(" + entityId + "," + loginFieldId + ",'admin')", CommandType.Text, null, trans);

                //Cria o usuário de integração do CAS
                par = new DbParameterCollection();
                par.Add("@context_id", typeof(Int64)).Value = contextId;
                par.Add("@alias", typeof(String)).Value     = "Integração CAS";
                par.Add("@login", typeof(String)).Value     = "integracao.cas";
                par.Add("@full_name", typeof(String)).Value = "Integração CAS";

                using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId, trans))
                    using (CryptApi cApi = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes("123456")))
                        par.Add("@password", typeof(String)).Value = Convert.ToBase64String(cApi.ToBytes());

                Int64 casEntityId = db.ExecuteScalar <Int64>("sp_new_entity", CommandType.StoredProcedure, par, trans);

                //Vincula o usuário na role de sistema como enterprise admin
                db.ExecuteNonQuery("insert into sys_entity_role (entity_id, role_id) values(" + casEntityId + "," + sysRoleId + ")", CommandType.Text, null, trans);

                //Cria informação na tabela entity_field para o usuário poder aparecer nas consultas
                db.ExecuteNonQuery("insert into entity_field (entity_id, field_id, value) values(" + casEntityId + "," + nameFieldId + ",'Admin')", CommandType.Text, null, trans);
                db.ExecuteNonQuery("insert into entity_field (entity_id, field_id, value) values(" + casEntityId + "," + loginFieldId + ",'admin')", CommandType.Text, null, trans);

                //Cria as regras padrões de criação de login
                db.ExecuteNonQuery("INSERT INTO [login_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'First name, lastname','first_name,dot,last_name',1)", CommandType.Text, null, trans);
                db.ExecuteNonQuery("INSERT INTO [login_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'Fistname, second name','first_name,dot,second_name',2)", CommandType.Text, null, trans);
                db.ExecuteNonQuery("INSERT INTO [login_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'First name, last name, index','first_name,dot,last_name,index',3)", CommandType.Text, null, trans);

                //Cria as regras padrões de criação de e-mail
                db.ExecuteNonQuery("INSERT INTO [st_mail_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'First name, lastname','first_name,dot,last_name',1)", CommandType.Text, null, trans);
                db.ExecuteNonQuery("INSERT INTO [st_mail_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'Fistname, second name','first_name,dot,second_name',2)", CommandType.Text, null, trans);
                db.ExecuteNonQuery("INSERT INTO [st_mail_rule]([context_id],[name],[rule],[order]) VALUES (" + contextId + ",'First name, last name, index','first_name,dot,last_name,index',3)", CommandType.Text, null, trans);

                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
        }
Ejemplo n.º 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;

            LoginData login = LoginUser.LogedUser(this);

            String err = "";

            if (!EnterpriseIdentify.Identify(this, false, out err)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                ret = new WebJsonResponse("", err, 3000, true);
            }
            else if (login == null)
            {
                ret = new WebJsonResponse("", MessageResource.GetMessage("expired_session"), 3000, true, "/login/");
            }
            else
            {
                try
                {
                    Int64 enterpriseId = 0;
                    if ((Page.Session["enterprise_data"]) != null && (Page.Session["enterprise_data"] is EnterpriseData) && (((EnterpriseData)Page.Session["enterprise_data"]).Id != null))
                    {
                        enterpriseId = ((EnterpriseData)Page.Session["enterprise_data"]).Id;
                    }


                    String currentPassword = Tools.Tool.TrataInjection(Request["current_password"]);
                    String password        = Tools.Tool.TrataInjection(Request["password"]);
                    String password2       = Request["password2"];
                    if ((currentPassword == null) || (currentPassword == ""))
                    {
                        ret = new WebJsonResponse("", MessageResource.GetMessage("type_password_current"), 3000, true);
                    }
                    else if ((password == null) || (password == ""))
                    {
                        ret = new WebJsonResponse("", MessageResource.GetMessage("type_password"), 3000, true);
                    }
                    else if ((password2 == null) || (password2 == ""))
                    {
                        ret = new WebJsonResponse("", MessageResource.GetMessage("type_password_confirm"), 3000, true);
                    }
                    else if (password != password2)
                    {
                        ret = new WebJsonResponse("", MessageResource.GetMessage("password_not_equal"), 3000, true);
                    }
                    else
                    {
                        using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        {
                            try
                            {
                                UserPasswordStrength       usrCheck = new UserPasswordStrength(db.Connection, login.Id);
                                UserPasswordStrengthResult check    = usrCheck.CheckPassword(password);
                                if (check.HasError)
                                {
                                    if (check.NameError)
                                    {
                                        ret = new WebJsonResponse("", MessageResource.GetMessage("password_name_part"), 3000, true);
                                    }
                                    else
                                    {
                                        String txt = "* " + MessageResource.GetMessage("number_char") + ": " + (!check.LengthError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("uppercase") + ":  " + (!check.UpperCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("lowercase") + ": " + (!check.LowerCaseError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("numbers") + ": " + (!check.DigitError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail")) + "<br />";
                                        txt += "* " + MessageResource.GetMessage("symbols") + ":  " + (!check.SymbolError ? MessageResource.GetMessage("ok") : MessageResource.GetMessage("fail"));

                                        ret = new WebJsonResponse("", MessageResource.GetMessage("password_complexity") + ": <br />" + txt, 5000, true);
                                    }
                                }
                                else
                                {
                                    DataTable c = db.Select("select * from entity where deleted = 0 and id = " + login.Id);
                                    if ((c != null) && (c.Rows.Count > 0))
                                    {
                                        //Verifica a senha atual
                                        using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId))
                                            using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(c.Rows[0]["password"].ToString())))
                                                if (Encoding.UTF8.GetString(cApi.clearData) != currentPassword)
                                                {
                                                    ret = new WebJsonResponse("", MessageResource.GetMessage("current_password_invalid"), 3000, true);
                                                }
                                                else
                                                {
                                                    using (SqlConnection conn1 = IAMDatabase.GetWebConnection())
                                                        using (EnterpriseKeyConfig sk1 = new EnterpriseKeyConfig(conn1, enterpriseId))
                                                            using (CryptApi cApi1 = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(password)))
                                                            {
                                                                DbParameterCollection pPar = new DbParameterCollection();;
                                                                String b64 = Convert.ToBase64String(cApi1.ToBytes());
                                                                pPar.Add("@password", typeof(String), b64.Length).Value = b64;

                                                                db.ExecuteNonQuery("update entity set password = @password, change_password = getdate() , recovery_code = null, must_change_password = 0 where id = " + login.Id, CommandType.Text, pPar);
                                                            }


                                                    db.AddUserLog(LogKey.User_PasswordChanged, null, "AutoService", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, login.Id, 0, "Password changed through autoservice logged user", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");

                                                    //Cria o pacote com os dados atualizados deste usuário
                                                    //Este processo visa agiliar a aplicação das informações pelos plugins
                                                    db.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + login.Id + ")", CommandType.Text, null);

                                                    /*
                                                     * IAMDeploy deploy = null;
                                                     *
                                                     * using (ServerDBConfig conf = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                                                     *  deploy = new IAMDeploy("WebServer", DB.GetConnectionString(), conf.GetItem("outboundFiles"));
                                                     *
                                                     * if (deploy != null)
                                                     *  deploy.DeployOne(login.Id);*/



                                                    String html = "";
                                                    html += "<div class=\"no-tabs pb10\">";
                                                    html += "   <div class=\"form-group\">";
                                                    html += "       <h1>" + MessageResource.GetMessage("password_changed_sucessfully") + "</h1> ";
                                                    html += "   </div>";
                                                    html += "   <div class=\"form-group\"><span class=\"text-message\">" + MessageResource.GetMessage("password_changed_text") + "</span></div>";
                                                    html += "</div>";

                                                    ret = new WebJsonResponse("#pwdForm", html);
                                                }
                                    }
                                    else
                                    {
                                        ret = new WebJsonResponse("", "Internal error", 3000, true);
                                    }
                                }
                            }
                            finally
                            {
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Tools.Tool.notifyException(ex);
                    throw ex;
                }
            }

            if (ret != null)
            {
                ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            ServerLocalConfig localConfig = new ServerLocalConfig();

            localConfig.LoadConfig();

            if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null);
            }


            /*************
             * Gera os certificados do servidor
             */
            MSSQLDB db = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);

            db.openDB();
            db.Timeout = 300;


            Int64 entityId = 0;

            if (args.Length > 0)
            {
                Int64.TryParse(args[0], out entityId);
            }

            DataTable tmp = db.Select(String.Format("select e.*, e1.id enterprise_id from entity e inner join context c on c.id = e.context_id inner join enterprise e1 on e1.id = c.enterprise_id where e.id = {0}", entityId));

            if (tmp == null)
            {
                StopOnError("Select is null", null);
            }

            if (tmp.Rows.Count == 0)
            {
                StopOnError("Select is empty", null);
            }

            EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.conn, (Int64)tmp.Rows[0]["entity_id"]);

            Int64 context      = (Int64)tmp.Rows[0]["context_id"];
            Int64 enterpriseId = (Int64)tmp.Rows[0]["enterprise_id"];

            Console.WriteLine("##############################");
            Console.WriteLine("C Pwd: " + tmp.Rows[0]["password"].ToString());

            Console.WriteLine("");
            Console.WriteLine("##############################");
            using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(tmp.Rows[0]["password"].ToString())))
                Console.WriteLine("Pwd: " + Encoding.UTF8.GetString(cApi.clearData));


            String text = "";

            do
            {
                //Console.Clear();
                Console.Write("Deseja redefinir a senha do usuário? (Y/N): ");
                text = Console.ReadLine().Trim();
                if (text.ToLower() == "y")
                {
                    break;
                }
                else if (text.ToLower() == "n")
                {
                    text = "";
                    break;
                }
                else
                {
                    text = "";
                }
            } while (text == "");

            if (text.ToLower() == "y")
            {
                BuildPassword(db, null, context, entityId, enterpriseId);
            }

            db.closeDB();

            StopOnError("", null);
        }
Ejemplo n.º 9
0
        public static void BuildPassword(MSSQLDB db, SqlTransaction trans, Int64 context, Int64 entityId, Int64 enterpriseId)
        {
            String pwdMethod = "random";
            String pwdValue  = "";

            using (DataTable dtRules = db.Select("select password_rule from context c where c.id = " + context + " and (c.password_rule is not null and rtrim(LTRIM(c.password_rule)) <> '')", trans))
            {
                if ((dtRules != null) && (dtRules.Rows.Count > 0))
                {
                    String v = dtRules.Rows[0]["password_rule"].ToString().Trim();

                    if (v.IndexOf("[") != -1)
                    {
                        Regex rex = new Regex(@"(.*?)\[(.*?)\]");
                        Match m   = rex.Match(v);
                        if (m.Success)
                        {
                            pwdMethod = m.Groups[1].Value.ToLower();
                            pwdValue  = m.Groups[2].Value;
                        }
                    }
                    else
                    {
                        pwdMethod = v;
                    }
                }
            }

            switch (pwdMethod)
            {
            case "default":
                //Nada a senha ja foi definida
                break;

            case "field":
                throw new NotImplementedException();

                /*
                 * Int64 fieldId = 0;
                 * Int64.TryParse(pwdValue, out fieldId);
                 * using (DataTable dtFields = db.Select("select * from identity_field where identity_id = " + this.IdentityId + " and field_id = " + fieldId, trans))
                 *  if ((dtFields != null) && (dtFields.Rows.Count > 0))
                 *  {
                 *      pwdValue = dtFields.Rows[0]["value"].ToString();
                 *  }*/
                break;

            default:     //Random
                pwdValue = "";
                break;
            }

            //Se a senha continua vazia, gera uma randômica
            if ((pwdValue == null) || (pwdValue == ""))
            {
                pwdValue = RandomPassword.Generate(14, 16);
            }

            Boolean MustChangePassword = true;

            String pwd = "";

            using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.conn, enterpriseId, trans))

                using (CryptApi cApi = new CryptApi(sk.ServerCert, Encoding.UTF8.GetBytes(pwdValue)))
                    pwd = Convert.ToBase64String(cApi.ToBytes());


            String sql = "update entity set password = @password, change_password = getdate(), must_change_password = @must where id = @entityId";

            SqlParameterCollection par = GetSqlParameterObject();

            par.Add("@entityId", SqlDbType.BigInt).Value = entityId;

            par.Add("@password", SqlDbType.VarChar, pwd.Length).Value = pwd;
            par.Add("@must", SqlDbType.Bit).Value = MustChangePassword;

            db.AddUserLog(LogKey.User_PasswordChanged, null, "Engine", UserLogLevel.Info, 0, 0, context, 0, 0, entityId, 0, "Password changed", "", trans);

            db.ExecuteNonQuery(sql, CommandType.Text, par, trans);
        }
Ejemplo n.º 10
0
        public RegistryProcessStatus Process(EnterpriseKeyConfig enterpriseKey, LockRules lockRules, IgnoreRules ignoreRules, RoleRules roleRules, LicenseControl lic)
        {
            List <UserDataFields> fieldsData = null;
            List <UserDataFields> filter     = null;
            TestTimer             tmp        = null;
            Boolean showError = true;


            SqlTransaction trans = null;

            try
            {
                RegistryProcess.ProccessLog dLog = new RegistryProcess.ProccessLog(delegate(String text)
                {
#if DEBUG
                    Log("\t{profile} " + text);
#endif
                });

                tmp = new TestTimer("Process->Starting", dLog);

                Log("Starting registry processor");
                Log("");

                Log("Plugin Config");
                Log(pluginConfig.ToString());
                Log("");

                Log("Registry data:");
                Log("\tGenerated Date: " + package.build_data);
                Log("\tContext id: " + this.contextId);
                Log("\tResource plugin id: " + this.resourcePluginId);
                Log("\tResource id: " + this.resourceId);
                Log("\tPlugin: " + this.pluginUri);
                Log("\tImport id: " + this.importId);
                Log("\tPackage id: " + this.packageId);
                Log("\tContainer: " + package.container);
                Log("\tGroups: " + (package.groups != null ? String.Join(", ", package.groups) : ""));
                Log("");

                if (this.pluginConfig.mapping == null)
                {
                    if (!pluginConfig.enable_import)
                    {
                        showError = false;
                    }

                    throw new Exception("Plugin mapping is null");
                }

                if (this.pluginConfig.mapping.Count == 0)
                {
                    if (!pluginConfig.enable_import)
                    {
                        showError = false;
                    }

                    throw new Exception("Plugin mapping is empty");
                }

                String where = "ci.status = 'F' and ci.resource_plugin_id = '" + this.resourcePluginId + "' and  ci.import_id = '" + this.importId + "' and ci.package_id = '" + this.packageId + "'";

                tmp.Stop(dbAux.Connection, null);


                /*
                 * ======================================
                 * == Resgata Package Track ID*/


                try
                {
                    DbParameterCollection par = new DbParameterCollection();

                    par.Add("@date", typeof(DateTime)).Value = this.package.GetBuildDate();
                    par.Add("@package_id", typeof(String), this.package.pkgId.Length).Value = this.package.pkgId;

                    this.packageTrackId = dbAux.ExecuteScalar <Int64>("select id from st_package_track where flow = 'inbound' and date = @date and package_id = @package_id", System.Data.CommandType.Text, par, null);
                }
                catch (Exception ex)
                {
#if DEBUG
                    internalLog.AppendLine("Error getting package track entity id: " + ex.Message);
#endif
                }

                /*
                 * == Final do resgate Package Track ID
                 * ======================================*/


                /*
                 * ======================================
                 * == Monta tabela de filtragem*/

                tmp = new TestTimer("Process->Filter table", dLog);


                filter = new List <UserDataFields>();

                //Adiciona os mapeamentos que são ID ou único para filtragem
                foreach (PluginConnectorBasePackageData data in package.properties)
                {
                    if (String.IsNullOrWhiteSpace(data.dataValue))
                    {
                        continue;
                    }

                    foreach (PluginConfigMapping m in this.pluginConfig.mapping)
                    {
                        if ((m.is_id || m.is_unique_property) && (m.data_name.ToLower() == data.dataName.ToLower()) && !filter.Exists(f => (f.Mapping.field_id == m.field_id && f.Equal(data.dataValue.Trim()))))
                        {
                            filter.Add(new UserDataFields((PluginConfigMapping)m.Clone(), data.dataValue.Trim()));
                        }
                    }
                }

                Log("Filter data:");
                foreach (UserDataFields f in filter)
                {
                    Log("\t[" + f.Mapping.data_name.ToLower() + "] is " + (f.Mapping.is_id ? "ID" : "Unique field") + " = " + f.Value);
                }
                Log("");


                tmp.Stop(dbAux.Connection, null);


                /*
                 * == Final tabela de filtragem
                 * ======================================*/

                /*
                 * ======================================
                 * == Monta tabela de dados*/

                tmp = new TestTimer("Process->Data table", dLog);


                //Monta tabela de dados com base no mapeamento e dados recebidos
                fieldsData = new List <UserDataFields>();

                foreach (PluginConnectorBasePackageData data in package.properties)
                {
                    if (String.IsNullOrWhiteSpace(data.dataValue))
                    {
                        continue;
                    }

                    foreach (PluginConfigMapping m in this.pluginConfig.mapping)
                    {
                        if ((m.data_name.ToLower() == data.dataName.ToLower()) && !fieldsData.Exists(f => (f.Mapping.field_id == m.field_id && f.Equal(data.dataValue.Trim()))))
                        {
                            try
                            {
                                fieldsData.Add(new UserDataFields((PluginConfigMapping)m.Clone(), data.dataValue.Trim()));
                            }
                            catch (Exception ex2)
                            {
                                Log(ex2.Message);
                            }
                        }
                    }
                }

                Log("Proccess data: " + (fieldsData.Count == 0 ? "empty" : ""));
                foreach (UserDataFields f in fieldsData)
                {
                    Log("\t[" + f.Mapping.data_name.ToLower() + "] Flags (" + (f.Mapping.is_login ? "is_login " : "") + (f.Mapping.is_name ? "is_name " : "") + (f.Mapping.is_password ? "is_password " : "") + ") " + (f.Mapping.is_id ? "is ID" : (f.Mapping.is_unique_property ? "is Unique field" : "")) + " = " + (f.Mapping.is_password ? "*****" : f.Value));
                }
                Log("");

                tmp.Stop(dbAux.Connection, null);


                /*
                 * == Final tabela de dados
                 * ======================================*/


                /*
                 * ======================================
                 * == Cria o objeto do usuário e tenta localiza-lo*/
                tmp = new TestTimer("Process->Create user object", dLog);

                userData        = new UserData(db.Connection, this.pluginConfig, enterpriseKey, enterpriseId, contextId, resourcePluginId, resourceId, pluginId, pluginConfig.mail_domain, pluginConfig.mail_field_id, filter, fieldsData, package.container);
                userData.OnLog += Log;
                userData.CheckUser();

                tmp.Stop(dbAux.Connection, null);

                tmp = new TestTimer("Process->Check exists and import enabled", dLog);

                //Não existe e não é possível adicionar
                if ((userData.EntityId == 0) && ((!pluginConfig.permit_add_entity) || (!pluginConfig.enable_import)))
                {
                    String sId = "";
                    foreach (UserDataFields f in filter)
                    {
                        if (sId != "")
                        {
                            sId += ", ";
                        }
                        sId += f.Mapping.data_name + " = " + f.Value;
                    }

                    //Add identity to audit
                    userData.AddToAudit("not_exists", null);

                    throw new Exception("Entity not found and this plugin " + (!pluginConfig.enable_import ? "is disabled to import" : "not permit add entity") + ": " + sId);
                    return(RegistryProcessStatus.Error);
                }


                tmp.Stop(dbAux.Connection, null);

                tmp = new TestTimer("Process->Check deleted", dLog);


                if (userData.Deleted)
                {
                    String sId = "";
                    foreach (UserDataFields f in filter)
                    {
                        if (sId != "")
                        {
                            sId += ", ";
                        }
                        sId += f.Mapping.data_name + " = " + f.Value;
                    }

                    //Add identity to audit
                    //userData.AddToAudit("deleted");

                    throw new Exception("Entity found but marked as deleted: " + sId);
                    return(RegistryProcessStatus.Error);
                }


                tmp.Stop(dbAux.Connection, null);

                //Verifica se o registro deve ser ignorado
                //Se sim, nada será realizado, nem bloqueio, nem explusão, nem adição....
                tmp = new TestTimer("Process->Check ignore", dLog);
                if (userData.Ignore(ignoreRules, this.pluginUri))
                {
                    DbParameterCollection par = new DbParameterCollection();
                    par.Add("@resource_plugin_id", typeof(Int64)).Value = resourcePluginId;
                    par.Add("@import_id", typeof(String)).Value         = importId;
                    par.Add("@package_id", typeof(String)).Value        = packageId;
                    par.Add("@status", typeof(String)).Value            = 'F';
                    par.Add("@new_status", typeof(String)).Value        = 'I';

                    ExecuteNonQuery(db.Connection, "sp_migrate_imported2", CommandType.StoredProcedure, par, null);

                    par.Clear();
                    par = null;

                    return(RegistryProcessStatus.Ignored);
                }

                tmp.Stop(dbAux.Connection, null);


                //Esta parte do código está propositalmente depois da verificação de existência e se permite add o login
                //Pois este código é dispendioso, e só deve ser executado quando realmente necessario
                tmp = new TestTimer("Process->Check lock", dLog);
                userData.CheckLock(lockRules, this.pluginUri);
                tmp.Stop(dbAux.Connection, null);

                if ((userData.EntityId == 0) && (userData.Locked))
                {
                    tmp = new TestTimer("Process->Check exists and locked", dLog);

                    String sId = "";
                    foreach (UserDataFields f in filter)
                    {
                        if (sId != "")
                        {
                            sId += ", ";
                        }
                        sId += f.Mapping.data_name + " = " + f.Value;
                    }

                    //userData.AddToAudit("locked", trans);

                    throw new Exception("Entity not found and this user is locked: " + sId);
                    return(RegistryProcessStatus.Error);
                }
                else if (userData.EntityId == 0)//Não existe a entidade
                {
                    tmp = new TestTimer("Process->Add entity (check lic)", dLog);

                    lic.Count++;

                    if ((lic.Entities > 0) && (lic.Count > lic.Entities))
                    {
                        String sId = "";
                        foreach (UserDataFields f in filter)
                        {
                            if (sId != "")
                            {
                                sId += ", ";
                            }
                            sId += f.Mapping.data_name + " = " + f.Value;
                        }

                        throw new Exception("License error: Entity not found and license limit (" + lic.Entities + " entities) exceeded. " + sId);
                        return(RegistryProcessStatus.Error);
                    }

                    tmp.Stop(dbAux.Connection, null);


                    userData.NewUser = true;

                    tmp = new TestTimer("Process->Add entity (UpdateName)", dLog);


                    userData.UpdateName();


                    tmp.Stop(dbAux.Connection, null);


                    //Cria o login
                    tmp = new TestTimer("Process->Add entity (MakeLogin)", dLog);

                    //Define o campo de login com base nas informações recebidas
                    foreach (UserDataFields f in fieldsData)
                    {
                        if (f.Mapping.is_login && !String.IsNullOrEmpty(f.Value.ToString()) && !String.IsNullOrWhiteSpace(f.Value.ToString()))
                        {
                            userData.Login = f.Value.ToString();
                        }
                    }

                    Log("Build login...");
                    userData.MakeLogin(pluginConfig.build_login, null);

                    tmp.Stop(dbAux.Connection, null);


                    tmp = new TestTimer("Process->Add entity (MakeEmail)", dLog);

                    //Cria o e-mail
                    Log("Build e-mail...");
                    if (pluginConfig.build_mail)
                    {
                        userData.MakeEmail(null, pluginConfig.mail_domain, pluginConfig.mail_field_id);
                    }

                    tmp.Stop(dbAux.Connection, null);

                    if (userData.FullName == null)
                    {
                        userData.FullName = userData.Login;
                    }

                    trans = db.Connection.BeginTransaction();

                    tmp = new TestTimer("Process->Add entity", dLog);

                    DbParameterCollection par = new DbParameterCollection();
                    par.Add("@resourcePluginId", typeof(Int64)).Value = resourcePluginId;
                    par.Add("@alias", typeof(String)).Value           = userData.FullName;
                    par.Add("@full_name", typeof(String)).Value       = userData.FullName;

                    DataTable dtEnt = ExecuteDataTable(db.Connection, "sp_new_entity_and_identity", CommandType.StoredProcedure, par, trans);
                    if ((dtEnt == null) || (dtEnt.Rows.Count == 0))
                    {
                        throw new Exception("Erro on insert entity & identity");
                    }

                    par.Clear();
                    par = null;

                    userData.EntityId   = (Int64)dtEnt.Rows[0]["id"];
                    userData.IdentityId = (Int64)dtEnt.Rows[0]["identity_id"];

                    Log("New entity/identity");

                    AddUserLog(db.Connection, LogKey.User_Added, null, "Engine", UserLogLevel.Info, 0, 0, 0, this.resourceId, this.pluginId, userData.EntityId, userData.IdentityId, "User added in IAM Database", this.internalLog.ToString(), trans);

                    tmp.Stop(dbAux.Connection, null);
                }
                else if (userData.IdentityId == 0)//Existe a entidade porém não a identidade
                {
                    tmp = new TestTimer("Process->Add identity", dLog);


                    trans = db.Connection.BeginTransaction();

                    DbParameterCollection par1 = new DbParameterCollection();
                    par1.Add("@entityId", typeof(Int64)).Value         = userData.EntityId;
                    par1.Add("@resourcePluginId", typeof(Int64)).Value = resourcePluginId;

                    DataTable dtEnt = ExecuteDataTable(db.Connection, "sp_new_identity", CommandType.StoredProcedure, par1, trans);
                    if ((dtEnt == null) || (dtEnt.Rows.Count == 0))
                    {
                        throw new Exception("Erro on insert identity");
                    }

                    par1.Clear();
                    par1 = null;

                    if ((Boolean)dtEnt.Rows[0]["new_identity"])
                    {
                        Log("New identity");
                    }

                    userData.IdentityId = (Int64)dtEnt.Rows[0]["identity_id"];

                    AddUserLog(db.Connection, LogKey.User_Added, null, "Engine", UserLogLevel.Info, 0, 0, 0, this.resourceId, this.pluginId, userData.EntityId, userData.IdentityId, "Identity added", this.internalLog.ToString(), trans);

                    tmp.Stop(dbAux.Connection, null);
                }

                try
                {
                    DbParameterCollection par = new DbParameterCollection();
                    par.Add("@entity_id", typeof(Int64)).Value = userData.EntityId;
                    par.Add("@date", typeof(DateTime)).Value   = this.package.GetBuildDate();
                    par.Add("@package_id", typeof(String), this.package.pkgId.Length).Value = this.package.pkgId;

                    dbAux.ExecuteNonQuery("UPDATE st_package_track SET entity_id = @entity_id where flow = 'inbound' and date = @date and package_id = @package_id", System.Data.CommandType.Text, par, null);
                }
                catch (Exception ex) {
#if DEBUG
                    internalLog.AppendLine("Error updating package track entity id: " + ex.Message);
#endif
                }

                if (trans == null)
                {
                    trans = db.Connection.BeginTransaction();
                }

                try
                {
                    tmp = new TestTimer("Process->Lockunlock", dLog);

                    //Só permite alterar este status se for um plugin de entrada
                    if ((pluginConfig.permit_add_entity) && (userData.Locked != userData.LastLocked))
                    {
                        Log((userData.Locked ? "Locking user" : "Unlocking user"));
                        AddUserLog(db.Connection, (userData.Locked ? LogKey.User_Locked : LogKey.User_Unlocked), null, "Engine", UserLogLevel.Debug, 0, 0, 0, this.resourceId, this.pluginId, userData.EntityId, userData.IdentityId, (userData.Locked ? "Locking user" : "Unlocking user"), (userData != null ? userData.LockedInfo : ""), trans);
                    }
                    else
                    {
                        //Caso não permitido retorna ao estado anterior
                        userData.Locked = userData.LastLocked;
                    }

                    tmp.Stop(dbAux.Connection, null);
                    tmp = new TestTimer("Process->UpdateFields", dLog);


                    //Atualiza as propriedades (fields)
                    Log("Updating user values...");
                    userData.UpdateFields(trans, pluginConfig.enable_import);

                    tmp.Stop(dbAux.Connection, null);


                    if (pluginConfig.enable_import)
                    {
                        tmp = new TestTimer("Process->BuildPassword", dLog);

                        Log("Building password...");
                        userData.BuildPassword(trans);

                        tmp.Stop(dbAux.Connection, null);
                        tmp = new TestTimer("Process->UpdateUser", dLog);

                        //Registro tudo que está pendente no banco
                        Log("Updating user data (name, login and password)...");
                        userData.UpdateUser(trans);

                        tmp.Stop(dbAux.Connection, null);
                        tmp = new TestTimer("Process->UpdateGroups", dLog);

                        //Registro tudo que está pendente no banco
                        if (pluginConfig.import_groups)
                        {
                            Log("Updating user groups...");
                            userData.UpdateGroups(trans, package.groups);
                        }

                        tmp.Stop(dbAux.Connection, null);
                    }

                    tmp = new TestTimer("Process->update collector_imports", dLog);

                    //Excluir estes registros processados
                    //ExecuteNonQuery(conn,"delete from collector_imports where " + where.Replace("ci.", ""), CommandType.Text, null, trans);
                    //ExecuteNonQuery(conn,"update collector_imports set status = 'I' where " + where.Replace("ci.", ""), CommandType.Text, null, trans);

                    /*	@plugin_uri varchar(500),
                     *  @resource_id bigint,
                     * @import_id varchar(40),
                     * @registry_id varchar(40),
                     * @status varchar(2),
                     * @new_status varchar(2)*/


                    tmp.Stop(dbAux.Connection, null);
                    tmp = new TestTimer("Process->Commit", dLog);

                    Log("Commit user data on database");
                    trans.Commit();
                    trans = null;

                    //try to rebuild user index
                    for (Int32 i = 0; i <= 5; i++)
                    {
                        try
                        {
                            if (pluginConfig.enable_import)
                            {
                                userData.RebuildIndexes(null);
                                break;
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch {
                            Thread.Sleep(2000);
                        }
                    }

                    tmp.Stop(dbAux.Connection, null);

                    DbParameterCollection par = new DbParameterCollection();
                    par.Add("@resource_plugin_id", typeof(Int64)).Value = resourcePluginId;
                    par.Add("@import_id", typeof(String)).Value         = importId;
                    par.Add("@package_id", typeof(String)).Value        = packageId;
                    par.Add("@status", typeof(String)).Value            = 'F';
                    par.Add("@new_status", typeof(String)).Value        = 'I';

                    ExecuteNonQuery(db.Connection, "sp_migrate_imported2", CommandType.StoredProcedure, par, null);

                    par.Clear();
                    par = null;


                    /*
                     * ======================================*/
                }
                catch (Exception ex)
                {
                    if (trans != null)
                    {
                        trans.Rollback();
                    }

                    trans = null;

                    throw ex;
                }


                tmp = new TestTimer("Process->UpdateRoles", dLog);


                //Por fim verifica as roles
                if (pluginConfig.enable_import)
                {
                    userData.UpdateRoles(null, roleRules, this.pluginUri);
                }


                tmp.Stop(dbAux.Connection, null);


                try
                {
                    dbAux.AddPackageTrack(this.packageTrackId, "engine", "Process sucess: " + this.internalLog.ToString());
                }
                catch { }

#if DEBUG
                AddUserLog(dbAux.Connection, LogKey.User_ImportInfo, null, "Engine", UserLogLevel.Debug, 0, 0, 0, this.resourceId, this.pluginId, (userData != null ? userData.EntityId : 0), (userData != null ? userData.IdentityId : 0), "User process status", this.internalLog.ToString());
#endif

                Log("Success");
                return(RegistryProcessStatus.OK);
            }
            catch (Exception ex)
            {
                if (tmp != null)
                {
                    tmp.Stop(dbAux.Connection, null);
                }

                String traceError = "";
                traceError += "Erro: " + ex.Message + ex.StackTrace;

                Log("Erro: " + ex.Message);
                if (ex.InnerException != null)
                {
                    Log("Erro: " + ex.InnerException.Message);
                }

#if DEBUG
                Log("StackTrace: " + ex.StackTrace);
#endif

                if (showError)
                {
                    if (ex is SqlException)
                    {
                        AddUserLog(dbAux.Connection, LogKey.User_ImportError, null, "Engine", UserLogLevel.Error, 0, 0, 0, this.resourceId, this.pluginId, (userData != null ? userData.EntityId : 0), (userData != null ? userData.IdentityId : 0), ex.Message, SafeTrend.Json.JSON.Serialize2(new { import_id = importId, package_id = packageId, db_laet_error = LastDBError }));
                    }
                    else
                    {
                        AddUserLog(dbAux.Connection, LogKey.User_ImportError, null, "Engine", UserLogLevel.Error, 0, 0, 0, this.resourceId, this.pluginId, (userData != null ? userData.EntityId : 0), (userData != null ? userData.IdentityId : 0), ex.Message, SafeTrend.Json.JSON.Serialize2(new { import_id = importId, package_id = packageId, trace_error = traceError }));
                    }
                }

                try
                {
                    dbAux.AddPackageTrack(this.packageTrackId, "engine", "Process error: " + SafeTrend.Json.JSON.Serialize2(new { error_message = ex.Message, error_stack_trace = ex.StackTrace, import_id = importId, package_id = packageId, trace_error = traceError }));
                }
                catch { }

                //Se o erro for de deadlock, mantem o registro na base para ser reprocessado
                if (!(ex is SqlException) || ((ex is SqlException) && (ex.Message.IndexOf("deadlock") == -1)))
                {
                    ExecuteNonQuery(dbAux.Connection, "update collector_imports set status = 'E' where status = 'F' and resource_plugin_id = '" + this.resourcePluginId + "' and  import_id = '" + this.importId + "' and package_id = '" + this.packageId + "'", CommandType.Text, null);
                    ExecuteNonQuery(dbAux.Connection, "delete from collector_imports where status = 'E' and resource_plugin_id = '" + this.resourcePluginId + "' and  import_id = '" + this.importId + "' and package_id = '" + this.packageId + "'", CommandType.Text, null);
                }

                //Console.ReadLine();

                //System.Diagnostics.Process.GetCurrentProcess().Kill();
                //throw ex;


                if (trans != null)
                {
                    trans.Rollback();
                }

                trans = null;

                return(RegistryProcessStatus.Error);
            }
            finally
            {
                Log("End of registry processor");

                if (fieldsData != null)
                {
                    fieldsData.Clear();
                }
                fieldsData = null;
            }
        }
Ejemplo n.º 11
0
        private void TmrCallback(Object o)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            TextLog.Log("Engine", "Importer", "Starting registry processor timer");
            Console.WriteLine("Starting registry processor timer");
            IAMDatabase db        = null;
            Stopwatch   stopWatch = new Stopwatch();

            stopWatch.Start();


            Dictionary <Int64, PluginConfig> resourcePluginCache = new Dictionary <Int64, PluginConfig>();

            StringBuilder procLog  = new StringBuilder();
            Boolean       writeLog = false;

            last_status = "Iniciando...";
            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 600;
                //db.Debug = true;

                Console.WriteLine("Select data...");

                Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.Indeterminate);
                startTime = DateTime.Now;
                newUsers  = 0;
                errors    = 0;
                totalReg  = 0;
                ignored   = 0;
                atualReg  = 0;

                //Seleciona os registros prontos para serem importados
                //Não colocar order neste select, fica extremamente lento
                //Coloca um limite de 500.000 somente p/ não estourar memória
                last_status = "Selecionando registros a serem processados";
                DataTable dtRegs = db.Select("select top 5000 * from vw_collector_imports_regs with(nolock) order by priority desc");

                if (dtRegs == null)
                {
                    TextLog.Log("Engine", "Importer", "\tError on select registries: " + db.LastDBError);
                    db.AddUserLog(LogKey.Engine, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on select registries: " + db.LastDBError);
                    executing = false;
                    return;
                }

                if (dtRegs.Rows.Count == 0)
                {
                    TextLog.Log("Engine", "Importer", "\t0 registers to process");
                    Console.WriteLine("0 registers to process");
                    executing = false;
                    return;
                }

                totalReg = dtRegs.Rows.Count;

                TextLog.Log("Engine", "Importer", "\t" + dtRegs.Rows.Count + " registers to process");
                procLog.AppendLine("[" + DateTime.Now.ToString("o") + "] " + dtRegs.Rows.Count + " registers to process");
                Console.WriteLine(dtRegs.Rows.Count + " registers to process");

                //Carrega todos os logins do sistema
                Console.WriteLine("Fetch logins...");
                last_status = "Listando login do sistema";
                DataTable dtLogins = db.Select("select context_id,id,login from vw_entity_logins2 with(nolock)");
                if ((dtLogins != null) || (dtLogins.Rows.Count > 0))
                {
                    foreach (DataRow dr in dtLogins.Rows)
                    {
                        LoginCache.AddItem((Int64)dr["context_id"], (Int64)dr["id"], dr["login"].ToString());
                    }
                }

                //Carrega todos os e-mails do sistema
                Console.WriteLine("Fetch e-mails...");
                last_status = "Listando e-mails do sistema";
                DataTable dtEmails = db.Select("select context_id, entity_id, mail from vw_entity_mails with(nolock)");
                if ((dtEmails != null) || (dtEmails.Rows.Count > 0))
                {
                    foreach (DataRow dr in dtEmails.Rows)
                    {
                        EmailCache.AddItem((Int64)dr["context_id"], (Int64)dr["entity_id"], dr["mail"].ToString());
                    }
                }


                //Calcula a quantidade de threads com base na quantidade de registros
                Int32 tCount = dtRegs.Rows.Count / 10;

                if (tCount < 1)
                {
                    tCount = 1;
                }
                else if (tCount > this.maxThreads)
                {
                    tCount = this.maxThreads;
                }

#if DEBUG
                tCount = 1;
#endif

                DebugMessage dbgC = new DebugMessage(delegate(String message)
                {
                    procLog.AppendLine(message);
                });



                Console.WriteLine("Starting...");
                queueManager = new QueueManager <RegistryProcessStarter>(tCount, ProcQueue);
                queueManager.OnThreadStart += new QueueManager <RegistryProcessStarter> .StartThread(delegate(Int32 threadIndex)
                {
                    LocalTheadObjects obj = new LocalTheadObjects();
                    for (Int32 t = 0; t <= 10; t++)
                    {
                        try
                        {
                            obj.db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                            obj.db.openDB();
                            obj.db.Timeout = 600;

#if DEBUG
                            //obj.db.Debug = true;
#endif

                            obj.lockRules   = new LockRules();
                            obj.ignoreRules = new IgnoreRules();
                            obj.roleRules   = new RoleRules();
                            obj.lockRules.GetDBConfig(obj.db.Connection);
                            obj.ignoreRules.GetDBConfig(obj.db.Connection);
                            obj.roleRules.GetDBConfig(obj.db.Connection);
                            obj.debugCallback = dbgC;
                            break;
                        }
                        catch (Exception ex) {
                            if (t >= 10)
                            {
                                throw ex;
                            }
                        }
                    }

                    return(obj);
                });

                queueManager.OnThreadStop += new QueueManager <RegistryProcessStarter> .ThreadStop(delegate(Int32 threadIndex, Object state)
                {
                    if ((state != null) && (state is LocalTheadObjects))
                    {
                        ((LocalTheadObjects)state).Dispose();
                    }

                    state = null;
                });


                Console.WriteLine("Starting treads...");
                last_status = "Iniciando treads";
                queueManager.Start();

                if (queueManager.ExecutingCount == 0)
                {
                    throw new Exception("Erro on start queue manager");
                }

                /*
                 * _queue = new RegistryQueue[tCount];
                 * Int32 qIndex = 0;
                 *
                 * for (Int32 i = 0; i < _queue.Length; i++)
                 *  _queue[i] = new RegistryQueue();
                 */

                Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.Normal);
                Taskbar.TaskbarProgress.SetProgressValue(0, (Int32)totalReg, System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle);

                Int32 addCount = 0;
                last_status = "Processando registros";
                foreach (DataRow dr in dtRegs.Rows)
                {
                    Int64 enterpriseId = (Int64)dr["enterprise_id"];
                    Int64 contextId    = (Int64)dr["context_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, "Engine", UserLogLevel.Error, 0, enterpriseId, 0, (Int64)dr["resource_id"], (Int64)dr["plugin_id"], 0, 0, "License error: " + lic.Error);
                        }
                        lic.Notified = true;

                        db.ExecuteNonQuery("update collector_imports set status = 'LE' where status = 'F' and resource_plugin_id = '" + dr["resource_id"] + "' and  import_id = '" + dr["import_id"] + "' and package_id = '" + dr["package_id"] + "'", CommandType.Text, null);

                        continue;
                    }

                    if ((lic.Entities > 0) && (lic.Count > lic.Entities))
                    {
                        if (!lic.Notified)
                        {
                            db.AddUserLog(LogKey.Licence_error, null, "Engine", UserLogLevel.Error, 0, enterpriseId, 0, (Int64)dr["resource_id"], (Int64)dr["plugin_id"], 0, 0, "License error: License limit (" + lic.Entities + " entities) exceeded");
                        }
                        lic.Notified = true;

                        db.ExecuteNonQuery("update collector_imports set status = 'LE' where status = 'F' and resource_plugin_id = '" + dr["resource_id"] + "' and  import_id = '" + dr["import_id"] + "' and package_id = '" + dr["package_id"] + "'", CommandType.Text, null);

                        continue;
                    }


                    if (!entKeys.ContainsKey(enterpriseId))
                    {
                        entKeys.Add(enterpriseId, new EnterpriseKeyConfig(db.Connection, enterpriseId));
                    }

                    if (entKeys[enterpriseId] == null)
                    {
                        entKeys[enterpriseId] = new EnterpriseKeyConfig(db.Connection, enterpriseId);
                    }

                    addCount++;
                    queueManager.AddItem(new RegistryProcessStarter(enterpriseId, contextId, new Uri(dr["plugin_uri"].ToString()), Int64.Parse(dr["resource_id"].ToString()), Int64.Parse(dr["plugin_id"].ToString()), Int64.Parse(dr["resource_plugin_id"].ToString()), (String)dr["import_id"], (String)dr["package_id"], (String)dr["package"]));

                    //A cada 100 registros monitora a CPU para adicionar mais registros
                    //O Objetivo deste processo é controlar a carga de processamento
                    if (addCount >= 100)
                    {
                        addCount = 0;
                        Int32 c = 0;
                        while (((c = queueManager.QueueCount) > 500) || ((getCPUCounter() >= 70) && (c > 0)))
                        {
                            Thread.Sleep(500);
                        }
                    }


                    /*
                     * _queue[qIndex].Add(enterpriseId, contextId, Int64.Parse(dr["plugin_id"].ToString()), (String)dr["plugin_uri"], Int64.Parse(dr["resource_id"].ToString()), (String)dr["import_id"], (String)dr["registry_id"]);
                     *
                     * qIndex++;
                     * if (qIndex > _queue.Length - 1) qIndex = 0;
                     */
                }



                /*
                 * for (Int32 i = 0; i < _queue.Length; i++)
                 * {
                 *  Thread procQueue = new Thread(new ParameterizedThreadStart(ProcQueue));
                 *  procQueue.Start(i);
                 *  //Thread.Sleep(1000);
                 * }*/

                Console.WriteLine("Waiting treads execution...");

                /*
                 * Int64 rest = 0;
                 * Double percent = 0;
                 * Int32 iPercent = 0;
                 * do
                 * {
                 *  rest = 0;
                 *
                 *  rest = queueManager.QueueCount;
                 *
                 *  //for (Int32 i = 0; i < _queue.Length; i++)
                 *  //    rest += _queue[i].Count;
                 *
                 *  percent = ((Double)(totalReg - rest) / (Double)totalReg) * 100F;
                 *
                 *  if (iPercent != (Int32)percent)
                 *  {
                 *      iPercent = (Int32)percent;
                 *      procLog.AppendLine("[" + DateTime.Now.ToString("o") + "] " + iPercent + "%");
                 *      TextLog.Log("Engine", "Importer", "\t" + iPercent + "%");
                 *      Console.Write(" " + iPercent + "% ");
                 *
                 *      Taskbar.TaskbarProgress.SetProgressValue((Int32)(totalReg - rest), (Int32)totalReg, System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle);
                 *
                 *  }
                 *
                 *  Thread.Sleep(1000);
                 *
                 * } while (rest > 0);*/


                //Envia comando para finalizar a execução e aguarda a finalização
                last_status = "Processando registros";
                queueManager.StopAndWait();


                Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.Indeterminate);

                last_status = "Finalizando";
                Console.WriteLine("Finishing...");

                if (dtRegs.Rows.Count > 0)
                {
                    writeLog = true;
                }

                procLog.AppendLine("New users: " + newUsers);
                procLog.AppendLine("Errors: " + errors);
                procLog.AppendLine("Ignored: " + ignored);
                procLog.AppendLine("Updated: " + (totalReg - errors - ignored - newUsers));

                procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Import registry processed with " + dtRegs.Rows.Count + " registers");

                //Joga todos os registros para a tabela de importados
                //e exclui da atual
                db.ExecuteNonQuery("sp_migrate_imported", CommandType.StoredProcedure, null);


                //Reconstroi os índices das tabelas de entidades e identidades
                try
                {
                    db.ExecuteNonQuery("sp_reindex_entity", CommandType.StoredProcedure, null);
                    db.ExecuteNonQuery("sp_rebuild_entity_keys", CommandType.StoredProcedure, null);
                }
                catch { }

                Console.WriteLine("");
            }
            catch (SqlException e)
            {
                procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] DB Error on registry processor: " + e.Message);
                procLog.AppendLine(db.LastDBError);

                db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "DB Error on registry processor", procLog.ToString());
                TextLog.Log("Engine", "Importer", "\tError on registry processor timer " + e.Message + " " + db.LastDBError);
            }
            catch (OutOfMemoryException ex)
            {
                procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Error on registry processor: " + ex.Message);

                db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Out Of Memory processing registry, killing processor", procLog.ToString());
                TextLog.Log("Engine", "Importer", "\tError on registry processor timer " + ex.Message);

                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            catch (Exception ex)
            {
                procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Error on registry processor: " + ex.Message);

                db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on registry processor", procLog.ToString());
                TextLog.Log("Engine", "Importer", "\tError on registry processor timer " + ex.Message);
            }
            finally
            {
                stopWatch.Stop();
                TimeSpan ts = stopWatch.Elapsed;

                executing   = false;
                last_status = "";

                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:0000}", ts.TotalHours, ts.Minutes, ts.Seconds, ts.Milliseconds);
                TextLog.Log("Engine", "Importer", "\tElapsed time: " + elapsedTime);

                TextLog.Log("Engine", "Importer", "\tScheduled for new registry processor in 60 seconds");
                TextLog.Log("Engine", "Importer", "Finishing registry processor timer");

                procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Elapsed time: " + elapsedTime);

                Console.WriteLine("Import registry processed " + procLog.ToString());
                Console.WriteLine("Elapsed time: " + elapsedTime);

                if (writeLog)
                {
                    db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Import registry processed", procLog.ToString());
                }

                Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.NoProgress);

                startTime = new DateTime(1970, 1, 1);

                try
                {
                    List <Int64> keys = new List <Int64>();
                    if ((entKeys != null) && (entKeys.Count > 0))
                    {
                        keys.AddRange(entKeys.Keys);
                        foreach (Int64 k in keys)
                        {
                            try
                            {
                                if (entKeys[k] != null)
                                {
                                    entKeys[k].Dispose();
                                    entKeys[k] = null;
                                }
                            }
                            catch { }
                            try
                            {
                                entKeys.Remove(k);
                            }
                            catch { }
                        }
                    }
                }
                catch { }

                try
                {
                    licControl.Clear();
                }
                catch { }

                try
                {
                    LoginCache.Clear();
                }
                catch { }

                if (db != null)
                {
                    db.Dispose();
                }

                db = null;

                Thread.CurrentThread.Abort();
            }
        }
Ejemplo n.º 12
0
        public LoginResult LocalAuth(IAMDatabase database, System.Web.UI.Page page, String username, String password, Boolean byPassPasswordCheck)
        {
            try
            {
                if ((username == null) || (username.Trim() == "") || (username == password) || (username.Trim() == ""))
                {
                    return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd")));
                }

                Int64 enterpriseId = 0;
                if ((page.Session["enterprise_data"]) != null && (page.Session["enterprise_data"] is EnterpriseData))
                {
                    enterpriseId = ((EnterpriseData)page.Session["enterprise_data"]).Id;
                }

                DbParameterCollection par = new DbParameterCollection();
                par.Add("@enterprise_id", typeof(Int64)).Value           = enterpriseId;
                par.Add("@login", typeof(String), username.Length).Value = username;

                DataTable tmp = null;


                tmp = database.ExecuteDataTable("select distinct id, alias, full_name, login, enterprise_id, password, must_change_password from vw_entity_logins with(nolock) where deleted = 0 and enterprise_id = @enterprise_id and locked = 0 and (login = @login or value = @login)", CommandType.Text, par);

                if ((tmp != null) && (tmp.Rows.Count > 0))
                {
                    foreach (DataRow dr in tmp.Rows)
                    {
                        using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(database.Connection, enterpriseId))
                            using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString())))
                                if (byPassPasswordCheck || Encoding.UTF8.GetString(cApi.clearData) == password)
                                {
                                    Random rnd = new Random();

                                    LoginData l = new LoginData();
                                    l.Alias         = tmp.Rows[0]["alias"].ToString();
                                    l.FullName      = tmp.Rows[0]["full_name"].ToString();
                                    l.Login         = tmp.Rows[0]["login"].ToString();
                                    l.Id            = (Int64)tmp.Rows[0]["id"];
                                    l.EnterpriseId  = (Int64)tmp.Rows[0]["enterprise_id"];
                                    l.SecurityToken = (Byte)rnd.Next(1, 255);

                                    SetLoginSession(page, l);

                                    database.ExecuteNonQuery("update entity set last_login = getdate() where id = " + l.Id, CommandType.Text, null);

                                    database.AddUserLog(LogKey.User_Logged, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, l.Id, 0, MessageResource.GetMessage("user_logged") + " " + GetIPAddress(page), "{ \"ipaddr\":\"" + GetIPAddress(page) + "\"} ");

                                    return(new LoginResult(true, "User OK", (Boolean)tmp.Rows[0]["must_change_password"]));

                                    break;
                                }
                                else
                                {
                                    database.AddUserLog(LogKey.User_WrongPassword, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, (Int64)tmp.Rows[0]["id"], 0, MessageResource.GetMessage("user_wrong_password") + " " + GetIPAddress(page), "{ \"ipaddr\":\"" + GetIPAddress(page) + "\"} ");
                                }
                    }

                    return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd")));
                }
                else
                {
                    database.AddUserLog(LogKey.User_WrongUserAndPassword, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, MessageResource.GetMessage("user_wrong_password") + " " + GetIPAddress(page), "{ \"username\":\"" + username.Replace("'", "").Replace("\"", "") + "\", \"ipaddr\":\"" + GetIPAddress(page) + "\"} ");
                    return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd")));
                }
            }
            catch (Exception ex)
            {
                //Tools.Tool.notifyException(ex, page);
                return(new LoginResult(false, "Internal error", ex.Message));
            }
            finally
            {
            }
        }