예제 #1
0
        public IAMDbUpdate(String server, String dbName, String username, String password)
        {
            scripts = UpdateScriptRepository.GetScriptsBySqlProviderName("System.Data.SqlClient");

            if ((scripts == null) || (scripts.Count <IUpdateScript>() == 0))
            {
                return;
            }

            foreach (IUpdateScript s in scripts)
            {
                if ((Int64)s.Serial > updateSerial)
                {
                    updateSerial = (Int64)s.Serial;
                }
            }

            this.db = new IAMDatabase(server, dbName, username, password);

            //Verifica se a base de dados está atualizada
            try
            {
                this.serial = db.ExecuteScalar <Int64>("select isnull(max([version]),0) from [db_ver]");
            }
            catch
            {
                this.serial = 0;
            }
        }
예제 #2
0
        private void SaveToSend(Int64 enterpriseId, DirectoryInfo saveTo, ProxyConfig config, List <PluginConnectorBaseDeployPackage> packages)
        {
            if ((packages == null) || (packages.Count == 0))
            {
                return;
            }

            Byte[] jData    = Encoding.UTF8.GetBytes(SafeTrend.Json.JSON.Serialize <List <PluginConnectorBaseDeployPackage> >(packages));
            String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));

            using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass), jData))
            {
                if (!saveTo.Exists)
                {
                    saveTo.Create();
                }

                FileInfo f = new FileInfo(Path.Combine(saveTo.FullName, DateTime.Now.ToString("yyyyMMddHHmss-ffffff")) + ".iamdat");

                File.WriteAllBytes(f.FullName, cApi.ToBytes());



                foreach (PluginConnectorBaseDeployPackage pkg in packages)
                {
                    try
                    {
                        //db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Debug, 0, enterpriseId, 0, 0, 0, pkg.entityId, pkg.identityId, "Saving package ID: " + pkg.pkgId, SafeTrend.Json.JSON.Serialize<PluginConnectorBaseDeployPackage>(pkg));

                        String tpkg = SafeTrend.Json.JSON.Serialize <PluginConnectorBaseDeployPackage>(pkg);

                        DbParameterCollection par = new DbParameterCollection();
                        par.Add("@entity_id", typeof(Int64)).Value = pkg.entityId;
                        par.Add("@date", typeof(DateTime)).Value   = DateTime.Now;
                        par.Add("@flow", typeof(String)).Value     = "deploy";
                        par.Add("@package_id", typeof(String), pkg.pkgId.Length).Value = pkg.pkgId;
                        par.Add("@filename", typeof(String), f.FullName.Length).Value  = f.FullName;
                        par.Add("@package", typeof(String), tpkg.Length).Value         = tpkg;

                        Int64 trackId = db.ExecuteScalar <Int64>("sp_new_package_track", System.Data.CommandType.StoredProcedure, par, null);

                        tpkg = null;

                        db.AddPackageTrack(trackId, "deploy", "Package generated");
                    }
                    catch { }
                }


#if DEBUG
                db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, 0, 0, "File to send created " + f.Name + " (" + packages.Count + ")");
#endif
            }
        }
예제 #3
0
        public void BuildCertificates()
        {
            //Cria os certificados digitais

            //firstEnterprise
            Int64 enterpriseCount = db.ExecuteScalar <Int64>("select count(*) from [enterprise]", CommandType.Text, null, null);

            if (enterpriseCount > 0)
            {
                firstEnterprise = false;
            }

            EnterpriseKey ent = new EnterpriseKey(new Uri("//" + this.fqdn), this.name, firstEnterprise);

            ent.BuildCerts(); //Cria os certificados

            this.ServerPKCS12Cert = ent.ServerPKCS12Cert;
            this.ServerCert       = ent.ServerCert;
            this.ClientPKCS12Cert = ent.ClientPKCS12Cert;
        }
예제 #4
0
파일: sync.aspx.cs 프로젝트: radtek/safeid
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!EnterpriseIdentify.Identify(Page, false, true)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                Page.Response.Status     = "403 Access denied";
                Page.Response.StatusCode = 403;
                Page.Response.End();
                return;
            }
            else
            {
                String proxyName = "";
                String version   = "";
                Int32  pid       = 0;
                try
                {
                    proxyName = Request.Headers["X-SAFEID-PROXY"];
                }
                catch { }

                try
                {
                    version = Request.Headers["X-SAFEID-VERSION"];
                }
                catch { }

                try
                {
                    pid = Int32.Parse(Request.Headers["X-SAFEID-PID"]);
                }
                catch { }

                if (String.IsNullOrEmpty(proxyName))
                {
                    Page.Response.Status     = "403 Access denied";
                    Page.Response.StatusCode = 403;
                    Page.Response.End();
                    return;
                }

                Int32   files   = 0;
                Int32   rConfig = 0;
                Int32   fetch   = 0;
                Boolean restart = false;
                try
                {
                    using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        using (ServerDBConfig c = new ServerDBConfig(db.Connection))
                        {
                            ProxyConfig config = new ProxyConfig();
                            config.GetDBConfig(db.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, proxyName);

                            if (config.fqdn != null) //Encontrou o proxy
                            {
                                DirectoryInfo outDir = null;


                                outDir = new DirectoryInfo(Path.Combine(c.GetItem("outboundFiles"), config.proxyID + "_" + config.proxy_name));

                                if (!outDir.Exists)
                                {
                                    outDir.Create();
                                }

                                files = outDir.GetDirectories().Length;

                                if (config.forceDownloadConfig)
                                {
                                    rConfig++;
                                }

                                //Verifica fetch
                                try
                                {
                                    fetch = db.ExecuteScalar <Int32>("select COUNT(*) from resource_plugin_fetch f with(nolock) inner join resource_plugin rp  with(nolock) on rp.id = f.resource_plugin_id inner join resource r  with(nolock) on r.id = rp.resource_id where f.response_date is null and proxy_id = " + config.proxyID, System.Data.CommandType.Text, null);
                                }
                                catch { }

                                try
                                {
                                    restart = db.ExecuteScalar <Boolean>("select restart from proxy where id = " + config.proxyID, System.Data.CommandType.Text, null);
                                }
                                catch { }

                                try
                                {
                                    db.ExecuteNonQuery("update proxy set restart = 0 where id = " + config.proxyID, System.Data.CommandType.Text, null);
                                }
                                catch {
                                    restart = false;
                                }



                                db.ExecuteNonQuery("update proxy set last_sync = getdate(), pid = " + pid + ", address = '" + Tools.Tool.GetIPAddress() + "', config = 0, version = '" + version + "' where id = " + config.proxyID, System.Data.CommandType.Text, null);
                            }
                            else
                            {
                                db.AddUserLog(LogKey.API_Error, DateTime.Now, "ProxyAPI", UserLogLevel.Warning, 0, ((EnterpriseData)Page.Session["enterprise_data"]).Id, 0, 0, 0, 0, 0, "Proxy not found " + proxyName);
                                Page.Response.Status     = "403 Access denied";
                                Page.Response.StatusCode = 403;
                                return;
                            }
                        }
                }
                catch (Exception ex)
                {
                    Tools.Tool.notifyException(ex, this);
                    //throw ex;
                }

                Page.Response.HeaderEncoding = Encoding.UTF8;
                ReturnHolder.Controls.Add(new LiteralControl("{\"config\":" + rConfig + ",\"files\":" + files + ",\"fetch\":" + fetch + ",\"restart\":" + (restart ? "1" : "0") + "}"));
            }
        }
