Exemplo n.º 1
0
    static public void NewCode(Page page, Int64 entityId, out String error)
    {
        error = "";
        try
        {
            if (entityId == 0)
            {
                return;
            }

            String code = GenerateCode(6);
            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                using (DbParameterCollection par = new DbParameterCollection())
                {
                    par.Add("@code", typeof(String)).Value     = code;
                    par.Add("@entity_id", typeof(Int64)).Value = entityId;

                    db.ExecuteNonQuery("update entity set recovery_code = @code where deleted = 0 and id = @entity_id and (recovery_code is null or ltrim(rtrim(recovery_code)) = '')", CommandType.Text, par);

                    db.AddUserLog(LogKey.User_NewRecoveryCode, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, entityId, 0, MessageResource.GetMessage("new_recovery_code") + " (" + code + ")", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
                }
        }
        catch (Exception ex)
        {
            error = MessageResource.GetMessage("internal_error");
            Tools.Tool.notifyException(ex, page);
            return;
        }
        finally
        {
        }
    }
Exemplo n.º 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Request.InputStream.Position = 0;

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

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

                    if (config.fqdn != null) //Encontrou o proxy
                    {
                        //Limpa os certificados para não enviar
                        config.server_cert        = "";
                        config.server_pkcs12_cert = "";
                        config.client_cert        = "";

                        db.ExecuteNonQuery("update proxy set last_sync = getdate(), address = '" + Tools.Tool.GetIPAddress() + "', config = 0 where id = " + config.proxyID, System.Data.CommandType.Text, null);
                        ReturnHolder.Controls.Add(new LiteralControl(config.ToJsonString()));
                    }
                    else
                    {
                        db.AddUserLog(LogKey.API_Error, DateTime.Now, "ProxyAPI", UserLogLevel.Warning, 0, ((EnterpriseData)Page.Session["enterprise_data"]).Id, 0, 0, 0, 0, 0, "Proxy not found " + req.host, req.ToString());
                    }
                }
            }
            catch (Exception ex) {
                Tools.Tool.notifyException(ex, this);
                //throw ex;
            }
        }
Exemplo n.º 3
0
        private void ImportDelete(ProxyConfig config, JsonGeneric jData, FileInfo f, JSONRequest req, IAMDatabase db)
        {
            Int32 resourceCol = jData.GetKeyIndex("resource");

            Int32 sourceCol     = jData.GetKeyIndex("source");
            Int32 uriCol        = jData.GetKeyIndex("uri");
            Int32 entityIdCol   = jData.GetKeyIndex("entityid");
            Int32 identityIdCol = jData.GetKeyIndex("identityid");

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

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


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


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

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


            DateTime date = DateTime.Now;

            foreach (String[] dr in jData.data)
            {
                try
                {
                    db.ExecuteNonQuery("update [identity] set deleted = 1, deleted_date = '" + date.ToString("o") + "' where id = " + dr[identityIdCol], CommandType.Text, null);
                }
                catch { }
            }

#if DEBUG
            TextLog.Log("Inbound", "\t[ImportDelete] Changed " + jData.data.Count + " identities for deleted status in enterprise " + req.enterpriseid + " and proxy " + req.host);
#endif

            jData = null;
        }
