Exemplo n.º 1
0
        private void LicTimer(Object oData)
        {
            using (IAMDatabase db2 = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword))
                using (ServerKey2 sk = new ServerKey2(db2.Connection))
                    try
                    {
                        db2.openDB();

                        TimeSpan ts = sk.ServerCert.NotAfter - DateTime.Now;

                        if (ts.TotalDays < 60)
                        {
                            db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Fatal, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri);
                        }
                        else if (ts.TotalDays < 180)
                        {
                            db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri);
                        }
                        else if (ts.TotalDays < 360)
                        {
                            db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Warning, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri);
                        }

                        db2.closeDB();
                    }
                    catch { }
        }
Exemplo n.º 2
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.º 3
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.º 4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;


            //if (Request.HttpMethod == "POST")
            //{
            if (!EnterpriseIdentify.Identify(this, true)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                return;
            }

            try
            {
                if ((RouteData.Values["module"] == null) || (RouteData.Values["module"].ToString() == ""))
                {
                    ret = new WebJsonResponse("", MessageResource.GetMessage("invalid_module"), 3000, true);
                }
                else
                {
                    LoadPage("/_admin/chartdata/" + RouteData.Values["module"] + ".aspx");
                }
            }
            catch (Exception ex)
            {
                if ((ex is HttpException) && (((HttpException)ex).GetHttpCode() == 404))
                {
                    ret = new WebJsonResponse("", MessageResource.GetMessage("not_implemented"), 3000, true);
                }
                else
                {
                    ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }

                try
                {
                    using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        db.AddUserLog(LogKey.API_Error, null, "AdminAPI", UserLogLevel.Error, 0, (((Page.Session["enterprise_data"]) != null && (Page.Session["enterprise_data"] is EnterpriseData) && (((EnterpriseData)Page.Session["enterprise_data"]).Id != null)) ? ((EnterpriseData)Page.Session["enterprise_data"]).Id : 0), 0, 0, 0, 0, 0, "API error: " + ex.Message, "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
                }
                catch { }

                Tools.Tool.notifyException(ex, this);
            }

            /*}
             * else
             * {
             *  ret = new WebJsonResponse("", MessageResource.GetMessage("invalid_http_method"), 3000, true);
             * }*/


            if (ret != null)
            {
                Retorno.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
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
        protected void Page_Load(object sender, EventArgs e)
        {
            /*
             * if ((Page.Request.Url.Host.ToLower() == "127.0.0.1") || (Page.Request.Url.Host.ToLower() == "localhost"))
             * {
             *  //Validação diferenciada em caso de requisição vinda de loopback
             *  //Pois o proprio servidor pode estar requisitando a API
             *  //Neste caso a empresa deve seve verificar se a empresa ja foi identificada nessa sessão
             *
             *  if ((Page.Session["enterprise_data"] == null) || !(Page.Session["enterprise_data"] is EnterpriseData))
             *  {
             *      Page.Response.Status = "403 Access denied";
             *      Page.Response.StatusCode = 403;
             *      Page.Response.End();
             *      return;
             *  }
             *
             * }
             * else
             * {*/

            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;
            }
            //}

            using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
            {
                ExecutionLog eLogs = new ExecutionLog(delegate(Boolean success, Int64 enterpriseId, String method, AccessControl acl, String jRequest, String jResponse)
                {
                    //Para efeitos de teste vou sempre retornar true
                    //return true;
                    LoginData login = null;

                    if ((Session["login"] != null) && (Session["login"] is LoginData))
                    {
                        login = (LoginData)Session["login"];
                    }


                    using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        db.AddUserLog(LogKey.Debug, null, "API", UserLogLevel.Debug, 0, enterpriseId, 0, 0, 0, (login != null ? login.Id : 0), 0, "API Call (" + method + "). Result success? " + success, "{\"Request\":" + jRequest + ", \"Response\":" + jResponse + "}");
                });

                WebPageAPI.Execute(database, this, eLogs);
            }
        }
Exemplo n.º 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod == "POST")
            {
                if (!EnterpriseIdentify.Identify(this, true)) //Se houver falha na identificação da empresa finaliza a resposta
                {
                    return;
                }

                //ResourceManager rm = new ResourceManager("Resources.Strings", System.Reflection.Assembly.Load("App_GlobalResources"));
                //CultureInfo ci = Thread.CurrentThread.CurrentCulture;

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

                    if ((req.request == null) || (req.request.Trim() == ""))
                    {
                        ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "Request is empty", "")));
                        return;
                    }

                    LoadPage("/proxy/methods/" + req.request.Trim() + ".aspx");
                }
                catch (Exception ex)
                {
                    if ((ex is HttpException) && (((HttpException)ex).GetHttpCode() == 404))
                    {
                        ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, MessageResource.GetMessage("not_implemented"), "")));
                    }
                    else
                    {
                        ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, MessageResource.GetMessage("api_error"), "")));
                    }

                    try
                    {
                        using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            db.AddUserLog(LogKey.API_Error, null, "ProxyAPI", UserLogLevel.Error, 0, (((Page.Session["enterprise_data"]) != null && (Page.Session["enterprise_data"] is EnterpriseData) && (((EnterpriseData)Page.Session["enterprise_data"]).Id != null)) ? ((EnterpriseData)Page.Session["enterprise_data"]).Id : 0), 0, 0, 0, 0, 0, "Proxy API error: " + ex.Message, Tools.Tool.getExceptionText(ex, this));
                    }
                    catch { }
                }
            }
            else
            {
                ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "Invalid http method", "")));
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Método utilizado para execução interna através da console de administração
        /// </summary>
        /// <param name="conn">Conexão com banco de dados MS-SQL</param>
        /// <param name="page">Página na qual a requisição foi iniciada</param>
        /// <param name="jRequest">Texto no formato JSON da requisição</param>
        public static String ExecuteLocal(DbBase database, Page page, String jRequest, ExecutionLog logDelegate)
        {
            try
            {
                ExecutionLog eLogs = new ExecutionLog(delegate(Boolean success, Int64 enterpriseIdLog, String method, AccessControl acl, String jRequestLog, String jResponseLog)
                {
                    if (!success)
                    {
                        using (IAMDatabase db = (IAMDatabase)database)
                            db.AddUserLog(LogKey.Debug, null, "API", UserLogLevel.Debug, 0, enterpriseIdLog, 0, 0, 0, 0, 0, "API Call (" + method + "). Result success? " + success, "{\"Request\":" + jRequestLog + ", \"Response\":" + jResponseLog + "}", 0, null);
                    }

                    if (logDelegate != null)
                    {
                        logDelegate(success, enterpriseIdLog, method, acl, jRequestLog, jResponseLog);
                    }
                });


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

                CJSONrpc jsonRpc = new CJSONrpc(database, jRequest, enterpriseId);

                ExternalAccessControl eAuth = GetDelegateInstance(database, page, enterpriseId);

                jsonRpc.ExternalAccessControl += eAuth;
                jsonRpc.ExecutionLog          += eLogs;
                String ret = jsonRpc.Execute();
                jsonRpc.ExternalAccessControl -= eAuth;
                jsonRpc.ExecutionLog          -= eLogs;

                eAuth = null;

                return(ret);
            }
            catch (Exception ex)
            {
                return(null);
            }
            finally
            {
            }
        }