예제 #5
0
        /// <summary>
        /// Método privado para processamento do método 'user.resetpassword'
        /// </summary>
        /// <param name="sqlConnection">Conexão com o banco de dados MS-SQL</param>
        /// <param name="parameters">Dicionário (String, Object) contendo todos os parâmetros necessários</param>
        private List <Object> accessrequestlist(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            List <Object> result = new List <Object>();

            DbParameterCollection par = new DbParameterCollection();

            par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId;

            Int32 page     = 1;
            Int32 pageSize = 10;

            if (parameters.ContainsKey("page"))
            {
                Int32.TryParse(parameters["page"].ToString(), out page);
            }

            if (parameters.ContainsKey("page_size"))
            {
                Int32.TryParse(parameters["page_size"].ToString(), out pageSize);
            }

            if (pageSize < 1)
            {
                pageSize = 1;
            }

            if (page < 1)
            {
                page = 1;
            }

            Int32 rStart = ((page - 1) * pageSize) + 1;
            Int32 rEnd   = rStart + (pageSize - 1);

            /*
             * select * from st_workflow_request r with(nolock)
             * inner join entity e  with(nolock) on e.id = r.entity_id
             * inner join context c  with(nolock) on c.id = e.context_id
             * */
            String sql = "";

            sql += "WITH result_set AS (";
            sql += "  SELECT ";
            sql += "    ROW_NUMBER() OVER (ORDER BY r.create_date) AS [row_number], r.*, e.context_id, c.enterprise_id, e.full_name, e.login";
            sql += "     from st_workflow_request r with(nolock)  ";
            sql += "     inner join entity e  with(nolock) on e.id = r.entity_id   ";
            sql += "     inner join context c  with(nolock) on c.id = e.context_id  ";
            sql += "     where (c.enterprise_id = @enterprise_id ";

            if ((parameters.ContainsKey("filter")) && (parameters["filter"] is Dictionary <String, Object>))
            {
                Dictionary <String, Object> filter = (Dictionary <String, Object>)parameters["filter"];
                foreach (String k in filter.Keys)
                {
                    switch (k.ToLower())
                    {
                    case "text":
                        if (!String.IsNullOrWhiteSpace(filter["text"].ToString()))
                        {
                            par.Add("@text", typeof(String)).Value = filter["text"].ToString();
                            sql += " and (e.full_name like '%'+@text+'%' or e.login like '%'+@text+'%' or r.description like '%'+@text+'%')";
                        }
                        break;

                    case "contextid":
                        if (!String.IsNullOrWhiteSpace(filter["contextid"].ToString()))
                        {
                            try
                            {
                                Int64 tmp = Int64.Parse(filter["contextid"].ToString());
                                par.Add("@context_id", typeof(Int64)).Value = tmp;
                                sql += " and c.id = @context_id";
                            }
                            catch { }
                        }
                        break;

                    case "workflowid":
                        if (!String.IsNullOrWhiteSpace(filter["workflowid"].ToString()))
                        {
                            try
                            {
                                Int64 tmp = Int64.Parse(filter["workflowid"].ToString());
                                par.Add("@workflow_id", typeof(Int64)).Value = tmp;
                                sql += " and r.workflow_id = @workflow_id";
                            }
                            catch { }
                        }
                        break;

                    case "status":
                        if (!String.IsNullOrWhiteSpace(filter["status"].ToString()))
                        {
                            try
                            {
                                WorkflowRequestStatus tmp = (WorkflowRequestStatus)Int32.Parse(filter["status"].ToString());
                                par.Add("@status", typeof(Int32)).Value = (Int32)tmp;
                                sql += " and r.status = @status";
                            }
                            catch { }
                        }
                        break;
                    }
                }
            }

            sql += "     )";
            sql += ") SELECT";
            sql += "  *";
            sql += " FROM";
            sql += "  result_set";
            sql += " WHERE";
            sql += "  [row_number] BETWEEN " + rStart + " AND " + rEnd;

            DataTable dtRequest = database.ExecuteDataTable(sql, CommandType.Text, par, null);

            if ((dtRequest != null) && (dtRequest.Rows.Count > 0))
            {
                foreach (DataRow dr1 in dtRequest.Rows)
                {
                    using (IAMRBAC rbac = new IAMRBAC())
                        if (!rbac.UserAdmin(database, Acl.EntityId, this._enterpriseId))
                        {
                            using (WorkflowRequest request = new WorkflowRequest((Int64)dr1["id"]))
                            {
                                WorkflowRequestProccess proc = request.GetInicialData(database);
                                if (!proc.Success)
                                {
                                    Error(ErrorType.InternalError, proc.Message, proc.Debug, null);
                                    return(null);
                                }

                                if (!database.ExecuteScalar <Boolean>("select case when COUNT(*) > 0 then CAST(1 as bit) else CAST(0 as bit) end from entity e with(nolock) where e.id = " + Acl.EntityId + " and (e.id in (" + request.Workflow.Owner + "," + request.Activity.ManualApproval.EntityApprover + ") or e.id in (select i.entity_id from identity_role ir with(nolock) inner join [identity] i with(nolock) on i.id = ir.identity_id where ir.role_id = " + request.Activity.ManualApproval.RoleApprover + "))", CommandType.Text, null))
                                {
                                    continue;
                                }
                            }
                        }

                    Dictionary <string, object> newItem = new Dictionary <string, object>();
                    newItem.Add("access_request_id", dr1["id"]);
                    newItem.Add("userid", dr1["entity_id"]);
                    newItem.Add("context_id", dr1["context_id"]);
                    newItem.Add("enterprise_id", dr1["enterprise_id"]);
                    newItem.Add("workflow_id", dr1["workflow_id"]);
                    newItem.Add("status", dr1["status"]);
                    newItem.Add("description", dr1["description"]);
                    newItem.Add("entity_full_name", dr1["full_name"]);
                    newItem.Add("entity_login", dr1["login"]);
                    newItem.Add("deployed", dr1["deployed"]);
                    newItem.Add("start_date", (dr1["start_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["start_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));
                    newItem.Add("end_date", (dr1["end_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["end_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));
                    newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));

                    WorkflowConfig wk = new WorkflowConfig();
                    wk.GetDatabaseData(database, (Int64)dr1["workflow_id"]);

                    newItem.Add("workflow", wk.ToJsonObject());

                    result.Add(newItem);
                }
            }

            return(result);
        }
