Ejemplo n.º 1
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 Boolean adduser(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            if (!parameters.ContainsKey("containerid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null);
                return(false);
            }


            String role = parameters["containerid"].ToString();

            if (String.IsNullOrWhiteSpace(role))
            {
                Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null);
                return(false);
            }

            String userid = parameters["userid"].ToString();

            if (String.IsNullOrWhiteSpace(userid))
            {
                Error(ErrorType.InvalidRequest, "Parameter userid is not defined.", "", null);
                return(false);
            }

            Int64 containerid = 0;

            try
            {
                containerid = Int64.Parse(role);
            }
            catch
            {
                Error(ErrorType.InvalidRequest, "Parameter containerid is not a long integer.", "", null);
                return(false);
            }

            List <Int64> users = new List <Int64>();

            String[] t = userid.Split(",".ToCharArray());
            foreach (String u in t)
            {
                try
                {
                    Int64 tmp = Int64.Parse(u);
                    users.Add(tmp);
                }
                catch
                {
                    Error(ErrorType.InvalidRequest, "Parameter users is not a long integer.", "", null);
                    return(false);
                }
            }

            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtUsers = database.ExecuteDataTable("select c.*, c1.enterprise_id, c1.name context_name, entity_qty = (select COUNT(distinct e.id) from entity e with(nolock) inner join entity_container ec with(nolock) on e.id = ec.entity_id where ec.container_id = c.id) from container c with(nolock) inner join context c1 with(nolock) on c1.id = c.context_id where c1.enterprise_id = @enterprise_id and c.id = @container_id order by c.name", CommandType.Text, par, null);

            if (dtUsers == null)
            {
                Error(ErrorType.InternalError, "", "", null);
                return(false);
            }

            if (dtUsers.Rows.Count == 0)
            {
                Error(ErrorType.InvalidRequest, "Container not found.", "", null);
                return(false);
            }

            try
            {
                SqlTransaction trans = (SqlTransaction)database.BeginTransaction();

                foreach (Int64 u in users)
                {
                    DbParameterCollection par2 = new DbParameterCollection();
                    par2.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId;
                    par2.Add("@container_id", typeof(Int64)).Value  = containerid;
                    par2.Add("@entity_id", typeof(Int64)).Value     = u;

                    //Select all old containers
                    DataTable drContainers = database.ExecuteDataTable("select c.* from entity_container e inner join container c on c.id = e.container_id where e.entity_id = @entity_id", CommandType.Text, par2, trans);
                    if ((drContainers != null) && (drContainers.Rows.Count > 0))
                    {
                        foreach (DataRow dr in drContainers.Rows)
                        {
                            if ((Int64)dr["id"] == containerid)
                            {
                                database.AddUserLog(LogKey.User_ContainerRoleUnbind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, u, 0, "Identity unbind to container " + dr["name"].ToString(), "", Acl.EntityId, trans);
                            }
                        }
                    }

                    DataTable dtRet = database.ExecuteDataTable("sp_insert_entity_to_container", CommandType.StoredProcedure, par2, trans);

                    if ((dtRet != null) && (dtRet.Rows.Count > 0))
                    {
                        database.AddUserLog(LogKey.User_ContainerRoleBind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, u, 0, "Identity bind to container " + dtRet.Rows[0]["name"].ToString(), "", Acl.EntityId, trans);
                        database.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + u + ")", CommandType.Text, null, trans);
                    }
                }
                database.Commit();
            }
            catch (Exception ex)
            {
                database.Rollback();

                Error(ErrorType.InvalidRequest, "Error on bind user to container", ex.Message, null);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 2
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 Dictionary <String, Object> change(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            Dictionary <String, Object> result = new Dictionary <String, Object>();

            if (!parameters.ContainsKey("workflowid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter workflowid is not defined.", "", null);
                return(null);
            }


            String plugin = parameters["workflowid"].ToString();

            if (String.IsNullOrWhiteSpace(plugin))
            {
                Error(ErrorType.InvalidRequest, "Parameter workflowid is not defined.", "", null);
                return(null);
            }

            Int64 workflowid = 0;

            try
            {
                workflowid = Int64.Parse(plugin);
            }
            catch
            {
                Error(ErrorType.InvalidRequest, "Parameter workflowid is not a long integer.", "", null);
                return(null);
            }


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtPlugin = database.ExecuteDataTable("select w.id, request_qty = (select COUNT(*) from st_workflow_request wr with(nolock) where wr.workflow_id = w.id) from st_workflow w with(nolock) inner join context c with(nolock) on c.id = w.context_id where c.enterprise_id = @enterprise_id and w.id = @workflow_id", CommandType.Text, par, null);

            if (dtPlugin == null)
            {
                Error(ErrorType.InternalError, "", "", null);
                return(null);
            }

            if (dtPlugin.Rows.Count == 0)
            {
                Error(ErrorType.InvalidRequest, "Workflow not found.", "", null);
                return(null);
            }


            String  updateSQL      = "update st_workflow set ";
            String  updateFields   = "";
            Boolean update         = false;
            Boolean disableTrigger = true;

            foreach (String key in parameters.Keys)
            {
                switch (key.ToLower())
                {
                case "name":
                    String name = parameters["name"].ToString();
                    if (!String.IsNullOrWhiteSpace(name))
                    {
                        par.Add("@name", typeof(String)).Value = name;
                        if (updateFields != "")
                        {
                            updateFields += ", ";
                        }
                        updateFields += "name = @name";
                        update        = true;
                    }
                    else
                    {
                        Error(ErrorType.InvalidRequest, "Parameter name is empty.", "", null);
                        return(null);
                    }
                    break;
                }
            }

            if (update)
            {
                updateSQL += updateFields + " where id = @workflow_id";

                Object trans = database.BeginTransaction();
                try
                {
                    //Desabilita a trigger para evitar a criação de um novo workflow
                    //Os campos alterados não interferem no funcionamento
                    if (disableTrigger)
                    {
                        database.ExecuteNonQuery("DISABLE TRIGGER st_WorkflowUpdate ON st_workflow", CommandType.Text, null, trans);
                    }

                    database.ExecuteNonQuery(updateSQL, CommandType.Text, par, trans);

                    if (disableTrigger)
                    {
                        database.ExecuteNonQuery("ENABLE TRIGGER st_WorkflowUpdate ON st_workflow", CommandType.Text, null, trans);
                    }

                    database.Commit();
                }
                catch (Exception ex)
                {
                    database.Rollback();

                    Error(ErrorType.InternalError, "Error updating workflow", ex.Message, null);
                    return(null);
                }
            }

            //Atualiza a busca com os dados atualizados
            return(get(database, parameters));
        }
Ejemplo n.º 3
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 { }
            }
        }