Exemplo n.º 9
0
        private void ReportTimer(Object state)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            //TextLog.Log("Report", "Starting report timer");
            try
            {
                //IAMDeploy deploy = new IAMDeploy("report", localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                //deploy.DeployAll();

                IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();

                DataTable dtS = db.Select("select * from report_schedule");

                try
                {
                    //Processa um a um dos agendamentos
                    foreach (DataRow dr in dtS.Rows)
                    {
                        CheckSchedule(db, (Int64)dr["id"], (Int64)dr["report_id"], dr["schedule"].ToString(), (DateTime)dr["next"]);
                    }
                }
                catch (Exception ex)
                {
                    TextLog.Log("Report", "\tError on report timer schedule: " + ex.Message);
                    db.AddUserLog(LogKey.Report, null, "Report", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on report scheduler", ex.Message);
                }

                db.closeDB();
            }
            catch (Exception ex1)
            {
                TextLog.Log("Report", "\tError on report timer: " + ex1.Message);
            }
            finally
            {
                //TextLog.Log("Report", "\tScheduled for new report process in 60 seconds");
                //TextLog.Log("Report", "Finishing report timer");
                executing = false;
            }
        }
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 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.º 11
0
        static public void usersTextReport(IAMDatabase db, DataTable dtS, List <MailAddress> recipents)
        {
            StringBuilder errors = new StringBuilder();

            DataTable dtU = db.Select("select e.*, c.name context_name from entity e inner join context c on c.id = e.context_id where e.deleted = 0 and c.enterprise_id = " + dtS.Rows[0]["enterprise_id"] + " order by c.name, e.full_name");

            if ((dtU == null) || (dtU.Rows.Count == 0))
            {
                return;
            }

            DataTable dtUsers = new DataTable();

            dtUsers.Columns.Add("context_name", typeof(String));
            dtUsers.Columns.Add("full_name", typeof(String));
            dtUsers.Columns.Add("login", typeof(String));
            dtUsers.Columns.Add("create_date", typeof(DateTime));
            dtUsers.Columns.Add("last_login", typeof(DateTime));
            dtUsers.Columns.Add("locked", typeof(String));

            Dictionary <String, String> title = new Dictionary <string, string>();

            title.Add("context_name", "Contexto");
            title.Add("full_name", "Nome completo");
            title.Add("login", "Login");
            title.Add("create_date", "Data de criação");
            title.Add("last_login", "Ultimo login");
            title.Add("locked", "Bloqueado");

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

            DataTable dtF = db.Select("select distinct f.id, f.name, rp.[order] from report_mapping rp inner join field f on rp.field_id = f.id  order by rp.[order], f.name");

            if ((dtF != null) && (dtF.Rows.Count > 0))
            {
                foreach (DataRow dr in dtF.Rows)
                {
                    fields.Add((Int64)dr["id"]);
                    dtUsers.Columns.Add("f_" + dr["id"], typeof(String));
                    title.Add("f_" + dr["id"], dr["name"].ToString());
                }
            }

            DataTable dtUsers2 = dtUsers.Clone();

            String fieldFilter = String.Join(",", fields);

            DateTime dateRef = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(-1);

            foreach (DataRow dU in dtU.Rows)
            {
                try
                {
                    DataRow newItem = dtUsers.NewRow();
                    newItem["context_name"] = dU["context_name"];
                    newItem["full_name"]    = dU["full_name"];
                    newItem["login"]        = dU["login"];
                    newItem["create_date"]  = dU["create_date"];
                    newItem["last_login"]   = (dU["last_login"] == DBNull.Value ? DBNull.Value : dU["last_login"]);
                    newItem["locked"]       = (((Boolean)dU["locked"]) ? "Y" : "N");

                    if (fields.Count > 0)
                    {
                        //Primeiro realiza a busca e preenchimento dos dados da entidade
                        try
                        {
                            DataTable dtUserData = db.Select("select efe.field_id, efe.value from [entity] e inner join entity_field efe on efe.entity_id = e.id where e.id = " + dU["id"] + " group by efe.field_id, efe.value");
                            foreach (DataRow dUD in dtUserData.Rows)
                            {
                                if (newItem["f_" + dUD["field_id"]] == DBNull.Value)
                                {
                                    newItem["f_" + dUD["field_id"]] = dUD["value"];
                                }
                            }
                        }
                        catch { }


                        //Primeiro realiza a busca e preenchimento dos dados com as informações dos plugins de entrada
                        try
                        {
                            DataTable dtUserData = db.Select("select ife.field_id, ife.value from [identity] i inner join identity_field ife on ife.identity_id = i.id inner join resource_plugin rp on i.resource_plugin_id = rp.id where rp.enable_import = 1 and rp.permit_add_entity = 1 and i.entity_id = " + dU["id"] + " and ife.field_id in (" + fieldFilter + ")  and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by ife.field_id, ife.value");
                            foreach (DataRow dUD in dtUserData.Rows)
                            {
                                if (newItem["f_" + dUD["field_id"]] == DBNull.Value)
                                {
                                    newItem["f_" + dUD["field_id"]] = dUD["value"];
                                }
                            }
                        }
                        catch { }

                        //Depois com os outros plugins
                        try
                        {
                            DataTable dtUserData = db.Select("select ife.field_id, ife.value from [identity] i inner join identity_field ife on ife.identity_id = i.id where i.entity_id = " + dU["id"] + " and ife.field_id in (" + fieldFilter + ")  and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by ife.field_id, ife.value");
                            foreach (DataRow dUD in dtUserData.Rows)
                            {
                                if (newItem["f_" + dUD["field_id"]] == DBNull.Value)
                                {
                                    newItem["f_" + dUD["field_id"]] = dUD["value"];
                                }
                            }
                        }
                        catch { }
                    }

                    dtUsers.Rows.Add(newItem.ItemArray);

                    //Caso a criação seja do dia anterior ou deste dia inclui na segunda tabela tb.
                    if (((DateTime)dU["create_date"]).CompareTo(dateRef) == 1)
                    {
                        dtUsers2.Rows.Add(newItem.ItemArray);
                    }
                }
                catch (Exception ex)
                {
                    errors.AppendLine("Error processing registry: " + ex.Message);
                }
            }

            if (errors.ToString() != "")
            {
                db.AddUserLog(LogKey.Report, null, "Report", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Report error", errors.ToString());
            }

            ReportBase rep1 = new ReportBase(dtUsers, title);
            ReportBase rep2 = new ReportBase(dtUsers2, title);

            List <Attachment> atts = new List <Attachment>();

            try
            {
                using (MemoryStream ms1 = new MemoryStream(Encoding.UTF8.GetBytes(rep1.GetTXT())))
                    using (MemoryStream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(rep1.GetXML("Usuários", ""))))
                        using (MemoryStream ms3 = new MemoryStream(Encoding.UTF8.GetBytes(rep2.GetTXT())))
                            using (MemoryStream ms4 = new MemoryStream(Encoding.UTF8.GetBytes(rep2.GetXML("Usuários", ""))))
                            {
                                atts.Add(new Attachment(ms1, "all.txt"));
                                //atts.Add(new Attachment(ms2, "all.xls"));
                                atts.Add(new Attachment(ms3, "created.txt"));
                                //atts.Add(new Attachment(ms4, "created.xls"));

                                sendEmail(db, dtS.Rows[0]["title"].ToString(), recipents, dtUsers2.Rows.Count + " criados deste " + dateRef.ToString("yyyy-MM-dd HH:mm:ss"), false, atts);
                            }
            }
            catch (Exception ex)
            {
                db.AddUserLog(LogKey.Report, DateTime.Now, "Report", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Erro sending report", ex.Message);
            }

            /*
             * DataTable created = db.Select("select * from vw_entity_mails where create_date between CONVERT(datetime, convert(varchar(10),DATEADD(DAY, -1, GETDATE()),120) + ' 00:00:00', 120) and CONVERT(datetime, convert(varchar(10),getdate(),120) + ' 23:59:59', 120) order by context_name, full_name");
             * DataTable all = db.Select("select * from vw_entity_mails order by context_name, full_name");
             * Dictionary<String, String> title = new Dictionary<string, string>();
             * title.Add("context_name", "Contexto");
             * title.Add("full_name", "Nome completo");
             * title.Add("login", "Login");
             * title.Add("create_date", "Data de criação");
             * title.Add("last_login", "Ultimo login");
             * title.Add("mail", "E-mail");
             * title.Add("locked", "Bloqueado");
             *
             * ReportBase rep1 = new ReportBase(created, title);
             * ReportBase rep2 = new ReportBase(all, title);
             *
             * List<Attachment> atts = new List<Attachment>();
             *
             * using (MemoryStream ms1 = new MemoryStream(Encoding.UTF8.GetBytes(rep1.GetTXT())))
             * using (MemoryStream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(rep1.GetXML("Usuários", ""))))
             * using (MemoryStream ms3 = new MemoryStream(Encoding.UTF8.GetBytes(rep2.GetTXT())))
             * using (MemoryStream ms4 = new MemoryStream(Encoding.UTF8.GetBytes(rep2.GetXML("Usuários", ""))))
             * {
             *  atts.Add(new Attachment(ms1, "created.txt"));
             *  atts.Add(new Attachment(ms2, "created.xls"));
             *  atts.Add(new Attachment(ms3, "all.txt"));
             *  atts.Add(new Attachment(ms4, "all.xls"));
             *
             *  sendEmail(db, "Listagem de usuários em " + DateTime.Now.ToString("dd/MM/yyyy"), recipents, created.Rows.Count + " usuários criados de " + DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy") + " até " + DateTime.Now.ToString("dd/MM/yyyy"), false, atts);
             * }*/
        }
Exemplo n.º 12
0
        private void BuildReport(Int64 reportId)
        {
            IAMDatabase db = null;

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

                DataTable dtS = db.Select("select * from report where id = " + reportId);

                if ((dtS == null) || (dtS.Rows.Count == 0))
                {
                    return;
                }

                //Chega as propriedades básicas do report
                List <MailAddress> recipents = new List <MailAddress>();

                if ((dtS.Rows[0]["recipient"] != DBNull.Value) && (!String.IsNullOrWhiteSpace((String)dtS.Rows[0]["recipient"])))
                {
                    String[] tTo = dtS.Rows[0]["recipient"].ToString().Split(",;".ToCharArray());
                    foreach (String s in tTo)
                    {
                        try
                        {
                            if (!String.IsNullOrWhiteSpace(s))
                            {
                                recipents.Add(new MailAddress(s));
                            }
                        }
                        catch { }
                    }
                }

                if (recipents.Count == 0)
                {
                    throw new Exception("No valid email informed in recipient");
                }


                switch (dtS.Rows[0]["type"].ToString().ToLower())
                {
                case "audit":
                    auditReport(db, dtS, recipents);
                    break;

                case "integrity":
                    integrityTextReport(db, dtS, recipents);
                    break;

                default:
                    usersTextReport(db, dtS, recipents);
                    break;
                }
            }
            catch (Exception ex)
            {
                TextLog.Log("Report", "\tError building report: " + ex.Message);
                try
                {
                    db.AddUserLog(LogKey.Report, DateTime.Now, "Report", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Erro building report", ex.Message);
                }
                catch { }
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Exemplo n.º 13
0
        private void TmrCallback(Object sender)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            TextLog.Log("Engine", "Time access control", "Starting processor timer");
            IAMDatabase db = null;

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

                //Seleciona as entidades/identidades vinculadas a um resource x plugin que tenha controle de acesso por horário
                DataTable dtRegs = db.Select("select i.id, i.temp_locked, e.id entity_id, r.name resource_name from entity e with(nolock) inner join [identity] i with(nolock) on e.id = i.entity_id  inner join resource_plugin rp with(nolock) on i.resource_plugin_id = rp.id and i.resource_plugin_id = rp.id inner join resource r with(nolock) on rp.resource_id = r.id  inner join resource_plugin_role_time_acl acl with(nolock) on acl.resource_plugin_id = rp.id  inner join role r1 with(nolock) on r1.id = acl.role_id inner join identity_role ir with(nolock) on ir.identity_id = i.id and ir.role_id = r1.id where r.enabled = 1 and rp.enabled = 1 group by i.id, i.temp_locked, e.id, r.name");

                if ((dtRegs == null) || (dtRegs.Rows.Count == 0))
                {
                    TextLog.Log("Engine", "Time access control", "\t0 registers to process");
                    return;
                }

                foreach (DataRow dr in dtRegs.Rows)
                {
                    try
                    {
                        using (EntityTimeControl eAcl = new EntityTimeControl(db, (Int64)dr["id"]))
                        {
                            StringBuilder tLog = new StringBuilder();
                            EntityTimeControl.ProccessLog log = new EntityTimeControl.ProccessLog(delegate(String text)
                            {
                                tLog.AppendLine(text);

#if DEBUG
                                TextLog.Log("Engine", "Time access control", text);
#endif
                            });

                            eAcl.OnLog += log;
                            eAcl.Process((Boolean)dr["temp_locked"]);
                            eAcl.OnLog -= log;

                            if ((Boolean)dr["temp_locked"] != eAcl.Locked)
                            {
                                db.AddUserLog((eAcl.Locked ? LogKey.User_TempLocked : LogKey.User_TempUnlocked), null, "Engine", UserLogLevel.Info, 0, 0, 0, 0, 0, Int64.Parse(dr["entity_id"].ToString()), Int64.Parse(dr["id"].ToString()), "Identity of resource " + dr["resource_name"] + (eAcl.Locked ? " locked by the time profile" : " unlocked by the time profile"), tLog.ToString());
                            }

                            tLog.Clear();
                            tLog = null;
                        }
                    }
                    catch (Exception ex) {
                        TextLog.Log("Engine", "Time access control", "\tError on time control processor " + ex.Message);
                    }
                }

                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on time control processor", ex.Message);
                TextLog.Log("Engine", "Time access control", "\tError on time control processor timer " + ex.Message);
            }
            finally
            {
                TextLog.Log("Engine", "Time access control", "Finishing processor timer");

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

                executing = false;
            }
        }
Exemplo n.º 14
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.º 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 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.º 16
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("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);
            }

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

            if (String.IsNullOrWhiteSpace(userid))
            {
                Error(ErrorType.InvalidRequest, "Parameter userid 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);
            }

            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("@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(false);
            }

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

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

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

                if ((dtRet != null) && (dtRet.Rows.Count > 0))
                {
                    database.AddUserLog(LogKey.User_IdentityRoleBind, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, u, (Int64)dtRet.Rows[0]["identity_id"], "Identity bind to role " + dtRet.Rows[0]["role_name"].ToString(), "");
                }
            }

            return(true);
        }
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("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.º 18
0
        //public static PluginConnectorBaseDeployPackage GetPackage(IAMDatabase db, Int64 proxyId, Int64 resourceId, Int64 pluginId, Int64 entityId, Int64 identityId, Boolean passwordAfterLogin, DateTime? lastChangePassword, String deploy_password_hash)
        public static PluginConnectorBaseDeployPackage GetPackage(IAMDatabase db, Int64 proxyId, Int64 resourcePluginId, Int64 entityId, Int64 identityId, Boolean passwordAfterLogin, DateTime?lastChangePassword, String deploy_password_hash, Boolean useSalt, Boolean saltOnEnd, String salt)
        {
            PluginConnectorBaseDeployPackage pkg = new PluginConnectorBaseDeployPackage();

            List <String> deployInfo = new List <string>();//"Identity addedd in deploy package with ";
            String        deployText = "";

            deployText = "Package ID: " + pkg.pkgId + Environment.NewLine;

            try
            {
                String sql = "select e.*, c.enterprise_id, rp.plugin_id, i.id identity_id, i.temp_locked, c.name context_name, e1.name enterprise_name, block_inheritance = case when exists (select 1 from identity_block_inheritance bi with(nolock) where bi.identity_id = i.id) then cast(1 as bit) else cast(0 as bit) end from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join resource_plugin rp with(nolock) on rp.id = i.resource_plugin_id inner join enterprise e1 with(nolock) on c.enterprise_id = e1.id where e.id = " + entityId + " and i.id = " + identityId;

                if (identityId == 0)
                {
                    sql = "select e.*, c.enterprise_id, rp.plugin_id, cast(0 as bigint) identity_id, cast(0 as bit) as temp_locked, c.name context_name, e1.name enterprise_name, cast(0 as bit) as block_inheritance from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id cross join resource_plugin rp with(nolock) inner join enterprise e1 with(nolock) on c.enterprise_id = e1.id where e.id = " + entityId;
                }

                DataTable dtEnt = db.Select(sql);
                if ((dtEnt == null) || (dtEnt.Rows.Count == 0))
                {
                    throw new Exception("Entity/Identity not found");
                }

                //DataTable dtPlugin = db.Select("select p.* from plugin p where p.id = " + pluginId);
                DataTable dtPlugin = db.Select("select distinct p.*, rp.resource_id from plugin p inner join resource_plugin rp on rp.plugin_id = p.id inner join resource r on rp.resource_id = r.id inner join entity e on e.context_id = r.context_id where rp.id = " + resourcePluginId + " and e.id = " + entityId);
                if ((dtPlugin == null) || (dtPlugin.Rows.Count == 0))
                {
                    throw new Exception("Plugin not found or not linked in the same context of entity");
                }

                if ((Boolean)dtEnt.Rows[0]["block_inheritance"])
                {
                    throw new Exception("Inheritance blocked");
                }

                Int64 resourceId = (Int64)dtPlugin.Rows[0]["resource_id"];
                Int64 pluginId   = (Int64)dtPlugin.Rows[0]["id"];

                //Define as pripriedades gerais
                pkg.registryId         = dtEnt.Rows[0]["id"] + "-" + DateTime.Now.ToString("yyyyMMddHHmmss");
                pkg.entityId           = entityId;
                pkg.identityId         = identityId;
                pkg.fullName           = new FullName(dtEnt.Rows[0]["full_name"].ToString());
                pkg.login              = dtEnt.Rows[0]["login"].ToString();
                pkg.lastChangePassword = (lastChangePassword.HasValue ? lastChangePassword.Value.ToString("o") : null);


                pkg.locked             = (Boolean)dtEnt.Rows[0]["locked"];
                pkg.temp_locked        = (Boolean)dtEnt.Rows[0]["temp_locked"];
                pkg.mustChangePassword = (Boolean)dtEnt.Rows[0]["must_change_password"];
                pkg.deleted            = (Boolean)dtEnt.Rows[0]["deleted"];

                pkg.enterprise = dtEnt.Rows[0]["enterprise_name"].ToString();
                pkg.context    = dtEnt.Rows[0]["context_name"].ToString();

                if ((Boolean)dtEnt.Rows[0]["deleted"])
                {
                    db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "Deploy to delete identity");
                }

                //Container
                pkg.container = "";
                try
                {
                    DataTable dtUserContainer = db.Select("select top 1 c.* from [container] c with(nolock) inner join entity_container ec with(nolock) on c.id = ec.container_id where ec.entity_id = " + entityId);
                    if ((dtUserContainer != null) && (dtUserContainer.Rows.Count > 0))
                    {
                        List <String> path = new List <string>();
                        path.Add(dtUserContainer.Rows[0]["name"].ToString());

                        if ((Int64)dtUserContainer.Rows[0]["parent_id"] > 0)
                        {
                            DataTable dtContainers = db.Select("select c.* from container c with(nolock)");
                            if ((dtContainers != null) || (dtContainers.Rows.Count > 0))
                            {
                                Func <Int64, Boolean> chields = null;
                                chields = new Func <Int64, Boolean>(delegate(Int64 root)
                                {
                                    foreach (DataRow dr in dtContainers.Rows)
                                    {
                                        if (((Int64)dr["id"] == root))
                                        {
                                            path.Add(dr["name"].ToString());
                                            chields((Int64)dr["parent_id"]);
                                            break;
                                        }
                                    }

                                    return(true);
                                });

                                chields((Int64)dtUserContainer.Rows[0]["parent_id"]);
                            }
                        }

                        path.Reverse();
                        pkg.container = "\\" + String.Join("\\", path);
                    }
                }
                catch { }

                //Senha
                pkg.password = "";
                if ((dtEnt.Rows[0]["password"] != DBNull.Value) && (dtEnt.Rows[0]["password"].ToString().Trim() != ""))
                {
                    //Este recurso x plugin só permite o deploy da SENHA após o primeiro login
                    if ((!passwordAfterLogin) || ((passwordAfterLogin) && (dtEnt.Rows[0]["last_login"] != DBNull.Value)))
                    {
                        try
                        {
                            String pwd = "";
                            using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, (Int64)dtEnt.Rows[0]["enterprise_id"]))
                                using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(dtEnt.Rows[0]["password"].ToString())))
                                    pwd = Encoding.UTF8.GetString(cApi.clearData);

                            //Verifica se usará SALT
                            if (useSalt)
                            {
                                if (!String.IsNullOrWhiteSpace(salt))
                                {
                                    if (saltOnEnd)
                                    {
                                        deployInfo.Add("password + SALT");
                                        pwd = pwd + salt.Trim();
                                    }
                                    else
                                    {
                                        deployInfo.Add("SALT + password");
                                        pwd = salt.Trim() + pwd;
                                    }
                                }
                                else
                                {
                                    deployInfo.Add("salt is empty");
                                }
                            }
                            else
                            {
                                deployInfo.Add("no salt");
                            }

                            if (!String.IsNullOrEmpty(deploy_password_hash))
                            {
                                switch (deploy_password_hash.ToLower())
                                {
                                case "md5":
                                    using (MD5 hAlg = MD5.Create())
                                        pkg.password = ComputeHash(hAlg, pwd).ToUpper();
                                    pkg.hash_alg = HashAlg.MD5;
                                    deployInfo.Add("MD5 password");
                                    break;

                                case "sha1":
                                    using (SHA1 hAlg = SHA1.Create())
                                        pkg.password = ComputeHash(hAlg, pwd).ToUpper();
                                    pkg.hash_alg = HashAlg.SHA1;
                                    deployInfo.Add("SHA1 password");
                                    break;

                                case "sha256":
                                    using (SHA256 hAlg = SHA256.Create())
                                        pkg.password = ComputeHash(hAlg, pwd).ToUpper();
                                    pkg.hash_alg = HashAlg.SHA256;
                                    deployInfo.Add("SHA256 password");
                                    break;

                                case "sha512":
                                    using (SHA512 hAlg = SHA512.Create())
                                        pkg.password = ComputeHash(hAlg, pwd).ToUpper();
                                    pkg.hash_alg = HashAlg.SHA512;
                                    deployInfo.Add("SHA512 password");
                                    break;

                                default:
                                    //Nenhum algoritmo de hash
                                    pkg.password = pwd;
                                    pkg.hash_alg = HashAlg.None;
                                    deployInfo.Add("clear text password");
                                    break;
                                }
                            }
                            else
                            {
                                pkg.password = pwd;
                                pkg.hash_alg = HashAlg.None;
                                deployInfo.Add("clear text password");
                            }


                            deployText += "User password added in deploy" + Environment.NewLine;
                            //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password added in deploy");
                        }
                        catch (Exception ex)
                        {
                            deployInfo.Add("no password");
                            deployText += "User password not deployed because a erro on decrypt password: "******"Deploy", UserLogLevel.Warning, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password not deployed because a erro on decrypt password: "******"no password");
                        deployText += "User password not deployed because the user is not logged in yet" + Environment.NewLine;
                        //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Debug, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password not deployed because the user is not logged in yet");
                    }
                }
                else
                {
                    deployInfo.Add("no password");
                    deployText += "User password is empty and not deployed" + Environment.NewLine;
                    //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Debug, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "User password is empty and not deployed");
                }


                //Busca todas as propriedades com o mapping deste plugin, porém com dados vindos exclusivos da entidade
                DataTable dtEntField = db.Select("select pf.data_name, efe.value, pf.data_type from entity_field efe inner join entity e on efe.entity_id = e.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id =  " + resourcePluginId + ") pf on pf.field_id = efe.field_id where e.id =  " + pkg.entityId + " group by pf.data_name, efe.value, pf.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        if (!pkg.entiyData.Exists(d => (d.dataName == drEf["data_name"].ToString())))
                        {
                            pkg.entiyData.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                        }
                    }
                }


                //Busca todas as propriedades com o mapping deste plugin, porém com dados vindos dos plugins de entrada
                //Exclui os itens de nome e senha por ja terem sido colocados acima
                dtEntField = db.Select("select pf.data_name, ife.value, pf.data_type, rp.priority from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on i.resource_plugin_id = rp.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id =  " + resourcePluginId + ") pf on pf.field_id = ife.field_id where rp.enable_import = 1 and i.entity_id =  " + pkg.entityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by pf.data_name, ife.value, pf.data_type, rp.priority order by rp.priority desc, pf.data_name");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        if (!pkg.importsPluginData.Exists(d => (d.dataName == drEf["data_name"].ToString())))
                        {
                            pkg.importsPluginData.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                        }
                    }
                }

                //Busca todas as propriedades vinculadas a este identity
                //Exclui os itens de nome e senha por ja terem sido colocados acima
                dtEntField = db.Select("select m.data_name, ife.value, f.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on rp.id = i.resource_plugin_id and ife.field_id <> rp.name_field_id inner join resource r on r.context_id = e.context_id and rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.field_id = ife.field_id and m.is_password = 0 inner join field f on ife.field_id = f.id where i.entity_id =  " + pkg.entityId + " and i.id = " + identityId + " group by m.data_name, ife.value, f.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        pkg.pluginData.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                    }
                }

                //Busca todas as propriedades vinculadas aos outras identity
                //Exclui os itens de nome e senha por ja terem sido colocados acima
                dtEntField = db.Select("select m.data_name, ife.value, f.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on rp.id = i.resource_plugin_id and ife.field_id <> rp.name_field_id inner join resource r on r.context_id = e.context_id and rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.field_id = ife.field_id and m.is_password = 0 inner join field f on ife.field_id = f.id where i.entity_id =  " + pkg.entityId + " and i.id <> " + identityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by m.data_name, ife.value, f.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        pkg.properties.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                    }
                }

                //Busca todas as propriedades (independente do identity) usando o mapping deste plugin
                //Exclui o senha por ja tere sido colocado acima
                dtEntField = db.Select("select pf.data_name, ife.value, pf.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id = " + resourcePluginId + ") pf on pf.field_id = ife.field_id where i.entity_id =  " + pkg.entityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by pf.data_name, ife.value, pf.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        pkg.properties.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                    }
                }


                //Busca todas as propriedades da tabela entity_field (exclusiva para dados manuais) usando o mapping deste plugin
                //Exclui o senha por ja tere sido colocado acima
                dtEntField = db.Select("select pf.data_name, efe.value, pf.data_type from entity_field efe inner join entity e on efe.entity_id = e.id inner join (select m.field_id, m.data_name, f.data_type from resource_plugin rp inner join resource r on rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.is_password = 0 inner join field f on m.field_id = f.id where rp.id = " + resourcePluginId + ") pf on pf.field_id = efe.field_id where efe.entity_id = " + pkg.entityId + "  group by pf.data_name, efe.value, pf.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        pkg.properties.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                    }
                }


                //Busca somente as propriedades marcadas como ID ou Unique property
                //Exclui os itens de nome e senha por ja terem sido colocados acima
                dtEntField = db.Select("select m.data_name, ife.value, f.data_type from identity_field ife inner join [identity] i on ife.identity_id = i.id inner join entity e on i.entity_id = e.id inner join resource_plugin rp on rp.id = i.resource_plugin_id and ife.field_id <> rp.name_field_id inner join resource r on r.context_id = e.context_id and rp.resource_id = r.id inner join resource_plugin_mapping m on m.resource_plugin_id = rp.id and m.field_id = ife.field_id and m.is_password = 0 and (m.is_unique_property = 1 or m.is_unique_property = 1) inner join field f on ife.field_id = f.id where i.entity_id =  " + pkg.entityId + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by m.data_name, ife.value, f.data_type");
                if ((dtEntField != null) && (dtEntField.Rows.Count > 0))
                {
                    foreach (DataRow drEf in dtEntField.Rows)
                    {
                        pkg.ids.Add(new PluginConnectorBasePackageData(drEf["data_name"].ToString(), ConvertoToString(dtEntField.Columns["value"], drEf), drEf["data_type"].ToString()));
                    }
                }


                //RBAC
                //Ações das roles desta identity para este resource x plugin
                DataTable dtRoleAction = db.Select("select i.id identity_id, r.* from [identity] i inner join [entity] e on e.id = i.entity_id inner join identity_role ir on ir.identity_id = i.id  inner join (select rp.id resource_plugin_id, rp.plugin_id, rp.resource_id, r.name role_name, rpa.id action_id, rpa.role_id, rpa.action_key, rpa.action_add_value, rpa.action_del_value, rpa.additional_data from resource_plugin rp inner join resource_plugin_role rpr on rpr.resource_plugin_id = rp.id inner join resource_plugin_role_action rpa on rpa.resource_plugin_id = rp.id inner join [role] r on r.id = rpa.role_id and r.id = rpr.role_id) r on r.role_id = ir.role_id where r.resource_plugin_id = " + resourcePluginId + " AND e.id = " + entityId);
                if ((dtRoleAction != null) && (dtRoleAction.Rows.Count > 0))
                {
                    foreach (DataRow drR in dtRoleAction.Rows)
                    {
                        pkg.pluginAction.Add(new PluginConnectorBaseDeployPackageAction(PluginActionType.Add, drR["role_name"].ToString(), drR["action_key"].ToString(), drR["action_add_value"].ToString(), (drR["additional_data"] != DBNull.Value ? drR["additional_data"].ToString() : null)));
                        //db.AddUserLog(LogKey.Role_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "Role: " + drR["role_name"].ToString());
                        deployInfo.Add("role " + drR["role_name"].ToString());
                        deployText += "role " + drR["role_name"].ToString() + Environment.NewLine;
                    }
                }

                db.AddUserLog(LogKey.Role_Deploy, null, "Deploy", UserLogLevel.Info, proxyId, 0, 0, resourceId, pluginId, (Int64)dtEnt.Rows[0]["id"], (Int64)dtEnt.Rows[0]["identity_id"], "Identity addedd in deploy package with: " + String.Join(", ", deployInfo), deployText);
            }
            finally
            {
                if (deployInfo != null)
                {
                    deployInfo.Clear();
                }
                deployInfo = null;

                deployText = "";
            }

            return(pkg);
        }