예제 #6
0
        private void startInstall()
        {
            Application.DoEvents();

            Boolean success = false;

            txtCheckConfig.Text = "Iniciando instalação" + Environment.NewLine;


            IAMDatabase db = null;

            try
            {
                txtCheckConfig.Text += "Definindo variáveis de ambiente: ";
                Application.DoEvents();
                DirectoryInfo appDir = new DirectoryInfo(Environment.CurrentDirectory);

                try
                {
                    appDir = new DirectoryInfo(args[0]);
                }
                catch { }
                txtCheckConfig.Text += "OK" + Environment.NewLine;
                txtCheckConfig.Text += "\tDiretório de execução: " + appDir.FullName + Environment.NewLine;

                Application.DoEvents();

                txtCheckConfig.Text += "Conectando no banco de dados: ";
                Application.DoEvents();

                if (txtDatabase.Text.Trim().ToLower() == "master")
                {
                    throw new Exception("Não pode ser utilizado a base de dados Master");
                }

                db = new IAMDatabase(txtDbServer.Text, txtDatabase.Text, txtUsername.Text, txtPassword.Text);

                db.openDB();

                txtCheckConfig.Text += "OK" + Environment.NewLine;
                Application.DoEvents();

                //##############################
                //Estrutura de dados
                txtCheckConfig.Text += "Criando estrutura de dados: ";
                Application.DoEvents();

                //Verifica se a base de dados está sendo utilizada
                Int64 tableCount = db.ExecuteScalar <Int64>("SELECT cast(COUNT(*) as bigint) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo'");

                if (tableCount > 0)
                {
                    if (MessageBox.Show("A base de dados " + txtDatabase.Text + " contém " + tableCount + " tabelas e aparentemente está sendo utilizado por outra aplicação.\r\n\r\nDeseja continuar a instalação nesta base?", "Deseja continuar a instalação?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                    {
                        throw new Exception("Cancelado pelo usuário");
                    }
                }

                Object trans = db.BeginTransaction();
                try
                {
                    using (IAMDbInstall dbCreate = new IAMDbInstall(db))
                        dbCreate.Create(trans);

                    db.Commit();
                }
                catch (Exception ex)
                {
                    db.Rollback();
                    throw ex;
                }
                txtCheckConfig.Text += "OK" + Environment.NewLine;
                Application.DoEvents();

                //##############################
                //Verificvando existência de outras empresas
                txtCheckConfig.Text += "Verificando configuração existente: ";

                Int64 enterpriseCount = db.ExecuteScalar <Int64>("SELECT cast(COUNT(*) as bigint) FROM enterprise");
                if (enterpriseCount > 0)
                {
                    throw new Exception("Base de dados com informações de outras empresas.");
                }

                txtCheckConfig.Text += "OK" + Environment.NewLine;
                Application.DoEvents();

                //##############################
                //Atualizando Base de dados
                txtCheckConfig.Text += "Atualizando base de dados: ";
                try
                {
                    using (IAM.GlobalDefs.Update.IAMDbUpdate updt = new IAM.GlobalDefs.Update.IAMDbUpdate(txtDbServer.Text, txtDatabase.Text, txtUsername.Text, txtPassword.Text))
                        updt.Update();

                    txtCheckConfig.Text += "OK" + Environment.NewLine;
                    Application.DoEvents();
                }
                catch (Exception ex)
                {
                    throw new Exception("Falha ao atualizar o banco de dados: " + ex.Message);
                }

                //##############################
                //Finalizando instalação
                txtCheckConfig.Text += "Configurando diretórios: ";
                Application.DoEvents();

                db.ExecuteNonQuery("delete from server_config where data_name = 'pluginFolder'; insert into server_config (data_name, data_value) values ('pluginFolder','" + Path.Combine(appDir.FullName, "IAMServer\\Plugins") + "')");
                db.ExecuteNonQuery("delete from server_config where data_name = 'inboundFiles'; insert into server_config (data_name, data_value) values ('inboundFiles','" + Path.Combine(appDir.FullName, "IAMServer\\In") + "')");
                db.ExecuteNonQuery("delete from server_config where data_name = 'outboundFiles'; insert into server_config (data_name, data_value) values ('outboundFiles','" + Path.Combine(appDir.FullName, "IAMServer\\Out") + "')");

                txtCheckConfig.Text += "OK" + Environment.NewLine;
                Application.DoEvents();

                //##############################
                //Certificados e chaves de instalação
                txtCheckConfig.Text += "Gerando chave de instalação: ";
                Application.DoEvents();

                using (ServerKey2 sk = new ServerKey2(db.Connection))
                    sk.RenewCert(db.Connection);
                txtCheckConfig.Text += "OK" + Environment.NewLine;
                Application.DoEvents();


                //##############################
                //Criando a empresa
                txtCheckConfig.Text += "Criando empresa: ";
                Application.DoEvents();

                Creator creator = new Creator(db, txtName.Text.Trim(), txtUri.Text.Trim(), "pt-BR");
                creator.BuildCertificates();
                creator.Commit();

                txtCheckConfig.Text += "OK" + Environment.NewLine;
                Application.DoEvents();

                //##############################
                //Criando a empresa
                txtCheckConfig.Text += "Criando arquivos de configuração: ";
                Application.DoEvents();

                FileInfo serverFile = new FileInfo(Path.Combine(appDir.FullName, "IAMServer\\server.conf"));

                if (serverFile.Exists)
                {
                    serverFile.Delete();
                }

                WriteToFile(serverFile, "sqlserver=" + txtDbServer.Text.Trim() + Environment.NewLine);
                WriteToFile(serverFile, "sqldb=" + txtDatabase.Text.Trim() + Environment.NewLine);
                WriteToFile(serverFile, "sqlusername="******"sqlpassword="******"enginemaxthreads=30" + Environment.NewLine);

                //Web.config
                FileInfo webConfigFile = new FileInfo(Path.Combine(appDir.FullName, "IAMServer\\web\\web.config"));

                if (webConfigFile.Exists)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(webConfigFile.FullName);

                    //get root element
                    System.Xml.XmlElement Root = doc.DocumentElement;

                    XmlNode connectionStringsNode = Root["connectionStrings"];
                    foreach (XmlNode cs in connectionStringsNode.ChildNodes)
                    {
                        Boolean update = false;
                        foreach (XmlAttribute att in cs.Attributes)
                        {
                            if (att.Name.ToLower() == "name" && att.Value.ToLower() == "iamdatabase")
                            {
                                update = true;
                            }
                        }

                        if (update)
                        {
                            foreach (XmlAttribute att in cs.Attributes)
                            {
                                if (att.Name.ToLower() == "connectionstring")
                                {
                                    att.Value = db.ConnectionString;
                                }
                            }
                        }
                    }

                    doc.Save(webConfigFile.FullName);
                    doc = null;
                }

                txtCheckConfig.Text += "OK" + Environment.NewLine;
                Application.DoEvents();

                success = true;
            }
            catch (Exception ex)
            {
                success = false;

                txtCheckConfig.Text += "ERRO" + Environment.NewLine;
                txtCheckConfig.Text += "\t" + ex.Message + Environment.NewLine;
                Application.DoEvents();

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

                if (!success)
                {
                    txtCheckConfig.Text += Environment.NewLine + "PROCESSO ABORTADO!!!" + Environment.NewLine;
                    btnBack.Enabled      = true;
                    btnBack.Visible      = true;
                    btnNext.Text         = "&Avançar >";
                    btnCancel.Enabled    = true;
                }
                else
                {
                    txtCheckConfig.Text += Environment.NewLine + "Instalação realizada com sucesso." + Environment.NewLine;
                    btnCancel.Text       = "Finalizar";
                    btnCancel.Enabled    = true;
                    btnNext.Visible      = false;
                    step = WizardStep.Installed;
                }


                //Localiza e remove todos os arquivos .cer e .pfx deste diretório
                try
                {
                    List <FileInfo> files = new List <FileInfo>();
                    try
                    {
                        files.AddRange(new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*.cer"));
                        files.AddRange(new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*.pfx"));
                    }
                    catch { }

                    try
                    {
                        System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(this.GetType());

                        files.AddRange(new DirectoryInfo(Path.GetDirectoryName(asm.Location)).GetFiles("*.cer"));
                        files.AddRange(new DirectoryInfo(Path.GetDirectoryName(asm.Location)).GetFiles("*.pfx"));
                    }
                    catch { }

                    foreach (FileInfo f in files)
                    {
                        try
                        {
                            f.Delete();
                        }
                        catch { }
                    }
                }
                catch { }
            }
        }
예제 #7
0
        private void WorkflowTimer(Object state)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            startTime = DateTime.Now;

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

                    DataTable dtRequests = db.ExecuteDataTable("select id, workflow_id from [st_workflow_request] r with(nolock) where r.deployed = 0 order by r.create_date");
                    if ((dtRequests != null) && (dtRequests.Rows.Count > 0))
                    {
                        try
                        {
                            TextLog.Log("WorkflowProcessor", "Starting workflow processor timer");

                            foreach (DataRow dr in dtRequests.Rows)
                            {
                                try
                                {
                                    WorkflowRequest request = new WorkflowRequest((Int64)dr["id"]);
                                    request.GetInicialData(db);

                                    WorkflowConfig workflow = new WorkflowConfig();
                                    workflow.GetDatabaseData(db, (Int64)dr["workflow_id"]);

                                    switch (request.Status)
                                    {
                                    case WorkflowRequestStatus.Deny:
                                    case WorkflowRequestStatus.Expired:
                                    case WorkflowRequestStatus.UserCanceled:
                                        //Somente atualiza como deployed, para não ficar verificando
                                        db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        continue;
                                        break;

                                    case WorkflowRequestStatus.Waiting:
                                        //Verifica escalation
                                        DateTime escalation = request.ActivityCreated.AddDays(request.Activity.EscalationDays);
                                        DateTime expired    = request.ActivityCreated.AddDays(request.Activity.ExpirationDays);
                                        if (expired.CompareTo(DateTime.Now) < 0)
                                        {
                                            request.SetStatus(db, WorkflowRequestStatus.Escalated, request.UserId);
                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        }
                                        else if (escalation.CompareTo(DateTime.Now) < 0)
                                        {
                                            request.SetStatus(db, WorkflowRequestStatus.Escalated, request.UserId);
                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        }
                                        break;

                                    case WorkflowRequestStatus.Escalated:
                                        //Verifica escalation
                                        DateTime expired2 = request.ActivityCreated.AddDays(request.Activity.ExpirationDays);
                                        if (expired2.CompareTo(DateTime.Now) < 0)
                                        {
                                            request.SetStatus(db, WorkflowRequestStatus.Expired, request.UserId);
                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        }
                                        break;

                                    case WorkflowRequestStatus.Approved:
                                        //Somente executa alguma ação quando não há mais nenhuma atividade a ser executada
                                        if (request.NextActivity == null)
                                        {
                                            switch (workflow.AccessType)
                                            {
                                            case WorkflowAccessType.RoleGrant:
                                                WorkflowAccessRoleGrant rg = (WorkflowAccessRoleGrant)workflow.Access;
                                                //Seleciona todas as identidades do usuário e adiciona na role

                                                DataTable drIdent = db.ExecuteDataTable("select i.* from [identity] i with(nolock) inner join resource_plugin rp with(nolock) on i.resource_plugin_id = rp.id where rp.enable_import = 1 and rp.permit_add_entity = 1 and i.entity_id = " + request.UserId);
                                                if ((drIdent == null) || (drIdent.Rows.Count == 0))
                                                {
                                                    using (DbParameterCollection par2 = new DbParameterCollection())
                                                    {
                                                        par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                        par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                        par2.Add("@description", typeof(String)).Value          = "No inbound identity found for allow access";
                                                        par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                        par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                        db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                    }
                                                }
                                                else
                                                {
                                                    //Lista o nome e id de todas as roles que serão utilizadas
                                                    List <String> roleList = new List <String>();
                                                    foreach (Int64 r in rg.Roles)
                                                    {
                                                        roleList.Add(r.ToString());
                                                    }

                                                    DataTable drRoles = db.ExecuteDataTable("select * from [role] where id in (" + String.Join(",", roleList) + ")");
                                                    if ((drRoles == null) || (drRoles.Rows.Count == 0))
                                                    {
                                                        using (DbParameterCollection par2 = new DbParameterCollection())
                                                        {
                                                            par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                            par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                            par2.Add("@description", typeof(String)).Value          = "No role found for allow access";
                                                            par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                            par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                            db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        String roleNames = "";

                                                        //Adiciona as roles
                                                        foreach (DataRow dr2 in drIdent.Rows)
                                                        {
                                                            foreach (DataRow drRole in drRoles.Rows)
                                                            {
                                                                DbParameterCollection par = new DbParameterCollection();
                                                                par.Add("@identity_id", typeof(Int64)).Value = dr2["id"];
                                                                par.Add("@role_id", typeof(Int64)).Value     = drRole["id"];

                                                                Boolean added = db.ExecuteScalar <Boolean>("sp_insert_identity_role", CommandType.StoredProcedure, par);

                                                                if (added)
                                                                {
                                                                    roleNames += drRole["name"] + Environment.NewLine;
                                                                }
                                                            }
                                                        }

                                                        if (roleNames != null)
                                                        {
                                                            db.AddUserLog(LogKey.User_IdentityRoleBind, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, request.UserId, 0, "Entity bind to roles by workflow access request", roleNames);
                                                        }


                                                        using (DbParameterCollection par2 = new DbParameterCollection())
                                                        {
                                                            par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                            par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                            par2.Add("@description", typeof(String)).Value          = "Entity bind to roles";
                                                            par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                            par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                            db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                        }
                                                    }
                                                }

                                                db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                                break;
                                            }
                                        }
                                        break;

                                    case WorkflowRequestStatus.Revoked:
                                        //Remove as permissões dadas
                                        switch (workflow.AccessType)
                                        {
                                        case WorkflowAccessType.RoleGrant:
                                            WorkflowAccessRoleGrant rg = (WorkflowAccessRoleGrant)workflow.Access;

                                            //Lista o nome e id de todas as roles que serão utilizadas
                                            List <String> roleList = new List <String>();
                                            foreach (Int64 r in rg.Roles)
                                            {
                                                roleList.Add(r.ToString());
                                            }

                                            String log = "";

                                            DataTable drRoles = db.ExecuteDataTable("select distinct ir.*, r.name role_name from [role] r with(nolock) inner join identity_role ir with(nolock) on ir.role_id = r.id inner join [identity] i with(nolock) on ir.identity_id = i.id where i.entity_id = " + request.UserId + " and r.id in (" + String.Join(",", roleList) + ")");
                                            if ((drRoles != null) && (drRoles.Rows.Count > 0))
                                            {
                                                foreach (DataRow dr2 in drRoles.Rows)
                                                {
                                                    log += "Identity unbind to role " + dr2["role_name"] + Environment.NewLine;

                                                    db.AddUserLog(LogKey.User_IdentityRoleUnbind, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, request.UserId, (Int64)dr2["identity_id"], "Identity unbind to role " + dr2["role_name"]);
                                                    db.ExecuteNonQuery("delete from identity_role where identity_id = " + dr2["identity_id"] + " and role_id = " + dr2["role_id"], CommandType.Text, null);
                                                }

                                                using (DbParameterCollection par2 = new DbParameterCollection())
                                                {
                                                    par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                    par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                    par2.Add("@description", typeof(String)).Value          = log;
                                                    par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                    par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                    db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                }
                                            }
                                            else
                                            {
                                                using (DbParameterCollection par2 = new DbParameterCollection())
                                                {
                                                    par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                    par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                    par2.Add("@description", typeof(String)).Value          = "No permission to remove";
                                                    par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                    par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                    db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                }
                                            }

                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                            break;
                                        }
                                        break;

                                    case WorkflowRequestStatus.UnderReview:
                                        //Nada
                                        break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    db.AddUserLog(LogKey.Workflow, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Workflow proccess error", ex.Message);
                                }
                            }
                        }
                        finally
                        {
                            if (db != null)
                            {
                                db.Dispose();
                            }

                            TextLog.Log("WorkflowProcessor", "Finishing workflow processor timer");
                        }
                    }

                    db.closeDB();
                }
                finally
                {
                    if (db != null)
                    {
                        db.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                TextLog.Log("WorkflowProcessor", "Error on message timer " + ex.Message);
            }
            finally
            {
                executing   = false;
                last_status = "";
                startTime   = new DateTime(1970, 1, 1);
            }
        }
예제 #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Request.InputStream.Position = 0;

            try
            {
                JSONRequest req = JSON.GetRequest(Request.InputStream);

                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    ProxyConfig config = new ProxyConfig(true);
                    config.GetDBConfig(database.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host);

                    if (config.fqdn != null) //Encontrou o proxy
                    {
                        DirectoryInfo inDir = null;

                        using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                            inDir = new DirectoryInfo(c.GetItem("inboundFiles"));

                        if (!inDir.Exists)
                        {
                            inDir.Create();
                        }

                        req.enterpriseid = ((EnterpriseData)Page.Session["enterprise_data"]).Id.ToString();

                        String filename = config.proxy_name + "-" + DateTime.Now.ToString("yyyyMMddHHmmss-ffffff") + ".iamreq";


                        if (String.IsNullOrEmpty(req.filename))
                        {
                            req.filename = "Empty";
                        }

                        StringBuilder trackData = new StringBuilder();
                        trackData.AppendLine("Proxy: " + req.host);
                        trackData.AppendLine("Enterprise ID: " + req.enterpriseid);
                        trackData.AppendLine("Proxy filename: " + req.filename);
                        trackData.AppendLine("Saved filename: " + filename);

                        UserLogLevel level = UserLogLevel.Info;

                        trackData.AppendLine("");
                        trackData.AppendLine("Checking package...");

                        if (String.IsNullOrEmpty(req.data))
                        {
                            throw new Exception("Request data is empty");
                        }

                        Byte[] rData = Convert.FromBase64String(req.data);

                        if (!String.IsNullOrEmpty(req.sha1hash))
                        {
                            if (!CATools.SHA1CheckHash(rData, req.sha1hash))
                            {
                                throw new Exception("SHA1 Checksum is not equal");
                            }
                        }

                        String type = "";
                        try
                        {
                            JsonGeneric jData = new JsonGeneric();
                            try
                            {
                                String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));
                                if (String.IsNullOrEmpty(config.server_pkcs12_cert))
                                {
                                    throw new Exception("Server PKCS12 from proxy config is empty");
                                }

                                using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.server_pkcs12_cert), certPass), rData))
                                    jData.FromJsonBytes(cApi.clearData);
                            }
                            catch (Exception ex)
                            {
                                jData = null;
                                trackData.AppendLine("Error decrypting package data for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message);

#if DEBUG
                                trackData.AppendLine(ex.StackTrace);
#endif
                            }

                            if (jData != null)
                            {
#if DEBUG
                                trackData.AppendLine("");
                                trackData.AppendLine("Request data:");
                                trackData.AppendLine(jData.ToJsonString());

                                trackData.AppendLine("");
#endif

                                type = jData.function;

                                trackData.AppendLine("Type: " + type);
                                trackData.AppendLine("Data array length: " + (jData.data == null ? "0" : jData.data.Count.ToString()));

                                if (type.ToLower() == "processimportv2")
                                {
                                    Int32 d = 1;
                                    foreach (String[] dr in jData.data)
                                    {
                                        try
                                        {
                                            Int32 resourcePluginCol = jData.GetKeyIndex("resource_plugin");
                                            Int32 pkgCol            = jData.GetKeyIndex("package");

                                            if (resourcePluginCol == -1)
                                            {
                                                trackData.AppendLine("[Package data " + d + "] Erro finding column 'resource_plugin'");
                                            }

                                            if (pkgCol == -1)
                                            {
                                                trackData.AppendLine("[Package data " + d + "] Erro finding column 'package'");
                                            }

                                            if ((resourcePluginCol != -1) && (pkgCol != -1))
                                            {
                                                PluginConnectorBaseImportPackageUser pkg = JSON.DeserializeFromBase64 <PluginConnectorBaseImportPackageUser>(dr[pkgCol]);
                                                trackData.AppendLine("[Package data " + d + "] Import id: " + pkg.importId);
                                                trackData.AppendLine("[Package data " + d + "] Package id: " + pkg.pkgId);

                                                Int64 trackId = 0;
                                                try
                                                {
                                                    String tpkg = JSON.Serialize2(pkg);

                                                    DbParameterCollection par = new DbParameterCollection();
                                                    par.Add("@entity_id", typeof(Int64)).Value = 0;
                                                    par.Add("@date", typeof(DateTime)).Value   = pkg.GetBuildDate();
                                                    par.Add("@flow", typeof(String)).Value     = "inbound";
                                                    par.Add("@package_id", typeof(String), pkg.pkgId.Length).Value = pkg.pkgId;
                                                    par.Add("@filename", typeof(String)).Value             = req.filename;
                                                    par.Add("@package", typeof(String), tpkg.Length).Value = tpkg;

                                                    trackId = database.ExecuteScalar <Int64>("sp_new_package_track", System.Data.CommandType.StoredProcedure, par, null);

                                                    trackData.AppendLine("[Package data " + d + "] Package track id: " + trackId);

                                                    tpkg = null;

                                                    if (trackId > 0)
                                                    {
                                                        database.AddPackageTrack(trackId, "ProxyAPI", "Package received from proxy and saved at " + filename);
                                                    }
                                                }
                                                catch (Exception ex3) {
                                                    trackData.AppendLine("[Package data " + d + "] Erro generating package track: " + ex3.Message);
                                                }


                                                pkg.Dispose();
                                                pkg = null;
                                            }
                                        }
                                        catch (Exception ex2)
                                        {
                                            trackData.AppendLine("[Package data " + d + "] Erro parsing package data " + ex2.Message);
                                        }
                                        d++;
                                    }
                                }
                            }
                        }
                        catch (Exception ex1) {
                            trackData.AppendLine("Erro parsing package " + ex1.Message);
                            level = UserLogLevel.Error;
                        }

                        database.AddUserLog(LogKey.API_Log, DateTime.Now, "ProxyAPI", level, 0, ((EnterpriseData)Page.Session["enterprise_data"]).Id, 0, 0, 0, 0, 0, "File received from proxy " + req.host + (String.IsNullOrEmpty(type) ? "" : " (" + type + ")"), trackData.ToString());


                        File.WriteAllBytes(Path.Combine(inDir.FullName, filename), Encoding.UTF8.GetBytes(JSON.Serialize <JSONRequest>(req)));

                        ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", "Request received and proxy finded (" + (req.data != null ? req.data.Length.ToString() : "0") + ")")));
                    }
                }
            }
            catch (Exception ex) {
                Tools.Tool.notifyException(ex);
                throw ex;
            }
        }