Ejemplo n.º 4
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));
            }
        }
Ejemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse contentRet = null;


            String action = "";

            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["action"]))
            {
                action = (String)RouteData.Values["action"];
            }

            Int64 pluginId = 0;

            if ((action != "add_license") && (action != "upload_item_template") && (action != "upload") && (action != "add_new"))
            {
                try
                {
                    pluginId = Int64.Parse((String)RouteData.Values["id"]);

                    if (pluginId < 0)
                    {
                        pluginId = 0;
                    }
                }
                catch { }

                if (pluginId == 0)
                {
                    contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true);
                    action     = "";
                }
            }

            Int64 enterpriseId = 0;

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

            String rData = "";
            //SqlConnection //conn = DB.GetConnection();
            String jData = "";

            try
            {
                switch (action)
                {
                case "upload_item_template":

                    String id    = Request.Form["id"];
                    String file  = Request.Form["file"];
                    String tSize = Request.Form["size"];

                    if (String.IsNullOrEmpty(id))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (String.IsNullOrEmpty(file))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else if (String.IsNullOrEmpty(tSize))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true);
                    }
                    else
                    {
                        String userHtmlTemplate = "<div id=\"file{0}\" data-id=\"{0}\" data-name=\"{1}\" class=\"app-list-item file-item\">";
                        userHtmlTemplate += "<div class=\"form-content\"><input type=\"hidden\" name=\"file_name_{0}\" value=\"{1}\">";
                        userHtmlTemplate += "<input type=\"hidden\" name=\"{1}\" value=\"{0}\"></div>";
                        userHtmlTemplate += "<table>";
                        userHtmlTemplate += "   <tbody>";
                        userHtmlTemplate += "       <tr>";
                        userHtmlTemplate += "           <td class=\"colfull\">";
                        userHtmlTemplate += "               <div class=\"title\"><span class=\"name\" id=\"file_name_{0}\" data-id=\"{0}\">{1}</span><div class=\"clear-block\"></div></div>";
                        userHtmlTemplate += "               <div class=\"description\">{2}</div></div>";
                        userHtmlTemplate += "           </td>";
                        userHtmlTemplate += "       </tr>";
                        userHtmlTemplate += "   </tbody>";
                        userHtmlTemplate += "</table></div>";

                        String infoTemplate = "<div class=\"line\">";
                        infoTemplate += "<label>{1}</label>";
                        infoTemplate += "<span class=\"no-edit {0}\">{2}</span></div>";

                        String desc = "";

                        desc += String.Format(infoTemplate, "status", "Status", "Enviando");

                        String tHtml = String.Format(userHtmlTemplate, id, file, desc);

                        contentRet = new WebJsonResponse("#" + id, tHtml);
                    }

                    break;

                case "upload":

                    MultipartFormDataParser mp  = new MultipartFormDataParser(Request.InputStream);
                    List <String>           fls = new List <String>();


                    String infoTemplate2 = "<div class=\"line\">";
                    infoTemplate2 += "<label>{1}</label>";
                    infoTemplate2 += "<span class=\"no-edit {0}\">{2}</span></div>";


                    // Loop through all the files
                    foreach (FilePart mpF in mp.Files)
                    {
                        try
                        {
                            String d = "";

                            try
                            {
                                Byte[] rawAssembly = new Byte[mpF.Data.Length];
                                mpF.Data.Read(rawAssembly, 0, rawAssembly.Length);


                                IAMKeyData memKey   = null;
                                String     fileData = Convert.ToBase64String(rawAssembly);
                                try
                                {
                                    memKey = IAMKey.ExtractFromCert(fileData);
                                }
                                catch { }

                                if (memKey != null)
                                {
                                    d += String.Format(infoTemplate2, "", "Nome", mpF.FileName);
                                    d += String.Format(infoTemplate2, "", "Tamanho", mpF.Data.Length + " bytes");

                                    Boolean useLicense = false;

                                    if (memKey.IsServerKey)
                                    {
                                        d += String.Format(infoTemplate2, "", "Definitiva?", (memKey.IsTemp ? MessageResource.GetMessage("no") : MessageResource.GetMessage("yes")));
                                        if (memKey.IsTemp)
                                        {
                                            d += String.Format(infoTemplate2, "", "Expiração", (memKey.TempDate.HasValue ? MessageResource.FormatDate(memKey.TempDate.Value, true) : "não definido"));
                                        }

                                        d += String.Format(infoTemplate2, "", "Entidades", (memKey.NumLic == 0 ? MessageResource.GetMessage("unlimited") : memKey.NumLic.ToString()));

                                        String installKey = "";

                                        using (IAM.Config.ServerKey2 sk = new IAM.Config.ServerKey2(IAMDatabase.GetWebConnection()))
                                            installKey = sk.ServerInstallationKey.AbsoluteUri;

                                        d += String.Format(infoTemplate2, "", "Chave de instalação", (memKey.InstallKey == installKey ? "Válida" : "Inválida"));

                                        if (memKey.InstallKey == installKey)
                                        {
                                            if (!memKey.IsTemp)
                                            {
                                                useLicense = true;
                                            }
                                            else if ((memKey.IsTemp) && (memKey.TempDate.Value.CompareTo(DateTime.Now) > 0))
                                            {
                                                useLicense = true;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        d += String.Format(infoTemplate2, "", "Status", "Licença inválida");
                                    }

                                    if (useLicense)
                                    {
                                        d += "<input type=\"hidden\" name=\"key_data\" value=\"" + fileData + "\">";
                                    }

                                    /*
                                     * if (p2.Count > 0)
                                     *  d += String.Format(infoTemplate2, "", "Plugins", String.Join(", ", p2));
                                     * else
                                     *  d += String.Format(infoTemplate2, "", "Plugins", "Nenhum plugin encontrado no arquivo enviado");
                                     *
                                     * if (p2.Count > 0)
                                     * {
                                     *  using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                     *  {
                                     *      DataTable dt = database.Select("select * from plugin where enterprise_id in (0," + enterpriseId + ") and (assembly in ('" + String.Join("','", p2) + "') or uri in ('" + String.Join("','", p2Uri) + "'))");
                                     *
                                     *      if (dt.Rows.Count > 0)
                                     *          throw new Exception("Plugin/uri ja cadastrado no sistema");
                                     *  }
                                     *
                                     *  FileInfo newFile = new FileInfo(Path.Combine(pluginsDir.FullName, mpF.FileName));
                                     *  if (newFile.Exists)
                                     *      newFile.Delete();
                                     *  File.WriteAllBytes(newFile.FullName, rawAssembly);
                                     * }*/
                                }
                                else
                                {
                                    d += String.Format(infoTemplate2, "", "Status", "Arquivo válido");
                                }
                            }
                            catch (Exception ex)
                            {
                                d  = String.Format(infoTemplate2, "", "Status", "Erro ao realizar o upload");
                                d += String.Format(infoTemplate2, "", "Informação do erro", ex.Message);
                            }


                            fls.Add(JSON.Serialize2(new { name = mpF.FileName, html = d }));
                        }
                        catch
                        {
                            fls.Add(JSON.Serialize2(new { name = mpF.FileName, error = "Erro enviando o arquivo" }));
                        }
                    }

                    Retorno.Controls.Add(new LiteralControl("{\"files\": [" + String.Join(",", fls) + "]}"));
                    contentRet = null;

                    break;

                case "add_new":

                    String key_data = "";
                    key_data = Request.Form["key_data"];
                    if (!String.IsNullOrEmpty(key_data))
                    {
                        IAMKeyData memKey = null;
                        try
                        {
                            memKey = IAMKey.ExtractFromCert(key_data);
                        }
                        catch { }

                        if (memKey != null)
                        {
                            Boolean useLicense = false;

                            if (memKey.IsServerKey)
                            {
                                String installKey = "";

                                using (IAM.Config.ServerKey2 sk = new IAM.Config.ServerKey2(IAMDatabase.GetWebConnection()))
                                    installKey = sk.ServerInstallationKey.AbsoluteUri;

                                if (memKey.InstallKey == installKey)
                                {
                                    if (!memKey.IsTemp)
                                    {
                                        useLicense = true;
                                    }
                                    else if ((memKey.IsTemp) && (memKey.TempDate.Value.CompareTo(DateTime.Now) > 0))
                                    {
                                        useLicense = true;
                                    }
                                }

                                if (useLicense)
                                {
                                    using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                    {
                                        db.openDB();
                                        Object trans = db.BeginTransaction();
                                        try
                                        {
                                            db.ExecuteNonQuery("delete from license where enterprise_id = " + enterpriseId, CommandType.Text, null, trans);

                                            using (DbParameterCollection par = new DbParameterCollection())
                                            {
                                                par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId;
                                                par.Add("@license", typeof(String)).Value      = key_data;

                                                db.ExecuteNonQuery("insert into license (enterprise_id,license_data) VALUES(@enterprise_id,@license)", CommandType.Text, par, trans);
                                            }

                                            db.Commit();

                                            contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/license/");
                                        }
                                        catch (Exception ex)
                                        {
                                            db.Rollback();
                                            contentRet = new WebJsonResponse("", "Falha ao aplicar a licença", 5000, true);
                                        }
                                    }
                                }
                                else
                                {
                                    contentRet = new WebJsonResponse("", "Licença inválida", 5000, true);
                                }
                            }
                            else
                            {
                                contentRet = new WebJsonResponse("", "Licença inválida", 5000, true);
                            }
                        }
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("", "Nenhuma licença válida encontrada para aplicar", 5000, true);
                    }

                    break;
                }
            }
            catch (Exception ex)
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
            }
            finally
            {
            }

            if (contentRet != null)
            {
                if (!String.IsNullOrWhiteSpace((String)Request["cid"]))
                {
                    contentRet.callId = (String)Request["cid"];
                }


                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Ejemplo n.º 6
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;
            }
        }