Exemplo n.º 19
0
        private void BuildBackup()
        {
            StringBuilder bkpLog = new StringBuilder();

            IAMDatabase db = null;

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


                bkpLog.AppendLine("Listando tabelas da base de dados...");

                DataTable dtS = db.Select("select TABLE_NAME from information_schema.tables where TABLE_TYPE = 'BASE TABLE' order by TABLE_NAME");

                if ((dtS == null) || (dtS.Rows.Count == 0))
                {
                    bkpLog.AppendLine("Listagem de tabelas vazia ou nula");
                    throw new Exception("Table list is null or empty");
                }

                bkpLog.AppendLine(dtS.Rows.Count + " tabelas");


                FileInfo bkpFile = new FileInfo(Path.Combine(Path.Combine(basePath, "Backup"), "bkp-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm") + ".iambkp"));
                if (!bkpFile.Directory.Exists)
                {
                    bkpFile.Directory.Create();
                }

                bkpLog.AppendLine("Criando arquivo de backup: " + bkpFile.FullName);

                using (SqliteBase exportDB = new SqliteBase(bkpFile))
                {
                    foreach (DataRow drSrc in dtS.Rows)
                    {
                        String tableName = drSrc["TABLE_NAME"].ToString();

                        bkpLog.AppendLine("Exportando tabela: " + tableName);
                        Console.WriteLine(tableName);


                        DataTable dtSchema = db.GetSchema(tableName);

                        StringBuilder createCmd = new StringBuilder();

                        createCmd.AppendLine("DROP TABLE IF EXISTS [" + tableName.ToLower() + "];");

                        /*
                         * CREATE TABLE [Events] (
                         * id INTEGER PRIMARY KEY AUTOINCREMENT,
                         * test_id TEXT NOT NULL,
                         * date datetime not null  DEFAULT (datetime('now','localtime')),
                         * event_text TEXT NULL
                         * );*/
                        List <String> columns = new List <string>();

                        bkpLog.AppendLine("Criando estrutura da tabela");
                        try
                        {
                            foreach (DataColumn dc in dtSchema.Columns)
                            {
                                if (dc.DataType.Equals(typeof(Int32)) || dc.DataType.Equals(typeof(Int64)))
                                {
                                    columns.Add("[" + dc.ColumnName + "] INTEGER NULL");
                                }
                                else if (dc.DataType.Equals(typeof(DateTime)))
                                {
                                    columns.Add("[" + dc.ColumnName + "] datetime NULL");
                                }
                                else
                                {
                                    columns.Add("[" + dc.ColumnName + "] TEXT NULL");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            bkpLog.AppendLine("Erro ao listar as colunas da tabela '" + tableName + "': " + ex.Message);
                            TextLog.Log("Backup", "\tErro ao listar as colunas da tabela '" + tableName + "': " + ex.Message);
                            throw ex;
                        }


                        try
                        {
                            createCmd.AppendLine("CREATE TABLE [" + tableName.ToLower() + "] (");

                            createCmd.AppendLine(String.Join(", " + Environment.NewLine, columns));

                            createCmd.AppendLine(");");

                            exportDB.ExecuteNonQuery(createCmd.ToString());
                        }
                        catch (Exception ex)
                        {
                            bkpLog.AppendLine("Erro ao criando tabela '" + tableName + "': " + ex.Message);
                            TextLog.Log("Backup", "\tErro ao criando tabela '" + tableName + "': " + ex.Message);
                            throw ex;
                        }

                        //Copiando dados das tabelas
                        try
                        {
                            bkpLog.AppendLine("Copiando dados");

                            if (tableName.ToLower() == "logs")
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select l.* from [logs] l with(nolock) inner join [entity_timeline] et with(nolock) on et.log_id = l.id");

                                exportDB.BulkCopy(dtSrcData, tableName.ToLower());
                            }
                            else if (tableName.ToLower() == "entity")
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)");

                                exportDB.BulkCopy(dtSrcData, tableName.ToLower());
                            }
                            else
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)");

                                exportDB.BulkCopy(dtSrcData, tableName.ToLower());
                            }
                        }
                        catch (Exception ex)
                        {
                            bkpLog.AppendLine("Erro copiando dados da tabela '" + tableName + "': " + ex.Message);
                            TextLog.Log("Backup", "\tErro copiando dados da tabela '" + tableName + "': " + ex.Message);
                            //throw ex;
                        }
                    }

                    //No final de todo o processo atualiza as senhas como cleartext
                    try
                    {
                        bkpLog.AppendLine("Atualizando as senhas das entidades");
                        DataTable dtEnt = db.ExecuteDataTable("select id from [enterprise] with(nolock)");

                        foreach (DataRow drEnt in dtEnt.Rows)
                        {
                            using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, (Int64)drEnt["id"]))
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select e.id, e.password, c.enterprise_id from [entity] e with(nolock) inner join [context] c with(nolock) on e.context_id = c.id where c.enterprise_id = " + drEnt["id"]);

                                //Atualiza senha em clear text de cada usu[ario
                                foreach (DataRow drUser in dtSrcData.Rows)
                                {
                                    try
                                    {
                                        using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(drUser["password"].ToString())))
                                        {
                                            exportDB.ExecuteNonQuery("update entity set password = '******' where id = " + drUser["id"]);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        bkpLog.AppendLine("Erro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message);
                                        TextLog.Log("Backup", "\tErro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message);
                                        //throw ex;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        bkpLog.AppendLine("Erro atualizando as senhas para cleartext: " + ex.Message);
                        TextLog.Log("Backup", "\tErro atualizando as senhas para cleartext: " + ex.Message);
                        //throw ex;
                    }
                }



                db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Backup realizado com sucesso", bkpLog.ToString());
            }
            catch (Exception ex)
            {
                TextLog.Log("Backup", "\tError building backup: " + ex.Message);
                bkpLog.AppendLine("Error building backup: " + ex.Message);
                try
                {
                    db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Backup finalizado com erro", bkpLog.ToString());
                }
                catch { }
            }
            finally
            {
                if (bkpLog != null)
                {
                    bkpLog = null;
                }

                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Exemplo n.º 20
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.º 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 Dictionary <String, Object> newfilter(SqlConnection sqlConnection, Dictionary <String, Object> parameters)
        {
            if (!parameters.ContainsKey("name"))
            {
                Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null);
                return(null);
            }

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

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


            DbParameterCollection par2 = new DbParameterCollection();

            par2.Add("@enterprise_id", typeof(Int64)).Value             = this._enterpriseId;
            par2.Add("@filter_name", typeof(String), name.Length).Value = name;

            DataTable dtF1 = ExecuteDataTable(sqlConnection, "select * from filters with(nolock) where enterprise_id = @enterprise_id and name = @filter_name", CommandType.Text, par2, null);

            if ((dtF1 != null) && (dtF1.Rows.Count > 0))
            {
                Error(ErrorType.InvalidRequest, "Filter with the same name already exists.", "", null);
                return(null);
            }


            List <String> log              = new List <String>();
            Boolean       updateName       = false;
            Boolean       updateConditions = false;
            FilterRule    filterData       = getFilterData(sqlConnection, "", parameters, log, out updateName, out updateConditions);

            if (filterData == null)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(filterData.FilterName))
            {
                Error(ErrorType.InvalidRequest, "Parameter name is not defined.", "", null);
                return(null);
            }

            if (filterData.FilterGroups.Count == 0)
            {
                Error(ErrorType.InvalidRequest, "Filter conditions is empty.", "", null);
                return(null);
            }

            DataTable dtFilter = null;

            SqlTransaction trans = sqlConnection.BeginTransaction();

            try
            {
                DbParameterCollection par = new DbParameterCollection();
                par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId;
                par.Add("@filter_name", typeof(String)).Value  = filterData.FilterName;

                dtFilter = ExecuteDataTable(sqlConnection, "sp_new_filter", CommandType.StoredProcedure, par, trans);
                if ((dtFilter == null) && (dtFilter.Rows.Count == 0))
                {
                    Error(ErrorType.InvalidRequest, "Error on insert filter.", "", null);
                    return(null);
                }

                if (updateConditions && filterData.FilterGroups.Count > 0)
                {
                    foreach (FilterGroup g in filterData.FilterGroups)
                    {
                        foreach (FilterCondition f in g.FilterRules)
                        {
                            DbParameterCollection p2 = new DbParameterCollection();
                            p2.Add("@filter_id", typeof(Int64)).Value       = (Int64)dtFilter.Rows[0]["id"];
                            p2.Add("@group_id", typeof(String)).Value       = g.GroupId;
                            p2.Add("@group_selector", typeof(String)).Value = g.Selector.ToString();
                            p2.Add("@field_id", typeof(String)).Value       = f.FieldId;
                            p2.Add("@text", typeof(String)).Value           = f.DataString;
                            p2.Add("@condition", typeof(String)).Value      = f.ConditionType.ToString();
                            p2.Add("@selector", typeof(String)).Value       = f.Selector.ToString();

                            log.Add("Condition inserted: group = " + g.GroupId + ", condition = " + f.ToString());

                            ExecuteNonQuery(sqlConnection, "insert into filters_conditions ([filter_id] ,[group_id] ,[group_selector] ,[field_id] ,[text] ,[condition] ,[selector]) VALUES (@filter_id,@group_id,@group_selector,@field_id,@text,@condition,@selector)", CommandType.Text, p2, trans);
                        }
                    }
                    log.Add("");
                }

                using (IAMDatabase db = new IAMDatabase(sqlConnection))
                    db.AddUserLog(LogKey.Filter_Inserted, null, "API", UserLogLevel.Info, 0, this._enterpriseId, 0, 0, 0, 0, 0, "Filter added", String.Join("\r\n", log), acl.EntityId, trans);

                trans.Commit();
                trans = null;
            }
            catch (Exception ex)
            {
                Error(ErrorType.InvalidRequest, "Error on insert filter", "", null);
                return(null);
            }
            finally
            {
                //Saída sem aviso, ou seja, erro
                if (trans != null)
                {
                    trans.Rollback();
                }
            }



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

            parameters2.Add("filterid", dtFilter.Rows[0]["id"]);

            return(get(sqlConnection, parameters2));
        }