예제 #9
0
        public WorkflowRequestProccess SetStatus(IAMDatabase database, WorkflowRequestStatus status, Int64 executing_user)
        {
            WorkflowRequestProccess initial = GetInicialData(database);

            if (!initial.Success)
            {
                return(initial);
            }

            //Verifica se o usuário atual faz parte do grupo de aprovadores
            if (!database.ExecuteScalar <Boolean>("select case when COUNT(*) > 0 then CAST(1 as bit) else CAST(0 as bit) end from entity e with(nolock) where e.id in (" + workflow.Owner + "," + activity.ManualApproval.EntityApprover + ") or e.id in (select i.entity_id from identity_role ir with(nolock) inner join [identity] i with(nolock) on i.id = ir.identity_id where ir.role_id = " + activity.ManualApproval.RoleApprover + ")", CommandType.Text, null))
            {
                return(new WorkflowRequestProccess(false, "Access denied. You are not part of the group of approvers users"));
            }

            Object trans = database.BeginTransaction();

            try
            {
                String changeTextAdmin = "";
                String changeText      = "";

                changeText = activity.Name + " " + MessageResource.GetMessage("wf_" + status.ToString().ToLower(), status.ToString());

                using (DbParameterCollection par2 = new DbParameterCollection())
                {
                    //Só altera o status do ítem ptincipal quando a aprovação for da última activity
                    if ((status == WorkflowRequestStatus.Approved) && (nextActivity == null))
                    {
                        par2.Add("@request_id", typeof(Int64)).Value = this.workflow_request_id;
                        par2.Add("@status", typeof(Int32)).Value     = (Int32)status;
                        database.ExecuteNonQuery("UPDATE [st_workflow_request] SET [status] = @status, deployed = 0 WHERE ID = @request_id", CommandType.Text, par2, trans);
                    }
                    else if (status == WorkflowRequestStatus.Approved)
                    {
                        par2.Add("@request_id", typeof(Int64)).Value = this.workflow_request_id;
                        database.ExecuteNonQuery("UPDATE [st_workflow_request] SET deployed = 0 WHERE ID = @request_id", CommandType.Text, par2, trans);
                    }
                    else
                    {
                        par2.Add("@request_id", typeof(Int64)).Value = this.workflow_request_id;
                        par2.Add("@status", typeof(Int32)).Value     = (Int32)status;
                        database.ExecuteNonQuery("UPDATE [st_workflow_request] SET [status] = @status, deployed = 0 WHERE ID = @request_id", CommandType.Text, par2, trans);
                    }

                    //Adiciona o status da activity atual
                    par2.Clear();
                    par2.Add("@workflow_request_id", typeof(Int64)).Value   = this.workflow_request_id;
                    par2.Add("@status", typeof(String)).Value               = (Int32)status;
                    par2.Add("@description", typeof(String)).Value          = changeText;
                    par2.Add("@activity_id", typeof(Int64)).Value           = activity.ActivityId;
                    par2.Add("@executed_by_entity_id", typeof(Int64)).Value = executing_user;
                    par2.Add("@date", typeof(DateTime)).Value               = DateTime.Now;

                    database.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[date],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@date,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, trans);

                    //Adiciona o status da próxima atividade
                    if ((status == WorkflowRequestStatus.Approved) && (nextActivity != null))
                    {
                        par2.Clear();
                        par2.Add("@workflow_request_id", typeof(Int64)).Value   = this.workflow_request_id;
                        par2.Add("@status", typeof(String)).Value               = (Int32)WorkflowRequestStatus.Waiting;
                        par2.Add("@description", typeof(String)).Value          = "Aguardando análise";
                        par2.Add("@activity_id", typeof(Int64)).Value           = nextActivity.ActivityId;
                        par2.Add("@executed_by_entity_id", typeof(Int64)).Value = executing_user;
                        par2.Add("@date", typeof(DateTime)).Value               = DateTime.Now.AddSeconds(1);

                        database.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[date],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@date,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, trans);
                    }
                }


                //E-mails para os próximos aprovadores, se houver
                if ((status == WorkflowRequestStatus.Approved) && (nextActivity != null))
                {
                    try
                    {
                        Dictionary <Int64, List <String> > mails = new Dictionary <long, List <string> >();

                        if ((nextActivity.ManualApproval != null) && ((nextActivity.ManualApproval.EntityApprover > 0) || (nextActivity.ManualApproval.RoleApprover > 0)))
                        {
                            DataTable dtUserMails = database.ExecuteDataTable("select distinct entity_id, mail, full_name from vw_entity_mails where entity_id in (" + activity.ManualApproval.EntityApprover + ") or entity_id in (select i.entity_id from identity_role ir with(nolock) inner join [identity] i with(nolock) on i.id = ir.identity_id where ir.role_id = " + activity.ManualApproval.RoleApprover + ")", CommandType.Text, null, trans);
                            if ((dtUserMails != null) && (dtUserMails.Rows.Count > 0))
                            {
                                foreach (DataRow dr in dtUserMails.Rows)
                                {
                                    try
                                    {
                                        MailAddress m = new MailAddress(dr["mail"].ToString());

                                        if (!mails.ContainsKey((Int64)dr["entity_id"]))
                                        {
                                            mails.Add((Int64)dr["entity_id"], new List <string>());
                                        }

                                        mails[(Int64)dr["entity_id"]].Add(m.Address);
                                    }
                                    catch { }
                                }
                            }
                        }

                        if (mails.Count > 0)
                        {
                            foreach (Int64 admin_id in mails.Keys)
                            {
                                try
                                {
                                    Dictionary <String, String> vars = new Dictionary <string, string>();
                                    vars.Add("workflow_name", workflow.Name);
                                    vars.Add("user_name", this.user_name);
                                    vars.Add("user_login", this.user_login);
                                    vars.Add("user_id", this.user_id.ToString());
                                    vars.Add("admin_id", admin_id.ToString());
                                    vars.Add("description", workflow.Description);
                                    vars.Add("approval_link", "%enterprise_uri%/admin/access_request/" + this.workflow_request_id + "/allow/");
                                    vars.Add("deny_link", "%enterprise_uri%/admin/access_request/" + this.workflow_request_id + "/deny/");



                                    MessageBuilder msgAdm = MessageBuilder.BuildFromTemplate(database, this.enterprise_id, "access_request_admin", String.Join(",", mails[admin_id]), vars, trans);
                                    msgAdm.SaveToDb(database, trans);
                                }
                                catch { }
                            }
                        }
                    }
                    catch { }
                }

                try
                {
                    //E-mail para o usuário
                    DataTable dtUserMails = database.ExecuteDataTable("select distinct mail from vw_entity_mails where entity_id = " + this.user_id, CommandType.Text, null, trans);
                    if ((dtUserMails != null) && (dtUserMails.Rows.Count > 0))
                    {
                        List <String> mails = new List <string>();

                        foreach (DataRow dr in dtUserMails.Rows)
                        {
                            try
                            {
                                MailAddress m = new MailAddress(dr["mail"].ToString());
                                mails.Add(m.Address);
                            }
                            catch { }
                        }

                        if (mails.Count > 0)
                        {
                            Dictionary <String, String> vars = new Dictionary <string, string>();
                            vars.Add("workflow_name", this.workflow.Name);
                            vars.Add("user_name", this.user_name);
                            vars.Add("user_login", this.user_login);
                            vars.Add("user_id", this.user_id.ToString());
                            vars.Add("change", changeText);

                            MessageBuilder msg1 = MessageBuilder.BuildFromTemplate(database, this.enterprise_id, "access_request_changed", String.Join(",", mails), vars, trans);
                            msg1.SaveToDb(database, trans);
                        }
                    }
                }
                catch { }

                database.Commit();

                return(new WorkflowRequestProccess(true, ""));
            }
            catch (Exception ex)
            {
                database.Rollback();

                return(new WorkflowRequestProccess(false, "Erro on deny access.", ex.Message));
            }
        }
