Example #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 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);
        }
Example #2
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);
            }
        }