Exemplo n.º 4
0
        private void CheckSchedule(IAMDatabase db, Int64 scheduleId, Int64 resourcePluginId, Int64 resourceId, String jSonSchedule, DateTime next)
        {
            DateTime date = DateTime.Now;
            TimeSpan ts   = date - new DateTime(1970, 01, 01);

            Schedule schedule = new Schedule();

            try
            {
                schedule.FromJsonString(jSonSchedule);
                jSonSchedule = null;
            }
            catch
            {
                schedule.Dispose();
                schedule = null;
            }

            if (schedule == null)
            {
                return;
            }

            //Check Start date

            TimeSpan stDateTs = next - new DateTime(1970, 01, 01);

            TextLog.Log("Dispatcher", "[" + resourceId + "] CheckSchedule> next " + next.ToString("yyyy-MM-dd HH:mm:ss"));
            TextLog.Log("Dispatcher", "[" + resourceId + "] CheckSchedule> Executa agora? " + (ts.TotalSeconds >= stDateTs.TotalSeconds));
            if (ts.TotalSeconds >= stDateTs.TotalSeconds) //Data e hora atual maior ou igual a data que se deve iniciar
            {
                TextLog.Log("Dispatcher", "[" + resourceId + "] Starting execution");

                try
                {
                    using (IAMDeploy deploy = new IAMDeploy("Dispatcher", localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword))
                        deploy.DeployResourcePlugin(resourcePluginId);
                }
                catch (Exception ex)
                {
                    TextLog.Log("Dispatcher", "[" + resourceId + "] Error on execution " + ex.Message);
                }
                finally
                {
                    TextLog.Log("Dispatcher", "[" + resourceId + "] Execution completed");

                    //Agenda a próxima execução
                    DateTime nextExecute = schedule.CalcNext();

                    db.ExecuteNonQuery("update resource_plugin_schedule set [next] = '" + nextExecute.ToString("yyyy-MM-dd HH:mm:ss") + "' where id = " + scheduleId, CommandType.Text, null);
                }
            }

            schedule.Dispose();
            schedule = null;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Método privado para processamento do método 'user.resetpassword'
        /// </summary>
        /// <param name="sqlConnection">Conexão com o banco de dados MS-SQL</param>
        /// <param name="parameters">Dicionário (String, Object) contendo todos os parâmetros necessários</param>
        private Boolean restart(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            if (!parameters.ContainsKey("proxyid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter proxyid is not defined.", "", null);
                return(false);
            }


            String proxy = parameters["proxyid"].ToString();

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

            Int64 proxyid = 0;

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


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtProxy = database.ExecuteDataTable("select * from proxy p where (p.enterprise_id = @enterprise_id or p.enterprise_id = 0) and p.id = @proxy_id", CommandType.Text, par, null);

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

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

            database.ExecuteNonQuery("update proxy set restart = 1 where id = @proxy_id", CommandType.Text, par);
            database.AddUserLog(LogKey.Proxy_ResetRequest, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Proxy " + dtProxy.Rows[0]["name"] + " reset requested", "");

            return(true);
        }
Exemplo n.º 6
0
        private void ImportRegistersStruct(ProxyConfig config, JsonGeneric jData, FileInfo f, JSONRequest req, IAMDatabase db)
        {
            Int32 resourcePluginCol = jData.GetKeyIndex("resource_plugin");
            Int32 pkgCol            = jData.GetKeyIndex("package");


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


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

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

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

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

            db.BulkCopy(dtBulk, "collector_imports_struct");

            //Atualiza os registros importados deste arquivo para liberar o processamento
            //Isso avisa o sistema que estes registros estão livres para processamento
            db.ExecuteNonQuery("update collector_imports_struct set status = 'F' where [file_name] = '" + f.Name + "'", CommandType.Text, null);

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

            dtBulk.Dispose();
            dtBulk = null;

            jData = null;
        }
Exemplo n.º 7
0
        public static void UpdateUri(Page page)
        {
            if (page.Session["Uri"] == null)
            {
                Int64 enterpriseId = 0;

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

                if (enterpriseId == 0)
                {
                    return;
                }


                IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString());
                try
                {
                    Uri url = new Uri((page.Request.Params["HTTPS"].ToLower() == "on" ? "https://" : "http://") + page.Request.Params["HTTP_HOST"]);

                    //Se for localhost ignora a requisição
                    if (url.Host.ToLower() == "localhost")
                    {
                        return;
                    }

                    try
                    {
                        System.Net.IPAddress ip = System.Net.IPAddress.Parse(url.Host);

                        //Se é IP (não ocorrer o exception), ignora a requisição
                        return;
                    }
                    catch { }

                    database.ExecuteNonQuery("update [enterprise] set last_uri = '" + url.AbsoluteUri + "' where id = " + enterpriseId);

                    page.Session["Uri"] = url;
                }
                catch
                {
                    page.Session["Uri"] = null;
                }
            }
        }
Exemplo n.º 8
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 delete(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            if (!parameters.ContainsKey("fieldid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter fieldid is not defined.", "", null);
                return(false);
            }


            String field = parameters["fieldid"].ToString();

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

            Int64 fieldid = 0;

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


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtField = database.ExecuteDataTable("select f.*, qty = (select COUNT(*) from resource_plugin rp with(nolock) where name_field_id = f.id or mail_field_id = f.id or login_field_id = f.id) + (select COUNT(*) from resource_plugin_mapping rpm with(nolock) where rpm.field_id = f.id) from field f with(nolock) where f.enterprise_id = @enterprise_id and f.id = @field_id", CommandType.Text, par, null);

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

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

            //Verifica se está sendo usado
            if ((Int32)dtField.Rows[0]["qty"] > 0)
            {
                Error(ErrorType.SystemError, "Field is being used and can not be deleted.", "", null);
                return(false);
            }

            database.ExecuteNonQuery("delete from field where id = @field_id", CommandType.Text, par);
            database.AddUserLog(LogKey.Field_Deleted, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Field " + dtField.Rows[0]["name"] + " deleted", "");

            return(true);
        }
Exemplo n.º 9
0
        private void CheckSchedule(IAMDatabase db, Int64 scheduleId, Int64 reportId, String jSonSchedule, DateTime next)
        {
            DateTime date = DateTime.Now;
            TimeSpan ts   = date - new DateTime(1970, 01, 01);

            Schedule schedule = new Schedule();

            try
            {
                schedule.FromJsonString(jSonSchedule);
            }
            catch
            {
                schedule = null;
            }

            if (schedule == null)
            {
                return;
            }

            //Check Start date

            TimeSpan stDateTs = next - new DateTime(1970, 01, 01);

            if (ts.TotalSeconds >= stDateTs.TotalSeconds) //Data e hora atual maior ou igual a data que se deve iniciar
            {
                TextLog.Log("Report", "[" + reportId + "] Starting execution");

                try
                {
                    BuildReport(reportId);
                }
                catch (Exception ex)
                {
                    TextLog.Log("Report", "[" + reportId + "] Error on execution " + ex.Message);
                }
                finally
                {
                    TextLog.Log("Report", "[" + reportId + "] Execution completed");

                    //Agenda a próxima execução
                    DateTime calcNext    = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, schedule.TriggerTime.Hour, schedule.TriggerTime.Minute, 0);
                    DateTime nextExecute = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0);
                    switch (schedule.Trigger)
                    {
                    case ScheduleTtiggers.Dialy:
                        calcNext = calcNext.AddDays(1);
                        break;

                    case ScheduleTtiggers.Monthly:
                        calcNext = calcNext.AddMonths(1);
                        break;

                    case ScheduleTtiggers.Annually:
                        calcNext = calcNext.AddYears(1);
                        break;
                    }

                    //TextLog.Log("PluginStarter", "Calc 1 " + calcNext.ToString("yyyy-MM-dd HH:mm:ss"));

                    if (schedule.Repeat > 0)
                    {
                        if (nextExecute.AddMinutes(schedule.Repeat).CompareTo(calcNext) < 0)
                        {
                            nextExecute = nextExecute.AddMinutes(schedule.Repeat);
                            //TextLog.Log("PluginStarter", "Calc 2 " + nextExecute.ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                        else
                        {
                            nextExecute = calcNext;
                        }
                    }
                    else
                    {
                        nextExecute = calcNext;
                    }


                    db.ExecuteNonQuery("update report_schedule set [next] = '" + nextExecute.ToString("yyyy-MM-dd HH:mm:ss") + "' where id = " + scheduleId, CommandType.Text, null);
                }
            }
        }
Exemplo n.º 10
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 deleteuser(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            if (!parameters.ContainsKey("roleid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null);
                return(false);
            }


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

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

            Int64 roleid = 0;

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

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

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

            Int64 userid = 0;

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


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtUsers = database.ExecuteDataTable("select c.enterprise_id, r.name as role_name, ir.*, i.entity_id from role r inner join context c with(nolock) on c.id = r.context_id left join identity_role ir on r.id = ir.role_id left join [identity] i with(nolock) on ir.identity_id = i.id and i.entity_id = @entity_id where c.enterprise_id = @enterprise_id and r.id = @role_id", CommandType.Text, par, null);

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

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

            foreach (DataRow dr in dtUsers.Rows)
            {
                if ((dr["identity_id"] != DBNull.Value) && (dr["entity_id"] != DBNull.Value))
                {
                    database.AddUserLog(LogKey.User_IdentityRoleUnbind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, (Int64)dr["entity_id"], (Int64)dr["identity_id"], "Identity unbind to role " + dr["role_name"], "");
                    database.ExecuteNonQuery("delete from identity_role where role_id = @role_id and identity_id = " + dr["identity_id"], CommandType.Text, par);
                    database.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + dr["entity_id"] + ")", CommandType.Text, null, null);
                }
            }


            return(true);
        }
Exemplo n.º 11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;

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


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

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

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

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

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

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

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


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

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


            if (ret != null)
            {
                ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Exemplo n.º 12
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);
        }