예제 #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Request.InputStream.Position = 0;

            try
            {
                JSONRequest req = JSON.GetRequest(Request.InputStream);

                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    ProxyConfig config = new ProxyConfig();
                    config.GetDBConfig(database.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host);

                    if (config.fqdn != null) //Encontrou o proxy
                    {
                        DirectoryInfo outDir = null;

                        using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                            outDir = new DirectoryInfo(Path.Combine(c.GetItem("outboundFiles"), config.proxyID + "_" + config.proxy_name));

                        if (!outDir.Exists)
                        {
                            outDir.Create();
                        }

                        if ((req.data != null) && (req.data != ""))
                        {
                            //Recebeu o nome do arquivo, envia o unico arquivo
                            FileInfo fName = null;
                            try
                            {
                                fName = new FileInfo(Path.Combine(outDir.FullName, req.data.Trim("..\\/".ToCharArray())));
                            }
                            catch
                            {
                                ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "Filename is invalid", "")));
                                return;
                            }

                            if (fName.Exists)
                            {
                                try
                                {
                                    Byte[] fData = File.ReadAllBytes(fName.FullName);

                                    ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", Convert.ToBase64String(fData))));


                                    try
                                    {
                                        DbParameterCollection par = new DbParameterCollection();
                                        par.Add("@filename", typeof(String)).Value = fName.FullName;

                                        Int64 packageTrackId = database.ExecuteScalar <Int64>("select id from st_package_track where flow = 'deploy' and filename = @filename", System.Data.CommandType.Text, par, null);

                                        par = new DbParameterCollection();
                                        par.Add("@package_id", typeof(Int64)).Value = packageTrackId;
                                        par.Add("@source", typeof(String)).Value    = "proxy";
                                        par.Add("@text", typeof(String)).Value      = "Proxy Downloaded file from IP " + Tools.Tool.GetIPAddress();

                                        database.ExecuteNonQuery("insert into st_package_track_history ([package_id] ,[source] ,[text]) values (@package_id ,@source ,@text)", System.Data.CommandType.Text, par, null);
                                    }
                                    catch { }
                                }
                                catch (Exception ex)
                                {
                                    ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "Error loading file " + fName.Name + ", " + ex.Message, "")));
                                }
                            }
                            else
                            {
                                ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "File not found '" + req.data + "'", "")));
                            }
                        }
                        else
                        {
                            List <FileInfo> files = new List <FileInfo>();
                            foreach (DirectoryInfo d in outDir.GetDirectories())
                            {
                                files.AddRange(d.GetFiles("*.iamdat", SearchOption.AllDirectories));
                            }

                            JsonGeneric list = new JsonGeneric();
                            list.fields = new String[] { "name" };

                            //Envia a listagem dos arquivos
                            foreach (FileInfo f in files)
                            {
                                list.data.Add(new String[] { f.FullName.Replace(outDir.FullName, "").Trim("\\/ ".ToCharArray()) });
                            }

                            ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", list.ToJsonString())));
                        }

                        //File.WriteAllBytes(Path.Combine(pluginsDir.FullName, config.fqdn + "-" + DateTime.Now.ToString("yyyyMMddHHmmss-ffffff") + ".iamreq"), Encoding.UTF8.GetBytes(JSON.Serialize<JSONRequest>(req)));
                    }
                }
            }
            catch (Exception ex) {
                Tools.Tool.notifyException(ex);
                throw ex;
            }
        }
