예제 #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 Dictionary <String, Object> getaccessrequest(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            Dictionary <String, Object> result = new Dictionary <String, Object>();

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

            Int64 requestid = 0;

            try
            {
                requestid = Int64.Parse(parameters["requestid"].ToString());
            }
            catch
            {
                Error(ErrorType.InvalidRequest, "Parameter requestid is not a long integer.", "", null);
                return(null);
            }

            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtPlugins = database.ExecuteDataTable("select r.*, e.context_id, c.enterprise_id, e.full_name, e.login 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 where r.id = @request_id and c.enterprise_id = @enterprise_id", CommandType.Text, par, null);

            if ((dtPlugins == null) || (dtPlugins.Rows.Count == 0))
            {
                Error(ErrorType.InvalidRequest, "Access request not found.", "", null);
                return(null);
            }

            DataRow dr1 = dtPlugins.Rows[0];

            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("info", newItem);

            return(result);
        }
예제 #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 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);
        }
예제 #3
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> list(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            List <Object> result = new List <Object>();

            String text = "";

            if (parameters.ContainsKey("text"))
            {
                text = (String)parameters["text"];
            }

            if (String.IsNullOrWhiteSpace(text))
            {
                text = "";
            }

            DbParameterCollection par = new DbParameterCollection();

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

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


            String sql = "";

            sql += "WITH result_set AS (";
            sql += "  SELECT ";
            sql += "    ROW_NUMBER() OVER (ORDER BY w.name) AS [row_number], w.id, request_qty = (select COUNT(*) from st_workflow_request wr with(nolock) where wr.workflow_id = w.id) ";
            sql += "     from st_workflow w with(nolock) inner join context c with(nolock) on c.id = w.context_id ";
            sql += "     where ((c.enterprise_id = @enterprise_id) " + (String.IsNullOrWhiteSpace(text) ? "" : " and w.name like '%'+@text+'%'") + ")";
            sql += ") SELECT";
            sql += "  *";
            sql += " FROM";
            sql += "  result_set";
            sql += " WHERE";
            sql += "  [row_number] BETWEEN " + rStart + " AND " + rEnd;

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

            if ((dtPlugins != null) && (dtPlugins.Rows.Count > 0))
            {
                foreach (DataRow dr1 in dtPlugins.Rows)
                {
                    using (WorkflowConfig wk = new WorkflowConfig())
                    {
                        wk.GetDatabaseData(database, (Int64)dr1["id"]);

                        Dictionary <string, object> newItem = wk.ToJsonObject();

                        newItem.Add("request_qty", dr1["request_qty"]);

                        result.Add(newItem);
                    }
                }
            }

            return(result);
        }
예제 #4
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> get(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);
            }


            DataRow dr1 = dtPlugin.Rows[0];


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

                Dictionary <string, object> newItem = wk.ToJsonObject();

                newItem.Add("request_qty", dr1["request_qty"]);

                result.Add("info", newItem);
            }

            return(result);
        }
예제 #5
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);
            }
        }