Exemplo n.º 13
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 delete(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            if (!parameters.ContainsKey("containerid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null);
                return(false);
            }


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

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

            Int64 containerid = 0;

            try
            {
                containerid = Int64.Parse(container);
            }
            catch
            {
                Error(ErrorType.InvalidRequest, "Parameter containerid 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.*, 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), chield_qty = (select COUNT(distinct chield.id) from container chield with(nolock) where chield.parent_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);
            }

            if ((Int32)dtUsers.Rows[0]["entity_qty"] > 0)
            {
                Error(ErrorType.InvalidRequest, "Container is not empty.", "", null);
                return(false);
            }


            if ((Int32)dtUsers.Rows[0]["chield_qty"] > 0)
            {
                Error(ErrorType.InvalidRequest, "Container has chield containers.", "", null);
                return(false);
            }


            database.ExecuteNonQuery("delete from container where id = @container_id", CommandType.Text, par);

            database.AddUserLog(LogKey.Context_Deleted, null, "API", UserLogLevel.Error, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Container " + dtUsers.Rows[0]["name"] + " deleted", "");

            return(true);
        }
Exemplo n.º 14
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("roleid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null);
                return(null);
            }


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

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

            Int64 roleid = 0;

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


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtSysRole = database.ExecuteDataTable("select r.*, entity_qty = (select COUNT(distinct e.id) from sys_entity_role er inner join entity e with(nolock) on e.id = er.entity_id where er.role_id = r.id) from sys_role r WHERE r.enterprise_id = @enterprise_id and r.id = @role_id order by r.name", CommandType.Text, par, null);

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

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


            List <String> log = new List <String>();

            String  updateSQL = "";
            Boolean update    = false;

            if (parameters["name"] != null)
            {
                String name = parameters["name"].ToString();
                if (!String.IsNullOrWhiteSpace(name))
                {
                    par.Add("@name", typeof(String)).Value = name;
                    if (updateSQL != "")
                    {
                        updateSQL += ", ";
                    }
                    updateSQL += " name = @name";
                    update     = true;

                    log.Add("Name changed from '" + dtSysRole.Rows[0]["name"] + "' to '" + name + "'");
                }
            }

            if ((parameters["enterprise_admin"] != null) && (parameters["enterprise_admin"] is Boolean))
            {
                par.Add("@enterprise_admin", typeof(Boolean)).Value = (Boolean)parameters["enterprise_admin"];
                if (updateSQL != "")
                {
                    updateSQL += ", ";
                }
                updateSQL += " ea = @enterprise_admin";
                update     = true;

                log.Add("Enterprise admin changed from '" + (Boolean)dtSysRole.Rows[0]["ea"] + "' to '" + (Boolean)parameters["enterprise_admin"] + "'");
            }

            if (update)
            {
                updateSQL = "update sys_role set " + updateSQL + " where id = @role_id";
                database.ExecuteNonQuery(updateSQL, CommandType.Text, par);
                database.AddUserLog(LogKey.SystemRole_Changed, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "System role changed", String.Join("\r\n", log));
            }

            return(get(database, parameters));
        }
Exemplo n.º 15
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 deleteuser(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            if (!parameters.ContainsKey("roleid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null);
                return(false);
            }


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

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

            Int64 roleid = 0;

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

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

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

            Int64 userid = 0;

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


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtSysRole = database.ExecuteDataTable("select *, entity_qty = (select COUNT(distinct e.id) from sys_entity_role er inner join entity e with(nolock) on e.id = er.entity_id where er.role_id = r.id), last_admin = case when r.ea = 1 and not exists (select 1 from sys_role r1 where r1.enterprise_id = r.enterprise_id and r1.ea = 1 and r1.id <> r.id) then cast(1 as bit) else cast(0 as bit) end from sys_role r WHERE r.enterprise_id = @enterprise_id and r.id = @role_id and r.sa = 0", CommandType.Text, par, null);

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

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

            DataTable dtSysRoleUsers = database.ExecuteDataTable("select e.id entity_id, r.* from entity e with(nolock) inner join sys_entity_role er on e.id = er.entity_id inner join sys_role r on r.id = er.role_id WHERE r.enterprise_id = @enterprise_id and r.id = @role_id", CommandType.Text, par, null);

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

            if (dtSysRoleUsers.Rows.Count > 0)
            {
                if ((Boolean)dtSysRole.Rows[0]["last_admin"] && ((Int32)dtSysRole.Rows[0]["entity_qty"] == 1))
                {
                    Error(ErrorType.SystemError, "Entity " + dtSysRoleUsers.Rows[0]["name"] + " is a last user on a system role and this role is the last role with enterprise admin permission, can not be delete this user.", "", null);
                    return(false);
                }


                database.ExecuteNonQuery("delete from sys_entity_role where role_id = @role_id and entity_id = @entity_id", CommandType.Text, par);

                foreach (DataRow dr in dtSysRoleUsers.Rows)
                {
                    if (dr["entity_id"] != DBNull.Value)
                    {
                        database.AddUserLog(LogKey.User_SystemRoleUnbind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, (Int64)dr["entity_id"], 0, "Entity unbind to system role " + dtSysRole.Rows[0]["name"], ((Boolean)dtSysRole.Rows[0]["ea"] ? "Enterprise admin" : ""));
                    }
                }
            }

            return(true);
        }
Exemplo n.º 16
0
        private void WatchdogTimerCallback(Object o)
        {
            IAMDatabase db = null;

            try
            {
                //check if we need to stop any service
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 600;

                //Limpa status lixo
                db.ExecuteNonQuery("delete from service_status where last_status < DATEADD(day,-15,getdate())");

                //seleciona os servicos comproblema ou parados
                DataTable dtServices = db.Select("select * from service_status where started_at is null or last_status < DATEADD(hour,-1,getdate()) or case when started_at is null then cast(getdate() as date) else cast(started_at as date) end <> cast(getdate() as date)");
                if (dtServices != null && dtServices.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtServices.Rows)
                    {
                        String svcName = dr["service_name"].ToString();

                        if (svcName.ToLower().IndexOf("watchdog") >= 0)
                        {
                            continue;
                        }

                        TextLog.Log("Watchdog", "Killing service '" + svcName + "'");
                        Killall(svcName);
                        Killall("IAM" + svcName);
                    }
                }

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

                db = null;
            }

            try
            {
                ServiceController[] services = ServiceController.GetServices();

                foreach (ServiceController service in ServiceController.GetServices())
                {
                    try
                    {
                        switch (service.ServiceName.ToLower())
                        {
                        case "iambackup":
                        case "iamdispatcher":
                        case "iamengine":
                        case "iaminbound":
                        case "iamreport":
                        case "iamproxy":
                        case "iammultiproxy":
                        case "iammessenger":
                        case "iamworkflowprocessor":
                            StartupState stMode = StartMode(service.ServiceName);

                            switch (stMode)
                            {
                            case StartupState.Automatic:
                                if ((service.Status.Equals(ServiceControllerStatus.Stopped)) || (service.Status.Equals(ServiceControllerStatus.StopPending)))
                                {
                                    TextLog.Log("Watchdog", "Starting service '" + service.DisplayName + "'");
                                    service.Start();

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

                                        db.AddUserLog(LogKey.Watchdog, null, "Watchdog", UserLogLevel.Warning, 0, 0, 0, 0, 0, 0, 0, "Starting service '" + service.DisplayName + "'");

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

                                        db = null;
                                    }
                                }
                                break;

                            default:
                                TextLog.Log("Watchdog", "Unknow action for service start mode '" + stMode.ToString() + "' for service '" + service.DisplayName + "'");
                                break;
                            }

                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        TextLog.Log("Watchdog", "Erro ao processar o controle do serviço '" + service.DisplayName + "': " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                TextLog.Log("Watchdog", "Erro ao processar o controle dos serviços: " + ex.Message);
            }
        }
Exemplo n.º 17
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("enterpriseid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter enterpriseid is not defined.", "", null);
                return(null);
            }

            String enterprise = parameters["enterpriseid"].ToString();

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

            Int64 enterpriseid = 0;

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


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtEnterprise = database.ExecuteDataTable("select * from enterprise where id = @enterprise_id", CommandType.Text, par, null);

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

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

            List <String> hosts = new List <String>();
            Dictionary <String, String> pgValues = new Dictionary <string, string>();
            Uri pluginUri = null;

            String  updateSQL      = "update enterprise set ";
            String  updateFields   = "";
            Boolean update         = false;
            Boolean updateHosts    = false;
            Boolean updateAuthPars = false;

            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;

                case "auth_plugin":

                    String auth_plugin = parameters["auth_plugin"].ToString();
                    if (!String.IsNullOrWhiteSpace(auth_plugin))
                    {
                        try
                        {
                            Uri tmp = new Uri(auth_plugin);
                            if (tmp.Scheme.ToLower() != "auth")
                            {
                                throw new Exception();
                            }
                        }
                        catch
                        {
                            Error(ErrorType.InvalidRequest, "Parameter auth_plugin is not a valid uri.", "", null);
                            return(null);
                        }

                        try
                        {
                            AuthBase plugin = AuthBase.GetPlugin(new Uri(auth_plugin));
                            if (plugin == null)
                            {
                                throw new Exception();
                            }
                        }
                        catch
                        {
                            Error(ErrorType.InvalidRequest, MessageResource.GetMessage("invalid_auth_service"), "", null);
                            break;
                        }


                        par.Add("@auth_plugin", typeof(String)).Value = auth_plugin;
                        if (updateFields != "")
                        {
                            updateFields += ", ";
                        }
                        updateFields += "auth_plugin = @auth_plugin";
                        update        = true;
                    }
                    else
                    {
                        Error(ErrorType.InvalidRequest, "Parameter auth_plugin is empty.", "", null);
                        return(null);
                    }
                    break;

                case "fqdn_alias":
                    if (parameters[key] is ArrayList)
                    {
                        updateHosts = true;

                        List <Object> ht = new List <Object>();
                        ht.AddRange(((ArrayList)parameters[key]).ToArray());
                        foreach (String host in ht)
                        {
                            if (!String.IsNullOrWhiteSpace(host))
                            {
                                try
                                {
                                    Uri tmp = new Uri("http://" + host);
                                    hosts.Add(host);
                                }
                                catch
                                {
                                    Error(ErrorType.InvalidRequest, "Parameter fqdn_alias->" + host + " is not a valid hostname.", "", null);
                                    return(null);
                                }
                            }
                        }
                    }
                    break;


                case "auth_paramters":
                    if (parameters[key] is Dictionary <String, Object> )
                    {
                        if (!parameters.ContainsKey("auth_plugin"))
                        {
                            Error(ErrorType.InvalidRequest, "Parameter auth_plugin is not defined.", "", null);
                            return(null);
                        }

                        if (String.IsNullOrWhiteSpace(parameters["auth_plugin"].ToString()))
                        {
                            Error(ErrorType.InvalidRequest, "Parameter auth_plugin is not defined.", "", null);
                            return(null);
                        }

                        try
                        {
                            Uri tmp = new Uri(parameters["auth_plugin"].ToString());
                            if (tmp.Scheme.ToLower() != "auth")
                            {
                                throw new Exception();
                            }
                        }
                        catch
                        {
                            Error(ErrorType.InvalidRequest, "Parameter auth_plugin is not a valid uri.", "", null);
                            return(null);
                        }

                        AuthBase plugin = null;
                        try
                        {
                            plugin = AuthBase.GetPlugin(new Uri(parameters["auth_plugin"].ToString()));
                            if (plugin == null)
                            {
                                throw new Exception();
                            }
                        }
                        catch
                        {
                            Error(ErrorType.InvalidRequest, MessageResource.GetMessage("invalid_auth_service"), "", null);
                            break;
                        }

                        pluginUri = plugin.GetPluginId();

                        updateAuthPars = true;

                        Dictionary <String, Object> p1 = (Dictionary <String, Object>)parameters[key];

                        AuthConfigFields[] fields = plugin.GetConfigFields();
                        foreach (AuthConfigFields f in fields)
                        {
                            String value = "";

                            if (p1.ContainsKey(f.Key))
                            {
                                value = p1[f.Key].ToString();
                            }

                            if (!String.IsNullOrEmpty(value))
                            {
                                pgValues.Add(f.Key, value);
                            }

                            if (f.Required && !pgValues.ContainsKey(f.Key))
                            {
                                Error(ErrorType.InvalidRequest, MessageResource.GetMessage("required_field") + " " + f.Name, "", null);
                                break;
                            }
                        }
                    }
                    break;
                }
            }

            if (update)
            {
                updateSQL += updateFields + " where id = @enterprise_id";
                database.ExecuteNonQuery(updateSQL, CommandType.Text, par);
            }

            if (updateHosts)
            {
                foreach (String host in hosts)
                {
                    if (!String.IsNullOrWhiteSpace(host))
                    {
                        DbParameterCollection par1 = new DbParameterCollection();
                        par1.Add("@enterprise_id", typeof(Int64)).Value = enterpriseid;
                        par1.Add("@fqdn", typeof(String)).Value         = host;

                        database.ExecuteNonQuery("insert into enterprise_fqdn_alias (enterprise_id, fqdn) select @enterprise_id, @fqdn where not exists (select 1 from enterprise_fqdn_alias where enterprise_id = @enterprise_id and fqdn = @fqdn) ", CommandType.Text, par1);
                    }
                }

                database.ExecuteNonQuery("delete from enterprise_fqdn_alias where enterprise_id = @enterprise_id " + (hosts.Count > 0 ? " and fqdn not in ('" + String.Join("', '", hosts) + "')" : ""), CommandType.Text, par);
            }


            if (updateAuthPars)
            {
                database.ExecuteNonQuery("delete from enterprise_auth_par where enterprise_id = @enterprise_id and plugin = '" + pluginUri.AbsoluteUri + "'", CommandType.Text, par);

                foreach (String key in pgValues.Keys)
                {
                    if (!String.IsNullOrWhiteSpace(pgValues[key]))
                    {
                        DbParameterCollection par1 = new DbParameterCollection();
                        par1.Add("@enterprise_id", typeof(Int64)).Value = enterpriseid;
                        par1.Add("@plugin", typeof(String)).Value       = pluginUri.AbsoluteUri;
                        par1.Add("@key", typeof(String)).Value          = key;
                        par1.Add("@value", typeof(String)).Value        = pgValues[key];

                        database.ExecuteNonQuery("insert into enterprise_auth_par (enterprise_id, plugin,[key],[value]) VALUES(@enterprise_id, @plugin, @key, @value)", CommandType.Text, par1);
                    }
                }
            }

            //Atualiza a busca com os dados atualizados
            return(get(database, parameters));
        }
Exemplo n.º 18
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> changepermissions(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            Dictionary <String, Object> result = new Dictionary <String, Object>();

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


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

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

            Int64 roleid = 0;

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


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

            if (!(parameters["permissions"] is ArrayList))
            {
                Error(ErrorType.InvalidRequest, "Parameter permissions is invalid.", "", null);
                return(null);
            }


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtSysRole = database.ExecuteDataTable("select r.*, entity_qty = (select COUNT(distinct e.id) from sys_entity_role er inner join entity e with(nolock) on e.id = er.entity_id where er.role_id = r.id) from sys_role r WHERE r.enterprise_id = @enterprise_id and r.id = @role_id order by r.name", CommandType.Text, par, null);

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

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

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

            try
            {
                List <String> log = new List <String>();

                List <String> perList = new List <String>();
                List <Object> lst     = new List <Object>();
                lst.AddRange(((ArrayList)parameters["permissions"]).ToArray());

                foreach (String p in lst)
                {
                    try
                    {
                        Int64 permissionid = Int64.Parse(p);

                        //Verifica se a permissão existe
                        DataTable dtP = database.ExecuteDataTable("select p.*, m.name module_name, sm.name submodule_name, sm.[api_module] + '.' + p.[key] api_key from sys_permission p inner join sys_sub_module sm on sm.id = p.submodule_id inner join sys_module m on m.id = sm.module_id WHERE p.id = " + p, CommandType.Text, null, trans);
                        if ((dtP == null) || (dtP.Rows.Count == 0))
                        {
                            Error(ErrorType.InvalidRequest, "Permission '" + p + "' not found.", "", null);
                            return(null);
                        }

                        database.ExecuteNonQuery("insert into sys_role_permission (role_id, permission_id) select @role_id, " + dtP.Rows[0]["id"] + " WHERE not exists(select 1 from sys_role_permission where role_id = @role_id and permission_id = " + dtP.Rows[0]["id"] + ")", CommandType.Text, par, trans);

                        perList.Add(dtP.Rows[0]["id"].ToString());
                        log.Add("Permission linked: " + dtP.Rows[0]["module_name"] + " => " + dtP.Rows[0]["api_key"]);
                    }
                    catch
                    {
                        Error(ErrorType.InvalidRequest, "Permission '" + p + "' is not a long integer.", "", null);
                        return(null);
                    }
                }

                //Exclui todas as outras não listadas
                database.ExecuteNonQuery("delete from sys_role_permission WHERE role_id = @role_id and permission_id not in (" + String.Join(",", perList) + ")", CommandType.Text, par, trans);
                database.AddUserLog(LogKey.SystemRolePermission_Changed, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "System role permissions changed", String.Join("\r\n", log), trans);

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

            Dictionary <String, Object> parR = new Dictionary <string, object>();

            parR.Add("roleid", roleid);
            parR.Add("permissions", true);

            return(get(database, parR));
        }
Exemplo n.º 19
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("containerid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter containerid is not defined.", "", null);
                return(null);
            }

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

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

            Int64 containerid = 0;

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


            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.* 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(null);
            }

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


            String  updateSQL    = "update container set ";
            String  updateFields = "";
            Boolean update       = false;

            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;

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

                    if (parentid > 0)
                    {
                        if (parentid == (Int64)dtUsers.Rows[0]["context_id"])
                        {
                            Error(ErrorType.InvalidRequest, "Parent container can not be this container", "", null);
                            return(null);
                        }

                        DataTable dtPar = database.ExecuteDataTable("select * from [container] c with(nolock) where c.id = " + parentid + " and c.context_id = " + dtUsers.Rows[0]["context_id"]);
                        if ((dtPar == null) || (dtPar.Rows.Count == 0))
                        {
                            Error(ErrorType.InvalidRequest, "Parent container is not a chield of this context", "", null);
                            return(null);
                        }
                    }

                    par.Add("@parent_id", typeof(Int64)).Value = parentid;
                    if (updateFields != "")
                    {
                        updateFields += ", ";
                    }
                    updateFields += "parent_id = @parent_id";
                    update        = true;

                    break;
                }
            }

            if (update)
            {
                updateSQL += updateFields + " where id = @container_id";
                database.ExecuteNonQuery(updateSQL, CommandType.Text, par);
            }

            //Atualiza a busca com os dados atualizados
            return(get(database, parameters));
        }