예제 #11
0
파일: IAMInbound.cs 프로젝트: radtek/safeid
        private void ImportRegistersV2(ProxyConfig config, JsonGeneric jData, FileInfo f, JSONRequest req, IAMDatabase db)
        {
            Int32 resourcePluginCol = jData.GetKeyIndex("resource_plugin");
            Int32 pkgCol            = jData.GetKeyIndex("package");


            if (resourcePluginCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportRegistersV2] Erro on find column 'resource_plugin' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }


            if (pkgCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportRegistersV2] Erro on find column 'package' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }

            //Realiza a importação no modelo BulkInsert por melhor desempenho do banco
            DataTable dtBulk = new DataTable();

            dtBulk.Columns.Add(new DataColumn("date", typeof(DateTime)));
            dtBulk.Columns.Add(new DataColumn("file_name", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("resource_plugin", typeof(Int64)));
            dtBulk.Columns.Add(new DataColumn("import_id", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("package_id", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("package", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("status", typeof(String)));

            foreach (String[] dr in jData.data)
            {
                PluginConnectorBaseImportPackageUser pkg = JSON.DeserializeFromBase64 <PluginConnectorBaseImportPackageUser>(dr[pkgCol]);
                dtBulk.Rows.Add(new Object[] { DateTime.Now, f.Name, dr[resourcePluginCol], pkg.importId, pkg.pkgId, JSON.Serialize2(pkg), 'F' });

                try
                {
                    DbParameterCollection par = new DbParameterCollection();

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

                    Int64 trackId = db.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);

                    db.AddPackageTrack(trackId, "inbound", "Package imported to process queue");
                }
                catch { }
            }

            db.BulkCopy(dtBulk, "collector_imports");

            //Apaga todos os registros da tabela temporaria

            /*
             * Procedimento desabiliato em 2018-08-29 por suspeita de problema
             * db.ExecuteNonQuery("delete from collector_imports_temp", System.Data.CommandType.Text, null, null);
             *
             * db.BulkCopy(dtBulk, "collector_imports_temp");
             *
             * //Proteção contra reimportação de pacotes (loop)
             * db.ExecuteNonQuery("delete from collector_imports_temp where exists (select 1 from collector_imports_old o where o.date >= dateadd(day,-1,getdate()) and o.file_name = file_name and o.resource_plugin_id = resource_plugin_id and o.import_id = import_id and o.package_id = package_id)", System.Data.CommandType.Text, null, null);
             * db.ExecuteNonQuery("delete from collector_imports_temp where exists (select 1 from collector_imports o where o.date >= dateadd(day,-1,getdate()) and o.file_name = file_name and o.resource_plugin_id = resource_plugin_id and o.import_id = import_id and o.package_id = package_id)", System.Data.CommandType.Text, null, null);
             *
             * db.ExecuteNonQuery("insert into collector_imports select * from collector_imports_temp", System.Data.CommandType.Text, null, null);
             * db.ExecuteNonQuery("delete from collector_imports_temp", System.Data.CommandType.Text, null, null);
             * */

            //Atualiza os registros importados deste arquivo para liberar o processamento
            //Isso avisa o sistema que estes registros estão livres para processamento
            //*** Desabilitado essa funç~~ao em 2018-03-08, e colocado o registro para ser importado diretamente com o Status 'F'
            //db.ExecuteNonQuery("update collector_imports set status = 'F' where [file_name] = '" + f.Name + "'", CommandType.Text, null);

            //Realiza o rebuild do indice desta tabela para agilizar no engine
            //Este processo será executado somente uma vez pelo objeto pai
            //db.ExecuteNonQuery("sp_reindex_imports", CommandType.StoredProcedure, null);

#if DEBUG
            TextLog.Log("Inbound", "\t[ImportRegistersV2] Imported " + dtBulk.Rows.Count + " registers for enterprise " + req.enterpriseid + " and proxy " + req.host);
#endif

            dtBulk.Dispose();
            dtBulk = null;

            jData = null;
        }
예제 #12
0
파일: IAMInbound.cs 프로젝트: radtek/safeid
        private void ImportPackageTrack(ProxyConfig config, JsonGeneric jData, FileInfo f, JSONRequest req, IAMDatabase db)
        {
            Int32 resourceCol = jData.GetKeyIndex("resource");

            Int32 dateCol      = jData.GetKeyIndex("date");
            Int32 sourceCol    = jData.GetKeyIndex("source");
            Int32 filenameCol  = jData.GetKeyIndex("filename");
            Int32 packageIdCol = jData.GetKeyIndex("packageid");
            Int32 flowCol      = jData.GetKeyIndex("flow");
            Int32 textCol      = jData.GetKeyIndex("text");


            if (resourceCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportLogs] Erro on find column 'resource' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }


            if (sourceCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportLogs] Erro on find column 'source' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }

            if (textCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportLogs] Erro on find column 'text' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }


            if (flowCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportLogs] Erro on find column 'flow' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }


            if (filenameCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportLogs] Erro on find column 'filename' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }

            if (packageIdCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportLogs] Erro on find column 'packageid' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }


            DateTime date = DateTime.Now;

            foreach (String[] dr in jData.data)
            {
                try
                {
                    //Console.WriteLine(f.Name + " - " + dr[entityIdCol] + " ==> " + dr[textCol]);
                    //Console.WriteLine(dr[additionaldataCol]);
                    //Console.WriteLine("");

                    Int64 packageId = 0;

                    DbParameterCollection par = new DbParameterCollection();
                    par.Add("@flow", typeof(String)).Value       = dr[flowCol];
                    par.Add("@package_id", typeof(String)).Value = dr[packageIdCol];

                    try
                    {
                        Int64 tmp = db.ExecuteScalar <Int64>("select id from st_package_track where flow = @flow and package_id = @package_id", System.Data.CommandType.Text, par, null);

                        if (tmp > 0)
                        {
                            packageId = tmp;
                        }
                    }
                    catch { }

                    if (packageId == 0)
                    {
                        par = new DbParameterCollection();
                        par.Add("@entity_id", typeof(Int64)).Value = 0;
                        par.Add("@date", typeof(DateTime)).Value   = (dateCol >= 0 ? DateTime.Parse(dr[dateCol]) : date);
                        par.Add("@flow", typeof(String)).Value     = dr[flowCol];
                        par.Add("@package_id", typeof(String), dr[packageIdCol].Length).Value = dr[packageIdCol];
                        par.Add("@filename", typeof(String), dr[filenameCol].Length).Value    = dr[filenameCol];
                        par.Add("@package", typeof(String), dr[textCol].Length).Value         = dr[textCol];

                        packageId = db.ExecuteScalar <Int64>("sp_new_package_track", System.Data.CommandType.StoredProcedure, par, null);
                    }

                    db.AddPackageTrack(packageId, dr[flowCol], dr[textCol]);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            jData = null;
        }
예제 #13
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;
            }
        }