예제 #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            MAutoservice mClass = ((MAutoservice)this.Master);

            menu1 = menu2 = menu3 = null;

            String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();

            menu1 = new LMenu("Home", ApplicationVirtualPath + "autoservice/");
            menu3 = new LMenu("Requisição de acesso", ApplicationVirtualPath + "autoservice/access_request/");

            login = LoginUser.LogedUser(this.Page);

            if (login == null)
            {
                Session["last_page"] = Request.ServerVariables["PATH_INFO"];
                Response.Redirect("/login/");
            }

            String action = "";

            if (RouteData.Values["action"] != null)
            {
                action = RouteData.Values["action"].ToString().ToLower();
            }

            String errorTemplate = "<span class=\"empty-results\">{0}</span>";
            String infoTemplate  = "<tr><td class=\"col1\">{0}</td><td class=\"col2\"><span class=\"no-edit\">{1}</span></td></tr>";


            String html  = "";
            String eHtml = "";
            String js    = "";
            String rData = "";
            String jData = "";


            String sideHTML = "";


            if (action != "new")
            {
                sideHTML += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "autoservice/access_request/new/'\">Nova requisição</button></div>";
            }


            //Verifica se está selecionado o usuário

            switch (action)
            {
            case "new":
                subtitle = "Nova requisição de acesso";

                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    //Busca todos os workflows disponíveis no mesmo contexto do usuário atual que esteja habilitado
                    DataTable dtWorkflow = database.ExecuteDataTable("select w.* from st_workflow w with(nolock) inner join context c with(nolock) on c.id = w.context_id inner join entity e with(nolock) on e.context_id = c.id where w.enabled = 1 and w.deprecated = 0 and e.id = " + login.Id + " order by w.name");
                    if ((dtWorkflow == null) || (dtWorkflow.Rows.Count == 0))
                    {
                        eHtml += String.Format(errorTemplate, "Nenhuma acesso disponível para solicitação");
                    }
                    else
                    {
                        js += "<script type=\"text/javascript\">";
                        js += "$( document ).ready(function() {";
                        js += "     $('#workflow').change(function() {";
                        js += "        $('#desc_text').html('');";
                        js += "        $('#desc_text').html( $('option:selected', this ).attr('description') );";
                        js += "     });";
                        js += "});";
                        js += "</script>";


                        html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "autoservice/access_request/action/add_request/\">";
                        html += "<div class=\"no-tabs fields\"><table><tbody>";

                        String select = "<select id=\"workflow\" name=\"workflow\" ><option value=\"\"></option>";
                        foreach (DataRow dr in dtWorkflow.Rows)
                        {
                            select += "<option value=\"" + dr["id"] + "\" description=\"" + HttpUtility.HtmlEncode(dr["description"]) + "\">" + dr["name"] + "</option>";
                        }
                        select += "</select><span id=\"desc_text\" class=\"description\" style=\"padding: 5px 0 0 0;\"></span>";

                        html += String.Format(infoTemplate, "Acesso", select);

                        html += String.Format(infoTemplate, "Descrição da necessidade do acesso", "<textarea id=\"description\" name=\"description\" rows=\"5\" placeholder=\"Digite a justificativa para necessidade de acesso\"></textarea>");

                        html += "</tbody></table><div class=\"clear-block\"></div></div>";

                        html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "autoservice/access_request/\" class=\"button link floatleft\">Cancelar</a></form>";
                    }
                }
                break;

            default:


                Int64 id = 0;
                try
                {
                    id = Int64.Parse((String)RouteData.Values["id"]);

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

                if (id > 0)
                {
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                    {
                        subtitle = "Requisição de acesso";

                        DataTable drRequest = database.ExecuteDataTable("select * from st_workflow_request r with(nolock) where r.id = " + id);
                        if ((drRequest != null) && (drRequest.Rows.Count > 0))
                        {
                            WorkflowConfig workflow = new WorkflowConfig();
                            workflow.GetDatabaseData(database, (Int64)drRequest.Rows[0]["workflow_id"]);

                            WorkflowRequestStatus status = (WorkflowRequestStatus)((Int32)drRequest.Rows[0]["status"]);

                            DataTable drRequestStatus = database.ExecuteDataTable("select r.*, a.name activity_name from st_workflow_request_status r with(nolock) inner join st_workflow_activity a with(nolock) on r.activity_id = a.id where r.workflow_request_id = " + drRequest.Rows[0]["id"] + " order by date desc");
                            DataTable drActivity      = database.ExecuteDataTable("select * from st_workflow_activity a with(nolock) where a.workflow_id = " + workflow.WorkflowId + " order by a.execution_order");

                            //html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "autoservice/access_request/action/add_request/\">";
                            html += "<div class=\"no-tabs fields\"><table><tbody>";

                            html += String.Format(infoTemplate, "Acesso", "<span class=\"no-edit\">" + workflow.Name + "<span class=\"description\">" + workflow.Description + "</span></span>");

                            html += String.Format(infoTemplate, "Último status", MessageResource.GetMessage("wf_" + status.ToString().ToLower()));

                            html += String.Format(infoTemplate, "Data da requisição", MessageResource.FormatDate((DateTime)drRequest.Rows[0]["create_date"], false));

                            html += String.Format(infoTemplate, "Descrição da necessidade do acesso", drRequest.Rows[0]["description"].ToString());

                            //html += String.Format(infoTemplate, "", "<span type=\"submit\" id=\"cancel\" class=\"button secondary floatleft red\">Cancelar requisição</span>");


                            //sideHTML += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "autoservice/access_request/new/'\">Nova requisição</button></div>";


                            html += "</tbody></table><div class=\"clear-block\"></div></div>";


                            html += "<h3>Passos de aprovação</h3>";

                            html += "<div class=\"sep\"><table id=\"users-table\" class=\"sorter\"><thead>";
                            html += "    <tr>";
                            html += "        <th class=\"pointer w80 header headerSortDown\" data-column=\"name\">Passo <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer header headerSortDown\" data-column=\"name\">Atividade <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer tHide mHide header\" data-column=\"status\">Último status <div class=\"icomoon\"></div></th>";
                            html += "    </tr>";
                            html += "</thead>";

                            html += "<tbody>";


                            String trTemplate = "    <tr class=\"request\" data-userid=\"{0}\">";
                            trTemplate += "            <td class=\"ident10\">{1}</td>";
                            trTemplate += "            <td class=\"tHide mHide\">{2}</td>";
                            trTemplate += "            <td class=\"tHide mHide\">{3}</td>";
                            trTemplate += "    </tr>";

                            Int32 step = 1;
                            if ((drActivity != null) && (drActivity.Rows.Count > 0))
                            {
                                foreach (DataRow dr in drActivity.Rows)
                                {
                                    String   st   = "";
                                    DateTime last = new DateTime(1970, 1, 1);

                                    if ((drRequestStatus != null) && (drRequestStatus.Rows.Count > 0))
                                    {
                                        foreach (DataRow drSt in drRequestStatus.Rows)
                                        {
                                            if (drSt["activity_id"].ToString() == dr["id"].ToString())
                                            {
                                                if (last.CompareTo((DateTime)drSt["date"]) < 0)
                                                {
                                                    last = (DateTime)drSt["date"];
                                                    st   = MessageResource.GetMessage("wf_" + ((WorkflowRequestStatus)((Int32)drSt["status"])).ToString().ToLower());
                                                }
                                            }
                                        }
                                    }

                                    if (st == "")
                                    {
                                        st = "Aguardando aprovação da atividade anterior";
                                    }

                                    html += String.Format(trTemplate, dr["id"], step++, dr["name"], st);
                                }
                            }

                            html += "</tbody></table><div class=\"clear-block\"></div></div>";

                            html += "<h3>Todos os status</h3>";

                            html += "<table id=\"users-table\" class=\"sorter\"><thead>";
                            html += "    <tr>";
                            html += "        <th class=\"w50 mHide {sorter: false}\"><div class=\"select-all\"></div></th>";
                            html += "        <th class=\"pointer w150 header headerSortDown\" data-column=\"name\">Data <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer w200 tHide mHide header\" data-column=\"status\">Status <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer tHide mHide header {sorter: false}\" data-column=\"create_date\">Atividade <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer tHide mHide header {sorter: false}\" data-column=\"create_date\">Descrição <div class=\"icomoon\"></div></th>";
                            html += "    </tr>";
                            html += "</thead>";

                            html += "<tbody>";

                            trTemplate  = "    <tr class=\"request\" data-userid=\"{0}\">";
                            trTemplate += "            <td class=\"select mHide\"><div class=\"checkbox\"></div></td>";
                            trTemplate += "            <td class=\"\">{1}</td>";
                            trTemplate += "            <td class=\"tHide mHide\">{2}</td>";
                            trTemplate += "            <td class=\"tHide mHide\">{3}</td>";
                            trTemplate += "            <td class=\"tHide mHide\">{4}</td>";
                            trTemplate += "    </tr>";



                            if ((drRequestStatus != null) && (drRequestStatus.Rows.Count > 0))
                            {
                                foreach (DataRow dr in drRequestStatus.Rows)
                                {
                                    try
                                    {
                                        html += String.Format(trTemplate, dr["id"], MessageResource.FormatDate((DateTime)dr["date"], false), MessageResource.GetMessage("wf_" + ((WorkflowRequestStatus)((Int32)dr["status"])).ToString().ToLower()), dr["activity_name"], dr["description"]);
                                    }
                                    catch (Exception ex)
                                    {
                                    }
                                }
                            }

                            html += "</tbody></table>";

                            //html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a href=\"" + ApplicationVirtualPath + "autoservice/access_request/\" class=\"button link floatleft\">Cancelar</a></form>";
                        }
                        else
                        {
                            eHtml += String.Format(errorTemplate, "Requisição não encontrada");
                        }
                    }
                }
                else     //Request não selecionado
                {
                    subtitle = "Requisição de acesso";

                    js += "<script type=\"text/javascript\">";
                    js += "$( document ).ready(function() {";
                    js += "    $('table tbody tr').each(function (index, element) {";
                    js += "        if ($(this).attr('data-href')) {";
                    js += "            $(this).unbind('click');";
                    js += "            $(this).click(function (event) {";
                    js += "                event.preventDefault();";
                    js += "                window.location = $(this).attr('data-href');";
                    js += "            });";
                    js += "        }";
                    js += "    });";
                    js += "});";
                    js += "</script>";

                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                    {
                        DataTable dtWorkflowRequests = database.ExecuteDataTable("select * from st_workflow_request where entity_id = " + login.Id + " order by create_date desc");
                        if ((dtWorkflowRequests == null) || (dtWorkflowRequests.Rows.Count == 0))
                        {
                            eHtml += String.Format(errorTemplate, "Nenhuma requisição cadastrada");
                        }
                        else
                        {
                            html += "<table id=\"users-table\" class=\"sorter\"><thead>";
                            html += "    <tr>";
                            html += "        <th class=\"w50 mHide {sorter: false}\"><div class=\"select-all\"></div></th>";
                            html += "        <th class=\"pointer header headerSortDown\" data-column=\"name\">Nome <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer tHide mHide header\" data-column=\"status\">Status <div class=\"icomoon\"></div></th>";
                            html += "        <th class=\"pointer w150 tHide mHide header\" data-column=\"create_date\">Data de criação <div class=\"icomoon\"></div></th>";
                            html += "    </tr>";
                            html += "</thead>";

                            html += "<tbody>";

                            String trTemplate = "    <tr class=\"request\" data-userid=\"{0}\" data-href=\"" + ApplicationVirtualPath + "autoservice/access_request/{0}/\">";
                            trTemplate += "            <td class=\"select mHide\"><div class=\"checkbox\"></div></td>";
                            trTemplate += "            <td class=\"pointer ident10\">{1}</td>";
                            trTemplate += "            <td class=\"pointer tHide mHide\">{2}</td>";
                            trTemplate += "            <td class=\"pointer tHide mHide\">{3}</td>";
                            trTemplate += "    </tr>";

                            foreach (DataRow dr in dtWorkflowRequests.Rows)
                            {
                                try
                                {
                                    WorkflowConfig workflow = new WorkflowConfig();
                                    workflow.GetDatabaseData(database, (Int64)dr["workflow_id"]);

                                    WorkflowRequestStatus status = (WorkflowRequestStatus)((Int32)dr["status"]);


                                    html += String.Format(trTemplate, dr["id"].ToString(), workflow.Name, MessageResource.GetMessage("wf_" + status.ToString().ToLower()), ((DateTime)dr["create_date"]).ToString("yyyy-MM-dd HH:mm:ss"));
                                }
                                catch (Exception ex)
                                {
                                }
                            }


                            html += "</tbody></table>";
                        }
                    }
                }
                break;
            }

            headContent.Controls.Add(new LiteralControl(js));
            contentHolder.Controls.Add(new LiteralControl((eHtml != "" ? eHtml : html)));

            sideHTML += "<ul class=\"user-profile\">";
            sideHTML += "    <li id=\"user-profile-general\" " + (action == "" ? "class=\"bold\"" : "") + "><span><a href=\"" + ApplicationVirtualPath + "autoservice/access_request/\">Requisições realizadas</a></span></li>";
            //sideHTML += "    <li id=\"user-profile-password\" " + (action == "changepassword" ? "class=\"bold\"" : "") + "><span><a href=\"" + ApplicationVirtualPath + "autoservice/access_request/new/\">Nova requisição</a></span></li>";
            sideHTML += "</ul>";

            sideHolder.Controls.Add(new LiteralControl(sideHTML));

            String titleBarHTML = "";

            /*
             * titleBarHTML += "<ul class=\"mobile-button-bar w50 \">";
             * titleBarHTML += "    <li id=\"user-profile-general-mobile\" "+ (action == "" ? "class=\"on\"" : "") + "><a href=\"" + ApplicationVirtualPath + "autoservice/user/\">Informações gerais</a></li>";
             * titleBarHTML += "    <li id=\"user-profile-password-mobile\" " + (action == "changepassword" ? "class=\"on\"" : "") + "><a href=\"" + ApplicationVirtualPath + "autoservice/user/changepassword/\">Troca de senha</a></li>";
             * titleBarHTML += "</ul>";*/

            titleBarContent.Controls.Add(new LiteralControl(titleBarHTML));
        }