Exemplo n.º 20
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);
            }
        }
Exemplo n.º 21
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 deleteallusers(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);
            }

            Int64 containerid = 0;

            try
            {
                containerid = Int64.Parse(role);
            }
            catch
            {
                Error(ErrorType.InvalidRequest, "Parameter containerid 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.*, e.entity_id from entity_container e inner join container c on c.id = e.container_id inner join context c1 on c.context_id = c1.id where c1.enterprise_id = @enterprise_id and  e.container_id = @container_id", 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);
            }

            database.ExecuteNonQuery("delete from entity_container where container_id = @container_id", CommandType.Text, par);

            foreach (DataRow dr in dtUsers.Rows)
            {
                if (dr["entity_id"] != DBNull.Value)
                {
                    database.AddUserLog(LogKey.User_ContainerRoleUnbind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, (Int64)dr["entity_id"], 0, "Identity unbind to container " + dr["name"], "");
                    database.ExecuteNonQuery("insert into deploy_now (entity_id) values(" + dr["entity_id"] + ")", CommandType.Text, null, null);
                }
            }


            return(true);
        }
Exemplo n.º 22
0
        public static LoginResult Grant(String service, String ticket, Boolean renew)
        {
            if (String.IsNullOrEmpty(ticket))
            {
                return(new LoginResult(false, MessageResource.GetMessage("invalid_ticket")));
            }

            DbParameterCollection par = null;

            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
            {
                try
                {
                    par = new DbParameterCollection();;
                    par.Add("@tgc", typeof(String), ticket.Length).Value  = ticket.Trim();
                    par.Add("@svc", typeof(String), service.Length).Value = service.TrimEnd("/".ToCharArray()).Replace("https://", "//").Replace("http://", "//").Trim();

                    Int64 userId = 0;

                    //Realiza a busca pelo ticket no mesmo serviço
                    DataTable dt = db.ExecuteDataTable("select * from [cas_entity_ticket] t inner join [cas_service] s on t.service_id = s.id where t.expire_date > getdate() " + (renew ? " and create_by_credentials = 1 " : "") + " and s.service_uri = @svc and t.grant_ticket = @tgc", CommandType.Text, par);
                    if ((dt != null) && (dt.Rows.Count > 0))
                    {
                        //Atualiza a expiração
                        //DB.ExecuteSQL("update cas_entity_ticket set expire_date = dateadd(day,1,getdate()) where entity_id = " + l.Id + " and service_id = " + tmp.Rows[0]["service_id"].ToString(), null, CommandType.Text);
                        userId = (Int64)dt.Rows[0]["entity_id"];
                    }
                    else
                    {
                        //Realiza a busca do ticket em outro serviço
                        //Se existir copia o ticket para o serviço atual
                        dt = db.ExecuteDataTable("select * from [cas_entity_ticket] t inner join [cas_service] s on t.service_id = s.id where t.expire_date > getdate() " + (renew ? " and create_by_credentials = 1 " : "") + " and t.grant_ticket = @tgc", CommandType.Text, par);
                        if ((dt != null) && (dt.Rows.Count > 0))
                        {
                            par.Add("@entity_id", typeof(Int64)).Value = (Int64)dt.Rows[0]["entity_id"];
                            par.Add("@grant_ticket", typeof(String), dt.Rows[0]["grant_ticket"].ToString().Length).Value = dt.Rows[0]["grant_ticket"].ToString().Trim();
                            par.Add("@long_ticket", typeof(String), dt.Rows[0]["long_ticket"].ToString().Length).Value   = dt.Rows[0]["long_ticket"].ToString().Trim();

                            //Cria o ticket
                            db.ExecuteNonQuery("insert into cas_entity_ticket ([entity_id],[service_id],[grant_ticket],[long_ticket],[create_by_credentials]) select @entity_id, s.id, @grant_ticket, @long_ticket, 0 from cas_service s where s.service_uri = @svc", CommandType.Text, par);
                            userId = (Int64)dt.Rows[0]["entity_id"];
                        }
                        else
                        {
                            return(new LoginResult(false, MessageResource.GetMessage("invalid_ticket")));
                        }
                    }

                    if (userId > 0)
                    {
                        LoginData l = new LoginData();

                        DataTable dtEntity = db.ExecuteDataTable("select distinct l.id, l.alias, l.full_name, l.login, l.enterprise_id, l.password, l.must_change_password, s.id as service_id, s.service_uri, et.grant_ticket, et.long_ticket from vw_entity_logins l  inner join dbo.cas_entity_ticket et on et.entity_id = l.id inner join cas_service s on l.enterprise_id = s.enterprise_id and et.service_id = s.id where et.grant_ticket = @tgc and s.service_uri = @svc", CommandType.Text, par);

                        if ((dtEntity != null) && (dtEntity.Rows.Count > 0))
                        {
                            l.Alias          = dtEntity.Rows[0]["alias"].ToString();
                            l.FullName       = dtEntity.Rows[0]["full_name"].ToString();
                            l.Login          = dtEntity.Rows[0]["login"].ToString();
                            l.Id             = (Int64)dtEntity.Rows[0]["id"];
                            l.EnterpriseId   = (Int64)dtEntity.Rows[0]["enterprise_id"];
                            l.CASGrantTicket = dtEntity.Rows[0]["grant_ticket"].ToString();
                            l.CASLongTicket  = dtEntity.Rows[0]["long_ticket"].ToString();

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

                    return(new LoginResult(false, MessageResource.GetMessage("invalid_ticket")));
                }
                catch (Exception ex)
                {
                    return(new LoginResult(false, "Internal error"));
                }
                finally
                {
                    par = null;
                }
            }

            return(new LoginResult(false, MessageResource.GetMessage("invalid_ticket")));
        }
Exemplo n.º 23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!EnterpriseIdentify.Identify(Page, false, true)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                Page.Response.Status     = "403 Access denied";
                Page.Response.StatusCode = 403;
                Page.Response.End();
                return;
            }
            else
            {
                String proxyName = "";
                String version   = "";
                Int32  pid       = 0;
                try
                {
                    proxyName = Request.Headers["X-SAFEID-PROXY"];
                }
                catch { }

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

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

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

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

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


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

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

                                files = outDir.GetDirectories().Length;

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

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

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

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



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

                Page.Response.HeaderEncoding = Encoding.UTF8;
                ReturnHolder.Controls.Add(new LiteralControl("{\"config\":" + rConfig + ",\"files\":" + files + ",\"fetch\":" + fetch + ",\"restart\":" + (restart ? "1" : "0") + "}"));
            }
        }