예제 #14
0
        public void SaveToDatabase(IAMDatabase database)
        {
            if (this.context_id == 0)
            {
                throw new Exception("ContextId can not be empty");
            }

            if (String.IsNullOrEmpty(this.name))
            {
                throw new Exception("EnterpriseId can not be empty");
            }

            if (String.IsNullOrEmpty(this.description))
            {
                this.description = "";
            }

            if (this.owner == 0)
            {
                throw new Exception("EnterpriseId can not be empty");
            }

            if (this.access == null)
            {
                throw new Exception("Access can not be empty");
            }

            if ((this.activities == null) || (this.activities.Count == 0))
            {
                throw new Exception("Activities list can not be empty");
            }

            Boolean newWorkflow = (this.workflow_id == 0);

            Object trans = database.BeginTransaction();

            try
            {
                if (newWorkflow)//New config
                {
                    using (DbParameterCollection par = new DbParameterCollection())
                    {
                        par.Add("@context_id", typeof(Int64)).Value   = this.context_id;
                        par.Add("@name", typeof(String)).Value        = this.name;
                        par.Add("@description", typeof(String)).Value = this.description;
                        par.Add("@owner", typeof(Int64)).Value        = this.owner;
                        par.Add("@enabled", typeof(Int64)).Value      = this.owner;
                        par.Add("@type", typeof(String)).Value        = this.access_type.ToString().ToLower();

                        DataTable dtNewWorkflow = database.ExecuteDataTable("sp_st_new_workflow", CommandType.StoredProcedure, par, trans);
                        if ((dtNewWorkflow == null) || (dtNewWorkflow.Rows.Count == 0))
                        {
                            throw new Exception("Database error on insert workflow");
                        }

                        this.workflow_id = (Int64)dtNewWorkflow.Rows[0]["id"];
                    }
                }
                else//update config
                {
                    using (DbParameterCollection par = new DbParameterCollection())
                    {
                        par.Add("@workflow_id", typeof(Int64)).Value  = this.workflow_id;
                        par.Add("@name", typeof(String)).Value        = this.name;
                        par.Add("@description", typeof(String)).Value = this.description;
                        par.Add("@owner", typeof(Int64)).Value        = this.owner;
                        par.Add("@type", typeof(String)).Value        = this.access_type.ToString().ToLower();
                        par.Add("@enabled", typeof(Int64)).Value      = this.enabled;

                        //Na atualização a trigger irá criar um novo ID, desta forma retorna o novo ID
                        this.workflow_id = database.ExecuteScalar <Int64>("update [st_workflow] set name = @name, description = @description, owner_id = @owner, [type] = @type, [enabled] = @enabled WHERE id = @workflow_id; select MAX(id) id from st_workflow where (id = @workflow_id and [deprecated] = 0) or ([original_id] = @workflow_id and [deprecated] = 0)", CommandType.Text, par, trans);
                    }
                }

                //Exclui todos os access
                database.ExecuteNonQuery("delete from st_workflow_access_entity where workflow_id = " + this.workflow_id + "; delete from st_workflow_access_role where workflow_id = " + this.workflow_id, CommandType.Text, null, trans);
                switch (access_type)
                {
                case WorkflowAccessType.RoleGrant:
                    WorkflowAccessRoleGrant roleGrant = ((WorkflowAccessRoleGrant)this.access);

                    if ((roleGrant.Roles == null) || (roleGrant.Roles.Count == 0))
                    {
                        throw new Exception("Role list can not be empty");
                    }

                    foreach (Int64 role in roleGrant.Roles)
                    {
                        using (DbParameterCollection par = new DbParameterCollection())
                        {
                            par.Add("@workflow_id", typeof(Int64)).Value = this.workflow_id;
                            par.Add("@role_id", typeof(Int64)).Value     = role;

                            database.ExecuteNonQuery("INSERT INTO st_workflow_access_role (workflow_id, role_id) VALUES (@workflow_id, @role_id)", CommandType.Text, par, trans);
                        }
                    }
                    break;

                case WorkflowAccessType.Delegation:
                    WorkflowAccessDelegation entityDelegation = ((WorkflowAccessDelegation)this.access);

                    if (entityDelegation.Entity == 0)
                    {
                        throw new Exception("Entity id can not be empty");
                    }

                    using (DbParameterCollection par = new DbParameterCollection())
                    {
                        par.Add("@workflow_id", typeof(Int64)).Value = this.workflow_id;
                        par.Add("@entity_id", typeof(Int64)).Value   = entityDelegation.Entity;

                        database.ExecuteNonQuery("INSERT INTO st_workflow_access_entity (workflow_id, entity_id) VALUES (@workflow_id, @entity_id)", CommandType.Text, par, trans);
                    }
                    break;

                case WorkflowAccessType.Unlock:
                    //Nada
                    break;
                }

                //Activities
                List <String> activitiesIds = new List <String>();
                Int32         order         = 0;
                foreach (WorkflowActivity activity in this.activities)
                {
                    if ((activity.AutoDeny == 0) && (activity.AutoDeny == 0) && (activity.ManualApproval == null || (activity.ManualApproval.EntityApprover == 0 && activity.ManualApproval.RoleApprover == 0)))
                    {
                        throw new Exception("All activity approvers is empty");
                    }

                    activity.ExeutionOrder = ++order;

                    if (activity.ActivityId == 0)//Novo
                    {
                        //SELECT SCOPE_IDENTITY()
                        using (DbParameterCollection par = new DbParameterCollection())
                        {
                            par.Add("@workflow_id", typeof(Int64)).Value     = this.workflow_id;
                            par.Add("@name", typeof(String)).Value           = activity.Name;
                            par.Add("@escalation_days", typeof(Int32)).Value = activity.EscalationDays;
                            par.Add("@expiration_days", typeof(Int32)).Value = activity.ExpirationDays;
                            par.Add("@auto_deny", typeof(Int64)).Value       = activity.AutoDeny;
                            par.Add("@auto_approval", typeof(Int64)).Value   = activity.AutoApproval;
                            par.Add("@execution_order", typeof(Int32)).Value = activity.ExeutionOrder;

                            activity.ActivityId = database.ExecuteScalar <Int64>("INSERT INTO st_workflow_activity ([workflow_id],[name],[escalation_days],[expiration_days],[auto_deny],[auto_approval],[execution_order]) VALUES (@workflow_id,@name,@escalation_days,@expiration_days," + (activity.AutoDeny > 0 ? "@auto_deny" : "null") + "," + (activity.AutoApproval > 0 ? "@auto_approval" : "null") + ",@execution_order); SELECT SCOPE_IDENTITY()", CommandType.Text, par, trans);
                        }
                    }
                    else//Atualiza
                    {
                        using (DbParameterCollection par = new DbParameterCollection())
                        {
                            par.Add("@activity_id", typeof(Int64)).Value     = activity.ActivityId;
                            par.Add("@workflow_id", typeof(Int64)).Value     = this.workflow_id;
                            par.Add("@name", typeof(String)).Value           = activity.Name;
                            par.Add("@escalation_days", typeof(Int32)).Value = activity.EscalationDays;
                            par.Add("@expiration_days", typeof(Int32)).Value = activity.ExpirationDays;
                            par.Add("@auto_deny", typeof(Int64)).Value       = activity.AutoDeny;
                            par.Add("@auto_approval", typeof(Int64)).Value   = activity.AutoApproval;
                            par.Add("@execution_order", typeof(Int32)).Value = activity.ExeutionOrder;

                            database.ExecuteNonQuery("UPDATE [st_workflow_activity] SET [name] = @name ,[escalation_days] = @escalation_days ,[expiration_days] = @expiration_days ,[auto_deny] = " + (activity.AutoDeny > 0 ? "@auto_deny" : "null") + " ,[auto_approval] = " + (activity.AutoApproval > 0 ? "@auto_approval" : "null") + ", [execution_order] = @execution_order WHERE [workflow_id] = @workflow_id", CommandType.Text, par, trans);
                        }
                    }

                    //Adiciona as activities que estão sendo utilizadas, para que posteriormente possam ser excluidas as não utilizadas
                    activitiesIds.Add(activity.ActivityId.ToString());

                    //Exclui todas as aprovações manuais
                    database.ExecuteNonQuery("delete from st_workflow_activity_manual_approval where workflow_activity_id = " + activity.ActivityId, CommandType.Text, null, trans);
                    if (activity.ManualApproval != null && (activity.ManualApproval.EntityApprover != 0 || activity.ManualApproval.RoleApprover != 0))
                    {
                        using (DbParameterCollection par = new DbParameterCollection())
                        {
                            par.Add("@workflow_activity_id", typeof(Int64)).Value = activity.ActivityId;
                            par.Add("@entity_approver", typeof(Int64)).Value      = activity.ManualApproval.EntityApprover;
                            par.Add("@role_approver", typeof(Int64)).Value        = activity.ManualApproval.RoleApprover;

                            database.ExecuteNonQuery("INSERT INTO [st_workflow_activity_manual_approval] ([workflow_activity_id],[entity_approver],[role_approver])VALUES (@workflow_activity_id ," + (activity.ManualApproval.EntityApprover > 0 ? "@entity_approver" : "null") + " ," + (activity.ManualApproval.RoleApprover > 0 ? "@role_approver" : "null") + ")", CommandType.Text, par, trans);
                        }
                    }
                }

                //Exclui as activities que não fazem mais parte deste workflow
                database.ExecuteNonQuery("delete from st_workflow_activity where workflow_id = " + this.workflow_id + " and id not in (" + String.Join(",", activitiesIds) + ")", CommandType.Text, null, trans);

                database.Commit();
            }
            catch (Exception ex)
            {
                String tst = ex.ToString();
                database.Rollback();
                throw ex;
            }
        }