Exemplo n.º 22
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.º 23
0
        /*[{"data_name":"id","field_id":"16","data_type":"string","value":"110059940913696826169"},{"data_name":"lastLoginTime","field_id":"14","data_type":"datetime","value":"1969- 12-31T22:00:00.0000000- 02:00"},{"data_name":"creationTime","field_id":"12","data_type":"datetime","value":"2013-12- 05T06:01:54.0000000- 02:00"},{"data_name":"primaryEmail","field_id":"4","data_type":"string","value":"*****@*****.**"},{"data_name":"fullname","field_id":"1","data_type":"string","value":"Adriana Aparecida Goll Tenorio"}] [{"data_name":"id","field_id":"16","data_type":"string","value":"110059940913696826169"},{"data_name":"lastLoginTime","field_id":"14","data_type":"datetime","value":"1969- 12-31T22:00:00.0000000- 02:00"},{"data_name":"creationTime","field_id":"12","data_type":"datetime","value":"2013-12- 05T06:01:54.0000000- 02:00"},{"data_name":"primaryEmail","field_id":"4","data_type":"string","value":"*****@*****.**"},{"data_name":"fullname","field_id":"1","data_type":"string","value":"Adriana Aparecida Goll Tenorio"}]*/

        static public void auditReport(IAMDatabase db, DataTable dtS, List <MailAddress> recipents)
        {
            Int64 enterpriseId = (Int64)dtS.Rows[0]["enterprise_id"];

            List <FileInfo> files = new List <FileInfo>();
            StringBuilder   body  = new StringBuilder();

            DataTable dtContext = db.Select("select distinct c.* from context c with(nolock) where c.enterprise_id = " + enterpriseId + " order by name");

            if ((dtContext != null) && (dtContext.Rows.Count > 0))
            {
                foreach (DataRow drC in dtContext.Rows)
                {
                    PDFReport report = new PDFReport(dtS.Rows[0]["title"].ToString() + " - " + drC["name"], "SafeTrend - SafeID v1.0");
                    body.AppendLine(dtS.Rows[0]["title"].ToString() + " - " + drC["name"]);


                    FileInfo tmpFile = new FileInfo(Path.Combine(Path.GetTempPath(), "audit-" + DateTime.Now.ToString("yyyyMMdd") + "-" + drC["id"] + "-" + DateTime.Now.ToString("hhmmssfffff") + ".pdf"));
                    if (tmpFile.Exists)
                    {
                        tmpFile.Delete();
                    }

                    body.AppendLine("    Arquivo: " + tmpFile.Name);
                    Int64 erroCount = 0;

                    DataTable dtResource = db.Select("select distinct r.* from resource r with(nolock) inner join resource_plugin rp  with(nolock) on rp.resource_id = r.id inner join context c with(nolock) on c.id = r.context_id where c.id = " + drC["id"] + " order by name");
                    if ((dtResource != null) && (dtResource.Rows.Count > 0))
                    {
                        foreach (DataRow drR in dtResource.Rows)
                        {
                            DataTable dtRP = db.Select("select distinct rp.*, p.name plugin_name, p.scheme, p.id plugin_id from resource r with(nolock) inner join resource_plugin rp with(nolock) on rp.resource_id = r.id inner join plugin p with(nolock) on rp.plugin_id = p.id where r.id = " + drR["id"] + " order by p.name");
                            if ((dtRP != null) && (dtRP.Rows.Count > 0))
                            {
                                report.AddH1("Recurso " + drR["name"]);

                                foreach (DataRow drRP in dtRP.Rows)
                                {
                                    report.AddH2("Plugin " + drRP["plugin_name"]);

                                    PluginConfig pluginConfig = new PluginConfig(db.Connection, drRP["scheme"].ToString(), (Int64)drRP["plugin_id"], (Int64)drRP["id"]);

                                    DataTable dtAudit = db.Select("select * from audit_identity a where resource_plugin_id = " + drRP["id"] + " and update_date >= DATEADD(day,-15,getdate()) order by full_name");
                                    if ((dtAudit != null) && (dtAudit.Rows.Count > 0))
                                    {
                                        Int64 count = 1;

                                        foreach (DataRow drAudit in dtAudit.Rows)
                                        {
                                            erroCount++;

                                            try
                                            {
                                                report.AddParagraph(String.Format("{0:0000}. {1}", count, drAudit["full_name"].ToString()), 1, 3, true);

                                                switch (drAudit["event"].ToString().ToLower())
                                                {
                                                case "not_exists":
                                                    report.AddParagraph("Problema encontrado: Usuário inexistente no SafeID", 2, 3, false);
                                                    break;

                                                case "locked":
                                                    report.AddParagraph("Problema encontrado: Usuário inexistente no SafeID e não pode ser inserido pois está com status de bloqueado.", 2, 3, false);
                                                    break;

                                                case "input_filter_empty":
                                                    report.AddParagraph("Problema encontrado: Informação para identificação não encontrado.", 2, 3, false);
                                                    break;

                                                default:
                                                    report.AddParagraph("Problema encontrado: desconhecido", 2, 3, false);
                                                    break;
                                                }


                                                report.AddParagraph("Registrio criado em " + MessageResource.FormatDate((DateTime)drAudit["create_date"], false) + " e atualizado em " + MessageResource.FormatDate((DateTime)drAudit["update_date"], false), 2, 3, false);


                                                List <FieldItem> fields = JSON.Deserialize <List <FieldItem> >(drAudit["fields"].ToString());

                                                List <String> keys   = new List <string>();
                                                List <String> others = new List <string>();

                                                foreach (FieldItem fi in fields)
                                                {
                                                    foreach (PluginConfigMapping m in pluginConfig.mapping)
                                                    {
                                                        if ((m.data_name.ToLower() == fi.data_name.ToLower()))
                                                        {
                                                            if (m.is_id || m.is_unique_property)
                                                            {
                                                                if (!keys.Contains(m.field_name + " = " + fi.value))
                                                                {
                                                                    keys.Add(m.field_name + " = " + fi.value);
                                                                }
                                                            }
                                                            else
                                                            {
                                                                if (!others.Contains(m.field_name + " = " + fi.value))
                                                                {
                                                                    others.Add(m.field_name + " = " + fi.value);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }


                                                report.AddParagraph("Identificadores: ", 2, 3, false);
                                                for (Int32 c = 0; c < keys.Count; c++)
                                                {
                                                    report.AddParagraph(keys[c], 3, (c == keys.Count - 1 ? 3 : 0), false);
                                                }


                                                report.AddParagraph("Outros dados: ", 2, 3, false);
                                                for (Int32 c = 0; c < others.Count; c++)
                                                {
                                                    report.AddParagraph(others[c], 3, (c == others.Count - 1 ? 6 : 0), false);
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                report.AddParagraph("Erro processando informação: " + ex.Message, 1, 0, false);
                                            }

                                            count++;
                                        }
                                    }
                                    else
                                    {
                                        report.AddParagraph("Nenhuma inconsistência encontrada", 1, 0, false);
                                    }
                                }
                            }
                            else
                            {
                                report.AddH1("Recurso " + drR["name"], false);
                                report.AddParagraph("Nenhum plugin vinculado a este recurso.");
                            }

                            //select distinct rp.* from resource r with(nolock) inner join resource_plugin rp with(nolock) on rp.resource_id = r.id where r.id = 1
                        }
                    }

                    body.AppendLine("    Inconsistências reportadas: " + erroCount);

                    //Salva e envia o relatório
                    report.SaveToFile(tmpFile.FullName);

                    files.Add(new FileInfo(tmpFile.FullName));

                    body.AppendLine("");
                }
            }

            List <Attachment> atts = new List <Attachment>();

            foreach (FileInfo f in files)
            {
                atts.Add(new Attachment(f.FullName));
            }

            try
            {
                sendEmail(db, dtS.Rows[0]["title"].ToString(), recipents, body.ToString(), false, atts);
            }
            catch (Exception ex)
            {
                db.AddUserLog(LogKey.Report, DateTime.Now, "Report", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Erro sending report", ex.Message);
            }

            //Exclui os arquivos temporários
            foreach (FileInfo f in files)
            {
                try
                {
                    f.Delete();
                }
                catch { }
            }
        }
Exemplo n.º 24
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.º 25
0
        static public void integrityTextReport(IAMDatabase db, DataTable dtS, List <MailAddress> recipents)
        {
            StringBuilder errors = new StringBuilder();

            DataTable dtL = db.Select("select l.text from logs l where text like 'Integrity check error: Multiplus entities%' and l.date >= DATEADD(day,-1,getdate()) and l.enterprise_id = " + dtS.Rows[0]["enterprise_id"] + " group by l.text");

            if (dtL == null)
            {
                return;
            }

            DataTable dtErrors = new DataTable();

            dtErrors.Columns.Add("text", typeof(String));

            Dictionary <String, String> title = new Dictionary <string, string>();

            title.Add("text", "Texto");

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

            foreach (DataRow dU in dtL.Rows)
            {
                try
                {
                    DataRow newItem = dtErrors.NewRow();
                    newItem["text"] = dU["text"];

                    dtErrors.Rows.Add(newItem.ItemArray);


                    //Captura somente os IDs das entidades
                    Regex rex = new Regex(@"\((.*?)\)");
                    Match m   = rex.Match(dU["text"].ToString());
                    if (m.Success)
                    {
                        String[] entities = m.Groups[1].Value.Replace(" ", "").Split(",".ToCharArray());
                        duplicatedEntities.AddRange(entities);
                    }
                }
                catch (Exception ex)
                {
                    errors.AppendLine("Error processing registry: " + ex.Message);
                }
            }



            Dictionary <String, String> title2 = new Dictionary <string, string>();

            title2.Add("id", "Entity ID");
            title2.Add("login", "Login");
            title2.Add("full_name", "Nome Completo");
            title2.Add("change_password", "Ultima troca de senha");
            title2.Add("last_login", "Ultimo Login ");


            DataTable dtUsr = new DataTable();

            dtUsr.Columns.Add("id", typeof(Int64));
            dtUsr.Columns.Add("login", typeof(String));
            dtUsr.Columns.Add("full_name", typeof(String));
            dtUsr.Columns.Add("change_password", typeof(DateTime));
            dtUsr.Columns.Add("last_login", typeof(DateTime));

            //select e.id, e.login, e.full_name, e.change_password, e.last_login from entity e where id in (10583, 13065) order by e.full_name

            DataTable dtU = db.Select("select e.id, e.login, e.full_name, e.change_password, e.last_login from entity e where id in (" + String.Join(",", duplicatedEntities) + ") order by e.full_name");

            if (errors.ToString() != "")
            {
                db.AddUserLog(LogKey.Report, null, "Report", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Report error", errors.ToString());
            }

            ReportBase rep1 = new ReportBase(dtErrors, title);

            List <Attachment> atts = new List <Attachment>();

            try
            {
                using (MemoryStream ms1 = new MemoryStream(Encoding.UTF8.GetBytes(rep1.GetTXT())))
                {
                    atts.Add(new Attachment(ms1, "integrity-check.txt"));

                    if (dtU != null)
                    {
                        ReportBase rep2 = new ReportBase(dtU, title2);
                        using (MemoryStream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(rep2.GetTXT())))
                        {
                            atts.Add(new Attachment(ms2, "integrity-users.txt"));

                            sendEmail(db, dtS.Rows[0]["title"].ToString(), recipents, dtL.Rows.Count + " erros de integridade", false, atts);
                        }
                    }
                    else
                    {
                        sendEmail(db, dtS.Rows[0]["title"].ToString(), recipents, dtL.Rows.Count + " erros de integridade", false, atts);
                    }
                }
            }
            catch (Exception ex)
            {
                db.AddUserLog(LogKey.Report, DateTime.Now, "Report", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Erro sending report", ex.Message);
            }
        }
Exemplo n.º 26
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.º 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
        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.º 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 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);
        }