Exemplo n.º 24
0
        static public LoginResult Grant(Page page, String username, String password)
        {
            try
            {
                if ((username == null) || (username.Trim() == "") || (username == password) || (username.Trim() == ""))
                {
                    return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd")));
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd")));
                    }
                    else
                    {
                        db.AddUserLog(LogKey.User_WrongUserAndPassword, null, "CAS", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, MessageResource.GetMessage("user_wrong_password") + " " + Tools.Tool.GetIPAddress(), "{ \"username\":\"" + username.Replace("'", "").Replace("\"", "") + "\", \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
                        return(new LoginResult(false, MessageResource.GetMessage("valid_username_pwd")));
                    }
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex, page);
                return(new LoginResult(false, "Internal error"));
            }
            finally
            {
            }
        }
Exemplo n.º 25
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("roleid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter roleid is not defined.", "", null);
                return(null);
            }


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

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

            Int64 roleid = 0;

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


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtUsers = database.ExecuteDataTable("select r.*, c.enterprise_id, entity_qty = (select COUNT(distinct i.entity_id) from identity_role ir inner join [identity] i with(nolock) on ir.identity_id = i.id where ir.role_id = r.id) from role r inner join context c with(nolock) on c.id = r.context_id where c.enterprise_id = @enterprise_id and r.id = @role_id order by r.name", CommandType.Text, par, null);

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

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

            List <String> log = new List <String>();

            String  updateSQL = "update role set ";
            Boolean update    = false;

            if (parameters["name"] != null)
            {
                String name = parameters["name"].ToString();
                if (!String.IsNullOrWhiteSpace(name))
                {
                    par.Add("@name", typeof(String)).Value = name;
                    updateSQL += "name = @name";
                    update     = true;

                    log.Add("Name changed from '" + dtUsers.Rows[0]["name"] + "' to '" + name + "'");
                }
            }

            if (update)
            {
                updateSQL += " where id = @role_id";
                database.ExecuteNonQuery(updateSQL, CommandType.Text, par);
                database.AddUserLog(LogKey.Role_Changed, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Role changed", String.Join("\r\n", log));
            }

            //Atualiza a busca com os dados atualizados
            dtUsers = database.ExecuteDataTable("select r.*, c.enterprise_id, entity_qty = (select COUNT(distinct i.entity_id) from identity_role ir inner join [identity] i with(nolock) on ir.identity_id = i.id where ir.role_id = r.id) from role r inner join context c with(nolock) on c.id = r.context_id where c.enterprise_id = @enterprise_id and r.id = @role_id order by r.name", CommandType.Text, par, null);

            DataRow dr1 = dtUsers.Rows[0];

            Dictionary <string, object> newItem = new Dictionary <string, object>();

            newItem.Add("enterprise_id", dr1["enterprise_id"]);
            newItem.Add("role_id", dr1["id"]);
            newItem.Add("parent_id", dr1["parent_id"]);
            newItem.Add("context_id", dr1["context_id"]);
            newItem.Add("name", dr1["name"]);
            newItem.Add("entity_qty", dr1["entity_qty"]);
            newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));

            result.Add("info", newItem);

            return(result);
        }