예제 #15
0
        public static LicenseControl GetLicenseData(SqlConnection conn, SqlTransaction trans, Int64 enterpriseId)
        {
            //Retorna zero para ilimitado



            String installKey = "";

            try
            {
                using (IAMDatabase db = new IAMDatabase(conn))
                {
                    //Server installation key
                    using (IAM.Config.ServerKey2 sk = new IAM.Config.ServerKey2(db.Connection))
                        installKey = sk.ServerInstallationKey.AbsoluteUri;

                    //Resgata todas as licenças desta empresa e de servidor
                    DataTable dtLic = db.ExecuteDataTable("select * from license where enterprise_id in (0, " + enterpriseId + ")", trans);
                    if (dtLic == null)
                    {
                        return(new LicenseControl(1, "Error on get licenses on server", installKey));
                    }

                    if (dtLic.Rows.Count == 0)
                    {
                        return(new LicenseControl(1, "License not found", installKey));
                    }

                    //Localiza a licença menos restrita
                    IAMKeyData key = null;
                    foreach (DataRow dr in dtLic.Rows)
                    {
                        try
                        {
                            IAMKeyData k = IAMKey.ExtractFromCert(dr["license_data"].ToString());

                            //Checa a validade da licença
                            if ((k.IsTemp) && (k.TempDate.Value.CompareTo(DateTime.Now) < 0))
                            {
                                continue;
                            }

                            if (key == null)
                            {
                                key = k;
                            }

                            if (k.NumLic > key.NumLic)
                            {
                                key = k;
                            }
                        }
                        catch { }
                    }

                    if (key == null)
                    {
                        return(new LicenseControl(1, "License not found", installKey));
                    }

                    //Resgata do banco a contagem atual de entidades
                    Int32 count = db.ExecuteScalar <Int32>(conn, "select count(e.id) from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id where e.deleted = 0 and c.enterprise_id = " + enterpriseId, CommandType.Text, null, trans);

                    LicenseControl lc = new LicenseControl((Int32)key.NumLic, count, installKey);

                    return(lc);
                }
            }
            catch (Exception ex)
            {
                return(new LicenseControl(0, ex.Message, installKey));
            }
        }