Exemplo n.º 26
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 { }
            }
        }
Exemplo n.º 27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            LoginData login = LoginUser.LogedUser(this);

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

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

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

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

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

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

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

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

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

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

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

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


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

                holderContent.Controls.Add(new LiteralControl(html));
            }
        }
Exemplo n.º 28
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 delete(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            if (!parameters.ContainsKey("workflowid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter workflowid is not defined.", "", null);
                return(false);
            }


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

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

            Int64 workflowid = 0;

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


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtPlugin = database.ExecuteDataTable("select p.*, resource_plugin_qty = (select COUNT(distinct rp1.plugin_id) from resource_plugin rp1 where rp1.plugin_id = p.id) from plugin p with(nolock) where p.enterprise_id = @enterprise_id and p.id = @plugin_id", CommandType.Text, par, null);

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

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

            //Verifica se está sendo usado
            if ((Int32)dtPlugin.Rows[0]["resource_plugin_qty"] > 0)
            {
                Error(ErrorType.SystemError, "Plugin is being used and can not be deleted.", "", null);
                return(false);
            }

            //Localiza o arquivo físico
            FileInfo assemblyFile = null;

            try
            {
                DirectoryInfo pluginsDir = null;

                pluginsDir = new DirectoryInfo(database.GetDBConfig("pluginFolder"));

                if (pluginsDir.Exists)
                {
                    assemblyFile = new FileInfo(Path.Combine(pluginsDir.FullName, dtPlugin.Rows[0]["assembly"].ToString()));
                }
            }
            catch
            {
                assemblyFile = null;
            }

            if ((assemblyFile == null) || (!assemblyFile.Exists))
            {
                Error(ErrorType.SystemError, "Plugin physical file not found.", "", null);
                return(false);
            }

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

            try
            {
                database.ExecuteNonQuery("delete from plugin where id = @plugin_id", CommandType.Text, par, trans);
                database.AddUserLog(LogKey.Plugin_Deleted, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Plugin " + dtPlugin.Rows[0]["name"] + " deleted", "", trans);

                assemblyFile.Delete();

                trans.Commit();
            }
            catch {
                trans.Rollback();
                Error(ErrorType.SystemError, "Fail on delete physical file", "", null);
                return(false);
            }

            return(true);
        }
Exemplo n.º 29
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("fieldid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter fieldid is not defined.", "", null);
                return(null);
            }


            String field = parameters["fieldid"].ToString();

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

            Int64 fieldid = 0;

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


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtField = database.ExecuteDataTable("select * from field with(nolock) where enterprise_id = @enterprise_id and id = @field_id", CommandType.Text, par, null);

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

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

            List <String> log = new List <String>();

            String  updateSQL = "";
            Boolean update    = false;

            foreach (String key in parameters.Keys)
            {
                switch (key)
                {
                case "name":
                    String name = parameters["name"].ToString();
                    if ((!String.IsNullOrWhiteSpace(name)) && (name != (String)dtField.Rows[0]["name"]))
                    {
                        DbParameterCollection par2 = new DbParameterCollection();
                        par2.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId;
                        par2.Add("@field_name", typeof(String)).Value   = name;

                        DataTable dtF1 = database.ExecuteDataTable("select * from field with(nolock) where enterprise_id = @enterprise_id and name = @field_name", CommandType.Text, par2, null);
                        if ((dtF1 != null) && (dtF1.Rows.Count > 0))
                        {
                            Error(ErrorType.InvalidRequest, "Field with the same name already exists.", "", null);
                            return(null);
                        }


                        par.Add("@name", typeof(String)).Value = name;
                        if (updateSQL != "")
                        {
                            updateSQL += ", ";
                        }
                        updateSQL += " name = @name";
                        update     = true;

                        log.Add("Name changed from '" + dtField.Rows[0]["name"] + "' to '" + name + "'");
                    }
                    break;

                case "data_type":
                    String data_type = parameters["data_type"].ToString();
                    if ((!String.IsNullOrWhiteSpace(data_type)) && (data_type != (String)dtField.Rows[0]["data_type"]))
                    {
                        switch (data_type.ToLower())
                        {
                        case "string":
                        case "datetime":
                        case "numeric":
                            break;

                        default:
                            Error(ErrorType.InvalidRequest, "Data type is not recognized.", "", null);
                            return(null);

                            break;
                        }

                        par.Add("@data_type", typeof(String)).Value = data_type;
                        if (updateSQL != "")
                        {
                            updateSQL += ", ";
                        }
                        updateSQL += " data_type = @data_type";
                        update     = true;

                        log.Add("Data type changed from '" + dtField.Rows[0]["data_type"] + "' to '" + data_type + "'");
                    }
                    break;

                case "public_field":
                    Boolean public_field = true;
                    try
                    {
                        public_field = Boolean.Parse(parameters["public_field"].ToString());
                    }
                    catch (Exception ex)
                    {
                        Error(ErrorType.InvalidRequest, "Parameter public_field is not a boolean.", "", null);
                        return(null);
                    }

                    if (public_field != (Boolean)dtField.Rows[0]["public"])
                    {
                        par.Add("@public_field", typeof(Boolean)).Value = public_field;
                        if (updateSQL != "")
                        {
                            updateSQL += ", ";
                        }
                        updateSQL += " [public] = @public_field";
                        update     = true;
                        log.Add("Changed to a " + (public_field ? "" : "non ") + "field");
                    }
                    break;

                case "user_field":
                    Boolean user_field = true;
                    try
                    {
                        user_field = Boolean.Parse(parameters["user_field"].ToString());
                    }
                    catch (Exception ex)
                    {
                        Error(ErrorType.InvalidRequest, "Parameter user_field is not a boolean.", "", null);
                        return(null);
                    }

                    if (user_field != (Boolean)dtField.Rows[0]["user"])
                    {
                        par.Add("@user_field", typeof(Boolean)).Value = user_field;
                        if (updateSQL != "")
                        {
                            updateSQL += ", ";
                        }
                        updateSQL += " [user] = @user_field";
                        update     = true;
                        log.Add("Changed to " + (user_field ? "an" : "a non ") + "user editable field");
                    }
                    break;
                }
            }

            if (update)
            {
                updateSQL = "update field set " + updateSQL + " where id = @field_id";
                database.ExecuteNonQuery(updateSQL, CommandType.Text, par);
                database.AddUserLog(LogKey.Field_Changed, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Field changed", String.Join("\r\n", log));
            }

            //Atualiza a busca com os dados atualizados
            dtField = database.ExecuteDataTable("select * from field with(nolock) where enterprise_id = @enterprise_id and id = @field_id", CommandType.Text, par, null);

            DataRow dr1 = dtField.Rows[0];

            Dictionary <string, object> newItem = new Dictionary <string, object>();

            newItem.Add("enterprise_id", dr1["enterprise_id"]);
            newItem.Add("field_id", dr1["id"]);
            newItem.Add("data_type", dr1["data_type"]);
            newItem.Add("name", dr1["name"]);
            newItem.Add("public_field", dr1["public"]);
            newItem.Add("user_field", dr1["user"]);

            result.Add("info", newItem);

            return(result);
        }
Exemplo n.º 30
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));
        }