Exemplo n.º 1
0
    public static Boolean SendCode(Int64 entityId, String sendTo, Boolean isMail, Boolean isSMS, out String error)
    {
        error = "";



        try
        {
            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
            {
                DataTable tmp = db.Select(String.Format("select id, recovery_code from entity with(nolock) where deleted = 0 and id = {0}", entityId));
                if ((tmp == null) || (tmp.Rows.Count == 0))
                {
                    error = MessageResource.GetMessage("entity_not_found");
                    return(false);
                }


                if (isMail)
                {
                    Tools.Tool.sendEmail("Password recover code", sendTo, "Code: " + tmp.Rows[0]["recovery_code"].ToString(), false);
                }
            }
            return(true);
        }
        catch (Exception ex) {
            error = ex.Message;
            return(false);
        }
    }
Exemplo n.º 2
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.º 3
0
    /*
     * static public LoginResult AuthUser(Page page, String username, String password)
     * {
     *  return AuthUser(page, username, password, false);
     * }
     *
     * static public LoginResult AuthUser(Page page, String username, String password, Boolean byPassPasswordCheck)
     * {
     *
     *  try
     *  {
     *      if ((username == null) || (username.Trim() == "") || (username == password) || (username.Trim() == ""))
     *          return new LoginResult(false, MessageResource.GetMessage("valid_username_pwd"));
     *
     *      Int64 enterpriseId = 0;
     *      if ((page.Session["enterprise_data"]) != null && (page.Session["enterprise_data"] is EnterpriseData))
     *          enterpriseId = ((EnterpriseData)page.Session["enterprise_data"]).Id;
     *
     *      DbParameterCollection par = new DbParameterCollection();;
     *      par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId;
     *      par.Add("@login", typeof(String), username.Length).Value = username;
     *
     *      DataTable tmp = null;
     *
     *      using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
     *      {
     *          tmp = db.ExecuteDataTable("select distinct id, alias, full_name, login, enterprise_id, password, must_change_password from vw_entity_logins with(nolock) where deleted = 0 and enterprise_id = @enterprise_id and locked = 0 and (login = @login or value = @login)", CommandType.Text, par);
     *
     *          if ((tmp != null) && (tmp.Rows.Count > 0))
     *          {
     *              foreach (DataRow dr in tmp.Rows)
     *              {
     *
     *                  using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, enterpriseId))
     *                  using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString())))
     *                      if (byPassPasswordCheck || Encoding.UTF8.GetString(cApi.clearData) == password)
     *                      {
     *                          //Realiza o login
     *                          try
     *                          {
     *                              //Adiciona o ciookie do usuário
     *                              HttpCookie cookie = new HttpCookie("uid");
     *                              //Define o valor do cookie
     *                              cookie.Value = tmp.Rows[0]["id"].ToString();
     *                              //Time para expiração (1 min)
     *                              DateTime dtNow = DateTime.Now;
     *                              TimeSpan tsMinute = new TimeSpan(365, 0, 0, 0);
     *                              cookie.Expires = dtNow + tsMinute;
     *                              //Adiciona o cookie
     *                              page.Response.Cookies.Add(cookie);
     *                          }
     *                          catch { }
     *
     *                          LoginData l = new LoginData();
     *                          l.Alias = tmp.Rows[0]["alias"].ToString();
     *                          l.FullName = tmp.Rows[0]["full_name"].ToString();
     *                          l.Login = tmp.Rows[0]["login"].ToString();
     *                          l.Id = (Int64)tmp.Rows[0]["id"];
     *                          l.EnterpriseId = (Int64)tmp.Rows[0]["enterprise_id"];
     *
     *                          page.Session["login"] = l;
     *
     *                          db.ExecuteNonQuery("update entity set last_login = getdate() where id = " + l.Id, CommandType.Text, null);
     *
     *                          db.AddUserLog(LogKey.User_Logged, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, l.Id, 0, MessageResource.GetMessage("user_logged") + " " + Tools.Tool.GetIPAddress(), "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
     *
     *                          return new LoginResult(true, "User OK", (Boolean)tmp.Rows[0]["must_change_password"]);
     *                          break;
     *                      }
     *                      else
     *                      {
     *                          db.AddUserLog(LogKey.User_WrongPassword, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, (Int64)tmp.Rows[0]["id"], 0, MessageResource.GetMessage("user_wrong_password") + " " + Tools.Tool.GetIPAddress(), "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
     *                      }
     *              }
     *
     *              return new LoginResult(false, MessageResource.GetMessage("valid_username_pwd"));
     *          }
     *          else
     *          {
     *              db.AddUserLog(LogKey.User_WrongUserAndPassword, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, MessageResource.GetMessage("user_wrong_password") + " " + Tools.Tool.GetIPAddress(), "{ \"username\":\"" + username.Replace("'", "").Replace("\"", "") + "\", \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
     *              return new LoginResult(false, MessageResource.GetMessage("valid_username_pwd"));
     *          }
     *      }
     *  }
     *  catch (Exception ex)
     *  {
     *      Tools.Tool.notifyException(ex, page);
     *      return new LoginResult(false, "Internal error", ex.Message);
     *  }
     *  finally
     *  {
     *
     *  }
     *
     * }
     *
     *
     * static public LoginResult AuthUserByTicket(Page page, String ticket)
     * {
     *
     *  try
     *  {
     *      if ((ticket == null) || (ticket.Trim() == ""))
     *          return new LoginResult(false, MessageResource.GetMessage("invalid_ticket"));
     *
     *      Int64 enterpriseId = 0;
     *      if ((page.Session["enterprise_data"]) != null && (page.Session["enterprise_data"] is EnterpriseData))
     *          enterpriseId = ((EnterpriseData)page.Session["enterprise_data"]).Id;
     *
     *      DbParameterCollection par = new DbParameterCollection();;
     *      par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId;
     *      par.Add("@tgc", typeof(String), ticket.Length).Value = ticket;
     *
     *      using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
     *      {
     *
     *          DataTable tmp = db.ExecuteDataTable("select distinct l.id, l.alias, l.full_name, l.login, l.enterprise_id, l.password, l.must_change_password, s.id as service_id, s.service_uri, et.grant_ticket, et.long_ticket from vw_entity_logins l with(nolock)  inner join cas_entity_ticket et with(nolock) on et.entity_id = l.id inner join cas_service s with(nolock) on l.enterprise_id = s.enterprise_id and et.service_id = s.id where et.grant_ticket = @tgc and s.enterprise_id = @enterprise_id", CommandType.Text, par);
     *
     *          if ((tmp != null) && (tmp.Rows.Count > 0))
     *          {
     *              foreach (DataRow dr in tmp.Rows)
     *              {
     *
     *                  //Realiza o login
     *                  try
     *                  {
     *                      //Adiciona o ciookie do usuário
     *                      HttpCookie cookie = new HttpCookie("uid");
     *                      //Define o valor do cookie
     *                      cookie.Value = tmp.Rows[0]["id"].ToString();
     *                      //Time para expiração (1 min)
     *                      DateTime dtNow = DateTime.Now;
     *                      TimeSpan tsMinute = new TimeSpan(365, 0, 0, 0);
     *                      cookie.Expires = dtNow + tsMinute;
     *                      //Adiciona o cookie
     *                      page.Response.Cookies.Add(cookie);
     *                  }
     *                  catch { }
     *
     *                  LoginData l = new LoginData();
     *                  l.Alias = tmp.Rows[0]["alias"].ToString();
     *                  l.FullName = tmp.Rows[0]["full_name"].ToString();
     *                  l.Login = tmp.Rows[0]["login"].ToString();
     *                  l.Id = (Int64)tmp.Rows[0]["id"];
     *                  l.EnterpriseId = (Int64)tmp.Rows[0]["enterprise_id"];
     *
     *                  page.Session["login"] = l;
     *
     *                  db.ExecuteNonQuery("update entity set last_login = getdate() where id = " + l.Id, CommandType.Text, null);
     *
     *                  db.AddUserLog(LogKey.User_Logged, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, l.Id, 0, MessageResource.GetMessage("user_logged") + " " + Tools.Tool.GetIPAddress(), "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
     *
     *                  return new LoginResult(true, "User OK", (Boolean)tmp.Rows[0]["must_change_password"]);
     *                  break;
     *              }
     *
     *              return new LoginResult(false, MessageResource.GetMessage("invalid_ticket"));
     *          }
     *          else
     *          {
     *              db.AddUserLog(LogKey.User_WrongTicket, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, MessageResource.GetMessage("user_wrong_password") + " " + Tools.Tool.GetIPAddress(), "{ \"ticket\":\"" + ticket.Replace("'", "").Replace("\"", "") + "\", \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
     *              return new LoginResult(false, MessageResource.GetMessage("invalid_ticket"));
     *          }
     *      }
     *  }
     *  catch (Exception ex)
     *  {
     *      Tools.Tool.notifyException(ex, page);
     *      return new LoginResult(false, "Internal error");
     *  }
     *  finally
     *  {
     *
     *  }
     *
     *
     * }*/

    static public Int64 FindUser(Page page, String username, out String error)
    {
        try
        {
            if ((username == null) || (username.Trim() == ""))
            {
                error = MessageResource.GetMessage("valid_username");
                return(0);
            }
            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
            {
                DataTable tmp = db.Select(String.Format("select id, locked from vw_entity_logins with(nolock) where (login = '******' or value = '{0}') group by id, locked", Tools.Tool.TrataInjection(username)));
                if ((tmp == null) || (tmp.Rows.Count == 0))
                {
                    error = MessageResource.GetMessage("valid_username");
                    return(0);
                }
                else if (tmp.Rows.Count > 1)
                {
                    error = MessageResource.GetMessage("ambiguous_id");
                    return(0);
                }
                else if ((Boolean)tmp.Rows[0]["locked"])
                {
                    error = MessageResource.GetMessage("user_locked");
                    return(0);
                }
                else
                {
                    error = "";
                    return((Int64)tmp.Rows[0]["id"]);
                }
            }
        }
        catch (Exception ex)
        {
            error = MessageResource.GetMessage("internal_error");
            Tools.Tool.notifyException(ex, page);
            return(0);
        }
        finally
        {
        }
    }
Exemplo n.º 4
0
        private void DispatcherTimer(Object state)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            TextLog.Log("Dispatcher", "Starting dispatcher timer");
            try
            {
                IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();

                DataTable dtS = db.Select("select * from vw_schedules order by context_id, [order]");

                //Processa um a um dos agendamentos
                foreach (DataRow dr in dtS.Rows)
                {
                    CheckSchedule(db, (Int64)dr["schedule_id"], (Int64)dr["resource_plugin_id"], (Int64)dr["resource_id"], dr["schedule"].ToString(), (DateTime)dr["next"]);
                }

                dtS.Clear();
                dtS = null;

                db.closeDB();
                db.Dispose();
                db = null;
            }
            catch (Exception ex)
            {
                TextLog.Log("Dispatcher", "\tError on dispatcher timer " + ex.Message);
            }
            finally
            {
                TextLog.Log("Dispatcher", "Finishing dispatcher timer");
                executing = false;
            }
        }
Exemplo n.º 5
0
        public String Plugin()
        {
            String pluginId = "";

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

            EnterpriseData ent = (EnterpriseData)Page.Session["enterprise_data"];

            FlowData flowData = new FlowData();

            DataTable dtPlugins = null;

            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                dtPlugins = db.Select("select * from plugin where (enterprise_id = " + ent.Id + " or enterprise_id = 0) and id = " + pluginId);

            if (dtPlugins == null)
            {
                return("");
            }

            Node pNode = flowData.AddNode(dtPlugins.Rows[0]["name"].ToString(), 0, 1);

            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
            {
                switch (dtPlugins.Rows[0]["scheme"].ToString().ToLower())
                {
                case "connector":
                    DataTable dtResources = db.Select("select r.* from resource_plugin rp inner join resource r on r.id = rp.resource_id where rp.plugin_id = " + dtPlugins.Rows[0]["id"]);
                    if ((dtResources == null) && (dtResources.Rows.Count == 0))
                    {
                        Node resNode = flowData.AddNode("Nenhum recurso vinculado a este plugin", 1, 1, true);
                        flowData.AddConnection(pNode, resNode, "");
                    }
                    else
                    {
                        foreach (DataRow drRes in dtResources.Rows)
                        {
                            Node nResource = flowData.AddNode("Recurso: " + drRes["name"], 2, 1, true);
                            flowData.AddConnection(pNode, nResource, "");
                        }
                    }
                    break;

                case "agent":
                    DataTable dtProxy = db.Select("select * from proxy_plugin pp inner join proxy p on pp.proxy_id = p.id where pp.plugin_id = " + dtPlugins.Rows[0]["id"]);
                    if ((dtProxy == null) && (dtProxy.Rows.Count == 0))
                    {
                        Node errProxyNode = flowData.AddNode("Nenhum proxy vinculado a este plugin", 1, 1, true);
                        flowData.AddConnection(pNode, errProxyNode, "");
                    }
                    else
                    {
                        foreach (DataRow drProxy in dtProxy.Rows)
                        {
                            Node nProxy = flowData.AddNode("Proxy: " + drProxy["name"], 2, 1, true);
                            flowData.AddConnection(pNode, nProxy, "");
                        }
                    }
                    break;

                default:
                    Node errNode = flowData.AddNode("Tipo de plugin não reconhecido", 1, 1, true);
                    flowData.AddConnection(pNode, errNode, "");
                    break;
                }
            }
            return(flowData.ToJson());
        }
Exemplo n.º 6
0
        public String ContextFlow()
        {
            String contextid = "";

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

            EnterpriseData ent = (EnterpriseData)Page.Session["enterprise_data"];

            FlowData flowData = new FlowData();
            Node     eNode    = flowData.AddNode(ent.Name, 0, 1);

            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
            {
                DataTable dtCtx = db.Select("select * from context where enterprise_id = " + ent.Id + (contextid != "" ? " and id = " + contextid : ""));
                if (dtCtx == null)
                {
                    return("");
                }

                foreach (DataRow dr in dtCtx.Rows)
                {
                    Int64  contextID = (Int64)dr["id"];
                    String cName     = "Contexto: " + dr["name"];
                    Node   cNode     = flowData.AddNode(cName, 1, 1);
                    flowData.AddConnection(eNode, cNode, "");

                    Node roleNode = null;

                    /*
                     * DataTable dtRoles1 = DB.Select("select * from [role] e where e.context_id = " + contextID);
                     * if (dtRoles1 != null)
                     * {
                     *  roleNode = flowData.AddNode("Perfis", 6, dtRoles1.Rows.Count);
                     *  flowData.AddConnection(cNode, roleNode, "");
                     *
                     *  foreach (DataRow drR in dtRoles1.Rows)
                     *  {
                     *
                     *      Int64 irId = (Int64)drR["id"];
                     *
                     *      Node roleNameNode = flowData.AddNode("Perfil: " + drR["name"].ToString(), 7, 1);
                     *      flowData.AddConnection(roleNode, roleNameNode, "");
                     *
                     *  }
                     * }*/

                    Node userNode = flowData.AddNode("Usuários", 3, 1, true);
                    flowData.AddConnection(cNode, userNode, "");

                    DataTable dtEntity = db.Select("select count(*) qty from [entity] e where e.context_id = " + contextID);
                    if ((dtEntity == null) || (dtEntity.Rows.Count == 0) || ((Int32)dtEntity.Rows[0]["qty"] == 0))
                    {
                        Node entNode = flowData.AddNode("Nenhuma entidade vinculada a este contexto", 4, 1, true);
                        flowData.AddConnection(userNode, entNode, "");
                    }
                    else
                    {
                        String rpEntName = "Entidades";
                        Node   entNode   = flowData.AddNode(rpEntName, 4, (Int32)dtEntity.Rows[0]["qty"], true);
                        flowData.AddConnection(userNode, entNode, dtEntity.Rows[0]["qty"] + " entidades");

                        DataTable dtIdentity = db.Select("select COUNT(distinct i.id) qty from [identity] i inner join entity e on i.entity_id = e.id where e.context_id = " + contextID);
                        if ((dtIdentity == null) || (dtIdentity.Rows.Count == 0))
                        {
                            Node identNode = flowData.AddNode("Nenhuma identidade vinculado a esta entidade", 4, 1, true);
                            flowData.AddConnection(entNode, identNode, "");
                        }
                        else
                        {
                            String rpIdentName = "Identidades";
                            Node   identNode   = flowData.AddNode(rpIdentName, 5, (Int32)dtIdentity.Rows[0]["qty"], true);
                            flowData.AddConnection(entNode, identNode, dtIdentity.Rows[0]["qty"] + " identidades");

                            DataTable dtResources = db.Select("select name, qty = (select COUNT(distinct i.id) from resource r1 inner join resource_plugin rp on r1.id = rp.resource_id inner join [identity] i on i.resource_plugin_id = rp.id inner join entity e on i.entity_id = e.id where r1.name = r.name and r1.context_id = r.context_id) from resource r  where r.context_id = " + contextID + " group by r.name, r.context_id");
                            if (dtResources != null)
                            {
                                foreach (DataRow drR in dtResources.Rows)
                                {
                                    String resourceName = drR["name"].ToString();
                                    Node   resNode      = flowData.AddNode(resourceName, 6, (Int32)drR["qty"], true);
                                    flowData.AddConnection(identNode, resNode, drR["qty"] + " identidades");
                                }
                            }
                        }
                    }


                    Node confNode = flowData.AddNode("Configuração", 3, 1, true);
                    flowData.AddConnection(cNode, confNode, "");

                    DataTable dtProxy = db.Select("select p.id, p.name from resource r inner join proxy p on r.proxy_id = p.id where r.context_id = " + contextID + " group by p.id, p.name order by p.name");
                    if ((dtProxy == null) || (dtProxy.Rows.Count == 0))
                    {
                        Node pNode = flowData.AddNode("Nenhuma configuração vinculada a este contexto", 4, 1, true);
                        flowData.AddConnection(confNode, pNode, "");
                    }
                    else
                    {
                        //Node proxyNode = flowData.AddNode("Proxy", 2, dtProxy.Rows.Count, false);
                        //flowData.AddConnection(cNode, proxyNode, "");

                        foreach (DataRow drP in dtProxy.Rows)
                        {
                            Int64 pId   = (Int64)drP["id"];
                            Node  pNode = flowData.AddNode("Proxy: " + drP["name"], 4, 1, true);
                            flowData.AddConnection(confNode, pNode, "");

                            DataTable dtResource = db.Select("select r.*, p.name proxy_name from resource r inner join proxy p on r.proxy_id = p.id where r.context_id = " + contextID + " and p.id = " + pId);
                            if (dtResource != null)
                            {
                                foreach (DataRow drR in dtResource.Rows)
                                {
                                    Int64 rId   = (Int64)drR["id"];
                                    Node  rNode = flowData.AddNode("Recurso: " + drR["name"], 5, 1, true);
                                    flowData.AddConnection(pNode, rNode, "");

                                    DataTable dtResPlugin = db.Select("select p.name plugin_name, rp.* from resource_plugin rp inner join plugin p on rp.plugin_id = p.id where rp.resource_id = " + rId);
                                    if (dtResPlugin != null)
                                    {
                                        foreach (DataRow drRP in dtResPlugin.Rows)
                                        {
                                            Int64 rpId   = (Int64)drRP["id"];
                                            Node  rpNode = flowData.AddNode("Plugin: " + drRP["plugin_name"].ToString(), 6, 1, true);
                                            flowData.AddConnection(rNode, rpNode, "");

                                            DataTable dtRoles = db.Select("select r.id, r.name from role r inner join resource_plugin_role rpr on rpr.role_id = r.id where rpr.resource_plugin_id = " + rpId + "  group by r.id, r.name");
                                            if (dtRoles != null)
                                            {
                                                foreach (DataRow drRol in dtRoles.Rows)
                                                {
                                                    String roleName = "Perfil: " + drRol["name"];

                                                    //if (roleNode != null)
                                                    //{

                                                    //Node roleNameNode = flowData.Find(roleNode, roleName, 6);
                                                    Node roleNameNode = flowData.Find(rpNode, roleName, 6);
                                                    if (roleNameNode == null)
                                                    {
                                                        roleNameNode = flowData.AddNode("Perfil: " + drRol["name"].ToString(), 7, 1, true);
                                                    }

                                                    if (roleNameNode != null)
                                                    {
                                                        flowData.AddConnection(rpNode, roleNameNode, "");
                                                    }

                                                    //Int32 roleNameNodeIndex = flowData.AddNode("Perfil: " + drRol["name"].ToString(), true);

                                                    //flowData.AddLink(rpNodeIndex, roleNameNodeIndex, 1, "");
                                                    //}
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(flowData.ToJson());
        }
Exemplo n.º 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            html += "<form id=\"serviceLogin\" name=\"serviceLogin\" method=\"post\" action=\"" + Session["ApplicationVirtualPath"] + "login2/recover/step2/\"><div class=\"login_form\">";

            LoginData login = LoginUser.LogedUser(this);

            if (login != null)
            {
                if (Session["last_page"] != null)
                {
                    Response.Redirect(Session["last_page"].ToString());
                    Session["last_page"] = null;
                }
                else
                {
                    Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "autoservice/", false);
                }
            }
            else if (Session["user_info"] == null || !(Session["user_info"] is Int64))
            {
                //Serviço não informado ou não encontrado
                html += "    <ul>";
                html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("invalid_session") + "</div>";
                html += "    </ul>";
            }
            else
            {
                Int64 entityId = (Int64)Session["user_info"];

                String err = "";

                if (Request.HttpMethod == "POST")
                {
                    String userCode = Request["userCode"];
                    if ((userCode == null) || (userCode == ""))
                    {
                        error = MessageResource.GetMessage("type_code");
                    }
                    else
                    {
                        if (entityId > 0)
                        {
                            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            {
                                DataTable c = db.Select("select * from entity where deleted = 0 and id = " + entityId + " and recovery_code = '" + Tools.Tool.TrataInjection(userCode) + "'");
                                if ((c != null) && (c.Rows.Count > 0))
                                {
                                    Session["userCode"] = c.Rows[0]["recovery_code"].ToString();

                                    Response.Redirect(Session["ApplicationVirtualPath"] + "login2/recover/step3/", false);
                                    return;
                                }
                                else
                                {
                                    error = MessageResource.GetMessage("invalid_code");
                                }
                            }
                        }
                        else
                        {
                            error = MessageResource.GetMessage("invalid_session");
                        }
                    }
                }

                html += "<ul>";
                html += "    <li>";
                html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">" + MessageResource.GetMessage("enter_code") + "</p>";
                html += "    </li>";
                html += "    <li>";
                html += "        <span class=\"inputWrap\">";
                html += "			<input type=\"text\" id=\"userCode\" tabindex=\"1\" name=\"userCode\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("code") + "\" onfocus=\"$('#userCode').addClass('focus');\" onblur=\"$('#userCode').removeClass('focus');\" />";
                html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#userCode').focus();\"></span>";
                html += "        </span>";
                html += "    </li>";


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


                html += "    <li>";
                html += "        <span class=\"forgot\"> <a href=\"/\">" + MessageResource.GetMessage("cancel") + "</a> " + MessageResource.GetMessage("or") + " </span>";
                html += "        <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("confirm_code") + "</button>";
                html += "    </li>";
                html += "</ul>     ";
            }

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

            holderContent.Controls.Add(new LiteralControl(html));
        }
Exemplo n.º 8
0
        private void DeployNowTimer(Object state)
        {
            if (executing2)
            {
                return;
            }

            executing2 = true;


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

                DataTable dtS = db.Select("select entity_id, MAX(date) [date] from deploy_now with(nolock) where date < GETDATE() group by entity_id order by MAX(date)");

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

                TextLog.Log("Dispatcher", "Starting deploy now timer");

                //Processa um a um dos agendamentos
                foreach (DataRow dr in dtS.Rows)
                {
                    try
                    {
                        Int32 count = 0;
                        using (IAMDeploy deploy = new IAMDeploy("Dispatcher", localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword))
                        {
                            count = deploy.DeployOne((Int64)dr["entity_id"]);


                            if (count == 0)
                            {
                                db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Error, 0, 0, 0, 0, 0, (Int64)dr["entity_id"], 0, "Erro on deploy now user: no package sent", deploy.ExecutionLog);
                            }
                        }


                        db.ExecuteNonQuery("delete from deploy_now where entity_id = " + dr["entity_id"], CommandType.Text, null);
                    }
                    catch (Exception ex2) {
                        db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Error, 0, 0, 0, 0, 0, (Int64)dr["entity_id"], 0, "Erro on deploy now user: "******"Dispatcher", "\tError on deploy now timer " + ex.Message + ex.StackTrace);
            }
            finally
            {
                TextLog.Log("Dispatcher", "Finishing deploy now timer");
                executing2 = false;
            }
        }
Exemplo n.º 9
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.º 10
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.º 11
0
        private void TmrCallback(Object o)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            TextLog.Log("Engine", "Importer", "Starting registry processor timer");
            Console.WriteLine("Starting registry processor timer");
            IAMDatabase db        = null;
            Stopwatch   stopWatch = new Stopwatch();

            stopWatch.Start();


            Dictionary <Int64, PluginConfig> resourcePluginCache = new Dictionary <Int64, PluginConfig>();

            StringBuilder procLog  = new StringBuilder();
            Boolean       writeLog = false;

            last_status = "Iniciando...";
            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 600;
                //db.Debug = true;

                Console.WriteLine("Select data...");

                Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.Indeterminate);
                startTime = DateTime.Now;
                newUsers  = 0;
                errors    = 0;
                totalReg  = 0;
                ignored   = 0;
                atualReg  = 0;

                //Seleciona os registros prontos para serem importados
                //Não colocar order neste select, fica extremamente lento
                //Coloca um limite de 500.000 somente p/ não estourar memória
                last_status = "Selecionando registros a serem processados";
                DataTable dtRegs = db.Select("select top 5000 * from vw_collector_imports_regs with(nolock) order by priority desc");

                if (dtRegs == null)
                {
                    TextLog.Log("Engine", "Importer", "\tError on select registries: " + db.LastDBError);
                    db.AddUserLog(LogKey.Engine, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on select registries: " + db.LastDBError);
                    executing = false;
                    return;
                }

                if (dtRegs.Rows.Count == 0)
                {
                    TextLog.Log("Engine", "Importer", "\t0 registers to process");
                    Console.WriteLine("0 registers to process");
                    executing = false;
                    return;
                }

                totalReg = dtRegs.Rows.Count;

                TextLog.Log("Engine", "Importer", "\t" + dtRegs.Rows.Count + " registers to process");
                procLog.AppendLine("[" + DateTime.Now.ToString("o") + "] " + dtRegs.Rows.Count + " registers to process");
                Console.WriteLine(dtRegs.Rows.Count + " registers to process");

                //Carrega todos os logins do sistema
                Console.WriteLine("Fetch logins...");
                last_status = "Listando login do sistema";
                DataTable dtLogins = db.Select("select context_id,id,login from vw_entity_logins2 with(nolock)");
                if ((dtLogins != null) || (dtLogins.Rows.Count > 0))
                {
                    foreach (DataRow dr in dtLogins.Rows)
                    {
                        LoginCache.AddItem((Int64)dr["context_id"], (Int64)dr["id"], dr["login"].ToString());
                    }
                }

                //Carrega todos os e-mails do sistema
                Console.WriteLine("Fetch e-mails...");
                last_status = "Listando e-mails do sistema";
                DataTable dtEmails = db.Select("select context_id, entity_id, mail from vw_entity_mails with(nolock)");
                if ((dtEmails != null) || (dtEmails.Rows.Count > 0))
                {
                    foreach (DataRow dr in dtEmails.Rows)
                    {
                        EmailCache.AddItem((Int64)dr["context_id"], (Int64)dr["entity_id"], dr["mail"].ToString());
                    }
                }


                //Calcula a quantidade de threads com base na quantidade de registros
                Int32 tCount = dtRegs.Rows.Count / 10;

                if (tCount < 1)
                {
                    tCount = 1;
                }
                else if (tCount > this.maxThreads)
                {
                    tCount = this.maxThreads;
                }

#if DEBUG
                tCount = 1;
#endif

                DebugMessage dbgC = new DebugMessage(delegate(String message)
                {
                    procLog.AppendLine(message);
                });



                Console.WriteLine("Starting...");
                queueManager = new QueueManager <RegistryProcessStarter>(tCount, ProcQueue);
                queueManager.OnThreadStart += new QueueManager <RegistryProcessStarter> .StartThread(delegate(Int32 threadIndex)
                {
                    LocalTheadObjects obj = new LocalTheadObjects();
                    for (Int32 t = 0; t <= 10; t++)
                    {
                        try
                        {
                            obj.db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                            obj.db.openDB();
                            obj.db.Timeout = 600;

#if DEBUG
                            //obj.db.Debug = true;
#endif

                            obj.lockRules   = new LockRules();
                            obj.ignoreRules = new IgnoreRules();
                            obj.roleRules   = new RoleRules();
                            obj.lockRules.GetDBConfig(obj.db.Connection);
                            obj.ignoreRules.GetDBConfig(obj.db.Connection);
                            obj.roleRules.GetDBConfig(obj.db.Connection);
                            obj.debugCallback = dbgC;
                            break;
                        }
                        catch (Exception ex) {
                            if (t >= 10)
                            {
                                throw ex;
                            }
                        }
                    }

                    return(obj);
                });

                queueManager.OnThreadStop += new QueueManager <RegistryProcessStarter> .ThreadStop(delegate(Int32 threadIndex, Object state)
                {
                    if ((state != null) && (state is LocalTheadObjects))
                    {
                        ((LocalTheadObjects)state).Dispose();
                    }

                    state = null;
                });


                Console.WriteLine("Starting treads...");
                last_status = "Iniciando treads";
                queueManager.Start();

                if (queueManager.ExecutingCount == 0)
                {
                    throw new Exception("Erro on start queue manager");
                }

                /*
                 * _queue = new RegistryQueue[tCount];
                 * Int32 qIndex = 0;
                 *
                 * for (Int32 i = 0; i < _queue.Length; i++)
                 *  _queue[i] = new RegistryQueue();
                 */

                Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.Normal);
                Taskbar.TaskbarProgress.SetProgressValue(0, (Int32)totalReg, System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle);

                Int32 addCount = 0;
                last_status = "Processando registros";
                foreach (DataRow dr in dtRegs.Rows)
                {
                    Int64 enterpriseId = (Int64)dr["enterprise_id"];
                    Int64 contextId    = (Int64)dr["context_id"];

                    LicenseControl lic = null;
                    if (!licControl.ContainsKey(enterpriseId))
                    {
                        lic = LicenseChecker.GetLicenseData(db.Connection, null, enterpriseId);
                        licControl.Add(enterpriseId, lic);
                    }
                    else
                    {
                        lic = licControl[enterpriseId];
                    }

                    if (!lic.Valid)
                    {
                        if (!lic.Notified)
                        {
                            db.AddUserLog(LogKey.Licence_error, null, "Engine", UserLogLevel.Error, 0, enterpriseId, 0, (Int64)dr["resource_id"], (Int64)dr["plugin_id"], 0, 0, "License error: " + lic.Error);
                        }
                        lic.Notified = true;

                        db.ExecuteNonQuery("update collector_imports set status = 'LE' where status = 'F' and resource_plugin_id = '" + dr["resource_id"] + "' and  import_id = '" + dr["import_id"] + "' and package_id = '" + dr["package_id"] + "'", CommandType.Text, null);

                        continue;
                    }

                    if ((lic.Entities > 0) && (lic.Count > lic.Entities))
                    {
                        if (!lic.Notified)
                        {
                            db.AddUserLog(LogKey.Licence_error, null, "Engine", UserLogLevel.Error, 0, enterpriseId, 0, (Int64)dr["resource_id"], (Int64)dr["plugin_id"], 0, 0, "License error: License limit (" + lic.Entities + " entities) exceeded");
                        }
                        lic.Notified = true;

                        db.ExecuteNonQuery("update collector_imports set status = 'LE' where status = 'F' and resource_plugin_id = '" + dr["resource_id"] + "' and  import_id = '" + dr["import_id"] + "' and package_id = '" + dr["package_id"] + "'", CommandType.Text, null);

                        continue;
                    }


                    if (!entKeys.ContainsKey(enterpriseId))
                    {
                        entKeys.Add(enterpriseId, new EnterpriseKeyConfig(db.Connection, enterpriseId));
                    }

                    if (entKeys[enterpriseId] == null)
                    {
                        entKeys[enterpriseId] = new EnterpriseKeyConfig(db.Connection, enterpriseId);
                    }

                    addCount++;
                    queueManager.AddItem(new RegistryProcessStarter(enterpriseId, contextId, new Uri(dr["plugin_uri"].ToString()), Int64.Parse(dr["resource_id"].ToString()), Int64.Parse(dr["plugin_id"].ToString()), Int64.Parse(dr["resource_plugin_id"].ToString()), (String)dr["import_id"], (String)dr["package_id"], (String)dr["package"]));

                    //A cada 100 registros monitora a CPU para adicionar mais registros
                    //O Objetivo deste processo é controlar a carga de processamento
                    if (addCount >= 100)
                    {
                        addCount = 0;
                        Int32 c = 0;
                        while (((c = queueManager.QueueCount) > 500) || ((getCPUCounter() >= 70) && (c > 0)))
                        {
                            Thread.Sleep(500);
                        }
                    }


                    /*
                     * _queue[qIndex].Add(enterpriseId, contextId, Int64.Parse(dr["plugin_id"].ToString()), (String)dr["plugin_uri"], Int64.Parse(dr["resource_id"].ToString()), (String)dr["import_id"], (String)dr["registry_id"]);
                     *
                     * qIndex++;
                     * if (qIndex > _queue.Length - 1) qIndex = 0;
                     */
                }



                /*
                 * for (Int32 i = 0; i < _queue.Length; i++)
                 * {
                 *  Thread procQueue = new Thread(new ParameterizedThreadStart(ProcQueue));
                 *  procQueue.Start(i);
                 *  //Thread.Sleep(1000);
                 * }*/

                Console.WriteLine("Waiting treads execution...");

                /*
                 * Int64 rest = 0;
                 * Double percent = 0;
                 * Int32 iPercent = 0;
                 * do
                 * {
                 *  rest = 0;
                 *
                 *  rest = queueManager.QueueCount;
                 *
                 *  //for (Int32 i = 0; i < _queue.Length; i++)
                 *  //    rest += _queue[i].Count;
                 *
                 *  percent = ((Double)(totalReg - rest) / (Double)totalReg) * 100F;
                 *
                 *  if (iPercent != (Int32)percent)
                 *  {
                 *      iPercent = (Int32)percent;
                 *      procLog.AppendLine("[" + DateTime.Now.ToString("o") + "] " + iPercent + "%");
                 *      TextLog.Log("Engine", "Importer", "\t" + iPercent + "%");
                 *      Console.Write(" " + iPercent + "% ");
                 *
                 *      Taskbar.TaskbarProgress.SetProgressValue((Int32)(totalReg - rest), (Int32)totalReg, System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle);
                 *
                 *  }
                 *
                 *  Thread.Sleep(1000);
                 *
                 * } while (rest > 0);*/


                //Envia comando para finalizar a execução e aguarda a finalização
                last_status = "Processando registros";
                queueManager.StopAndWait();


                Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.Indeterminate);

                last_status = "Finalizando";
                Console.WriteLine("Finishing...");

                if (dtRegs.Rows.Count > 0)
                {
                    writeLog = true;
                }

                procLog.AppendLine("New users: " + newUsers);
                procLog.AppendLine("Errors: " + errors);
                procLog.AppendLine("Ignored: " + ignored);
                procLog.AppendLine("Updated: " + (totalReg - errors - ignored - newUsers));

                procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Import registry processed with " + dtRegs.Rows.Count + " registers");

                //Joga todos os registros para a tabela de importados
                //e exclui da atual
                db.ExecuteNonQuery("sp_migrate_imported", CommandType.StoredProcedure, null);


                //Reconstroi os índices das tabelas de entidades e identidades
                try
                {
                    db.ExecuteNonQuery("sp_reindex_entity", CommandType.StoredProcedure, null);
                    db.ExecuteNonQuery("sp_rebuild_entity_keys", CommandType.StoredProcedure, null);
                }
                catch { }

                Console.WriteLine("");
            }
            catch (SqlException e)
            {
                procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] DB Error on registry processor: " + e.Message);
                procLog.AppendLine(db.LastDBError);

                db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "DB Error on registry processor", procLog.ToString());
                TextLog.Log("Engine", "Importer", "\tError on registry processor timer " + e.Message + " " + db.LastDBError);
            }
            catch (OutOfMemoryException ex)
            {
                procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Error on registry processor: " + ex.Message);

                db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Out Of Memory processing registry, killing processor", procLog.ToString());
                TextLog.Log("Engine", "Importer", "\tError on registry processor timer " + ex.Message);

                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            catch (Exception ex)
            {
                procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Error on registry processor: " + ex.Message);

                db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on registry processor", procLog.ToString());
                TextLog.Log("Engine", "Importer", "\tError on registry processor timer " + ex.Message);
            }
            finally
            {
                stopWatch.Stop();
                TimeSpan ts = stopWatch.Elapsed;

                executing   = false;
                last_status = "";

                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:0000}", ts.TotalHours, ts.Minutes, ts.Seconds, ts.Milliseconds);
                TextLog.Log("Engine", "Importer", "\tElapsed time: " + elapsedTime);

                TextLog.Log("Engine", "Importer", "\tScheduled for new registry processor in 60 seconds");
                TextLog.Log("Engine", "Importer", "Finishing registry processor timer");

                procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Elapsed time: " + elapsedTime);

                Console.WriteLine("Import registry processed " + procLog.ToString());
                Console.WriteLine("Elapsed time: " + elapsedTime);

                if (writeLog)
                {
                    db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Import registry processed", procLog.ToString());
                }

                Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.NoProgress);

                startTime = new DateTime(1970, 1, 1);

                try
                {
                    List <Int64> keys = new List <Int64>();
                    if ((entKeys != null) && (entKeys.Count > 0))
                    {
                        keys.AddRange(entKeys.Keys);
                        foreach (Int64 k in keys)
                        {
                            try
                            {
                                if (entKeys[k] != null)
                                {
                                    entKeys[k].Dispose();
                                    entKeys[k] = null;
                                }
                            }
                            catch { }
                            try
                            {
                                entKeys.Remove(k);
                            }
                            catch { }
                        }
                    }
                }
                catch { }

                try
                {
                    licControl.Clear();
                }
                catch { }

                try
                {
                    LoginCache.Clear();
                }
                catch { }

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

                db = null;

                Thread.CurrentThread.Abort();
            }
        }
Exemplo n.º 12
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.º 13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;

            LoginData login = LoginUser.LogedUser(this);

            String err = "";

            if (!EnterpriseIdentify.Identify(this, false, out err)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                ret = new WebJsonResponse("", err, 3000, true);
            }
            else if (login == null)
            {
                ret = new WebJsonResponse("", MessageResource.GetMessage("expired_session"), 3000, true, "/login/");
            }
            else
            {
                try
                {
                    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 currentPassword = Tools.Tool.TrataInjection(Request["current_password"]);
                    String password        = Tools.Tool.TrataInjection(Request["password"]);
                    String password2       = Request["password2"];
                    if ((currentPassword == null) || (currentPassword == ""))
                    {
                        ret = new WebJsonResponse("", MessageResource.GetMessage("type_password_current"), 3000, true);
                    }
                    else 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
                    {
                        using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        {
                            try
                            {
                                UserPasswordStrength       usrCheck = new UserPasswordStrength(db.Connection, login.Id);
                                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 = " + 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())))
                                                if (Encoding.UTF8.GetString(cApi.clearData) != currentPassword)
                                                {
                                                    ret = new WebJsonResponse("", MessageResource.GetMessage("current_password_invalid"), 3000, true);
                                                }
                                                else
                                                {
                                                    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 autoservice 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);

                                                    /*
                                                     * IAMDeploy deploy = null;
                                                     *
                                                     * using (ServerDBConfig conf = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                                                     *  deploy = new IAMDeploy("WebServer", DB.GetConnectionString(), conf.GetItem("outboundFiles"));
                                                     *
                                                     * if (deploy != null)
                                                     *  deploy.DeployOne(login.Id);*/



                                                    String html = "";
                                                    html += "<div class=\"no-tabs pb10\">";
                                                    html += "   <div class=\"form-group\">";
                                                    html += "       <h1>" + MessageResource.GetMessage("password_changed_sucessfully") + "</h1> ";
                                                    html += "   </div>";
                                                    html += "   <div class=\"form-group\"><span class=\"text-message\">" + MessageResource.GetMessage("password_changed_text") + "</span></div>";
                                                    html += "</div>";

                                                    ret = new WebJsonResponse("#pwdForm", html);
                                                }
                                    }
                                    else
                                    {
                                        ret = new WebJsonResponse("", "Internal error", 3000, true);
                                    }
                                }
                            }
                            finally
                            {
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Tools.Tool.notifyException(ex);
                    throw ex;
                }
            }

            if (ret != null)
            {
                ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Exemplo n.º 14
0
    static public Boolean Identify(Page Page, Boolean JsonReturn, Boolean supressReturn, out String errorText)
    {
        try
        {
            Boolean busca = false;

            if ((Page.Session["enterprise_data"] == null) || !(Page.Session["enterprise_data"] is EnterpriseData))
            {
                busca = true;
            }

            if ((!busca) && ((EnterpriseData)Page.Session["enterprise_data"]).Host.ToLower() != Page.Request.Url.Host.ToLower())
            {
                busca = true;
            }

            if (busca)
            {
                Page.Session["enterprise_data"] = null;

                EnterpriseData data = new EnterpriseData();
                data.Host = Page.Request.Url.Host.ToLower();

                if ((Page.Request.Url.Port != 80) && (Page.Request.Url.Port != 443))
                {
                    data.Host += ":" + Page.Request.Url.Port;
                }

                try
                {
                    DataTable dt = null;

                    using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        dt = db.Select("select id, e.fqdn, name, ef.fqdn alias, language, auth_plugin from [enterprise] e left join enterprise_fqdn_alias ef on ef.enterprise_id = e.id where e.fqdn = '" + data.Host + "' or ef.fqdn = '" + data.Host + "'");

                    if ((dt != null) && (dt.Rows.Count > 0))
                    {
                        data.Host       = dt.Rows[0]["fqdn"].ToString().ToLower();
                        data.Name       = dt.Rows[0]["name"].ToString();
                        data.Language   = dt.Rows[0]["language"].ToString();
                        data.Id         = (Int64)dt.Rows[0]["id"];
                        data.AuthPlugin = dt.Rows[0]["auth_plugin"].ToString();

                        Page.Session["enterprise_data"] = data;

                        errorText = "";

                        return(true);
                    }
                    else
                    {
                        errorText = "Nenhuma empresa encontrada com o host '" + data.Host + "'";
                        throw new Exception("Nenhuma empresa encontrada com o host '" + data.Host + "'");
                    }
                }
                catch (Exception ex)
                {
                    errorText = "Falha ao identificar a empresa: " + ex.Message;
                    throw new Exception("Falha ao identificar a empresa", ex);
                }
            }
            else
            {
                errorText = "";
            }

            if ((Page.Session["enterprise_data"] != null) && (Page.Session["enterprise_data"] is EnterpriseData))
            {
                Thread.CurrentThread.CurrentCulture = new CultureInfo(((EnterpriseData)Page.Session["enterprise_data"]).Language);
            }
            else
            {
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            }

            return(true);
        }
        catch (Exception ex)
        {
            Tools.Tool.notifyException(ex, Page);

            errorText = "Falha na identificação da empresa e/ou empresa não cadastrada";

            if (!supressReturn)
            {
                Byte[] erro = new Byte[0];


                if (JsonReturn)
                {
                    erro = Encoding.UTF8.GetBytes(JSON.GetResponse(false, "Falha na identificação da empresa e/ou empresa não cadastrada", ""));
                }
                else
                {
                    erro = Encoding.UTF8.GetBytes("Falha na identificação da empresa e/ou empresa não cadastrada");
                    Page.Response.Status     = "500 Internal error";
                    Page.Response.StatusCode = 500;
                }

                Page.Response.ContentType     = "text/json;charset=UTF-8";
                Page.Response.ContentEncoding = Encoding.UTF8;
                Page.Response.OutputStream.Write(erro, 0, erro.Length);
                Page.Response.End();
            }

            return(false);
        }
    }
Exemplo n.º 15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!EnterpriseIdentify.Identify(this)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                return;
            }

            LoginData login = LoginUser.LogedUser(this);

            if (login != null)
            {
                Response.Redirect("/autoservice/");
            }

            if ((Session["entity_id"] == null) || !(Session["entity_id"] is Int64))
            {
                Response.Redirect("/login/");
            }

            String html = "";

            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
            {
                DataTable c = db.Select("select * from entity where deleted = 0 and id = " + Session["entity_id"]);
                if ((c != null) && (c.Rows.Count > 0))
                {
                    html  = "";
                    html += "<div class=\"login_form\">";
                    html += "<ul>";
                    html += "    <li>";
                    html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">" + MessageResource.GetMessage("password_expired_text") + "</p>";
                    html += "    </li>";
                    html += "    <li>";
                    html += "        <span class=\"inputWrap\">";
                    //html += "			<span id=\"ph_current_password\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">" + MessageResource.GetMessage("current_password") + "</span>";
                    html += "			<input type=\"password\" id=\"current_password\" tabindex=\"1\" name=\"current_password\" value=\"\" style=\"\"  placeholder=\""+ MessageResource.GetMessage("current_password") + "\" onfocus=\"$('#current_password').addClass('focus');\" onblur=\"$('#current_password').removeClass('focus');\" />";
                    html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
                    html += "        </span>";
                    html += "    </li>";
                    html += "    <li>";
                    html += "        <span class=\"inputWrap\">";
                    //html += "			<span id=\"ph_password\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">" + MessageResource.GetMessage("new_password") + "</span>";
                    html += "			<input type=\"password\" id=\"password\" tabindex=\"1\" name=\"password\" value=\"\" style=\"\"  placeholder=\""+ MessageResource.GetMessage("new_password") + "\" onkeyup=\"iamadmin.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 += "			<span id=\"ph_password2\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">" + MessageResource.GetMessage("new_password_confirm") + "</span>";
                    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>";
                    html += "    <li>";
                    html += "        <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("change_password") + "</button>";
                    html += "    </li>";
                    html += "</ul>     ";
                    html += "</div>";
                }
                else
                {
                    Tools.Tool.notifyException(new Exception("User not found in change password"), this);

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

            holderContent.Controls.Add(new LiteralControl(html));
        }
Exemplo n.º 16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse contentRet = null;


            String action = "";

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

            Int64 pluginId = 0;

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

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

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

            Int64 enterpriseId = 0;

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

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

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

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

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

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

                        String desc = "";

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

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

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

                    break;

                case "upload":

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


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


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

                            DirectoryInfo pluginsDir = null;

                            try
                            {
                                using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                                    pluginsDir = new DirectoryInfo(Path.Combine(c.GetItem("pluginFolder"), "temp\\" + ((EnterpriseData)Page.Session["enterprise_data"]).Id));

                                if (!pluginsDir.Exists)
                                {
                                    pluginsDir.Create();
                                }
                            }
                            catch {
                                pluginsDir = null;
                            }

                            if (pluginsDir == null)
                            {
                                d += String.Format(infoTemplate2, "", "Status", "Diretório de plugins não encontrado");
                            }
                            else
                            {
                                try
                                {
                                    if (!pluginsDir.Exists)
                                    {
                                        pluginsDir.Create();
                                    }

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

                                    List <String> p2    = new List <String>();
                                    List <String> p2Uri = new List <String>();
                                    try
                                    {
                                        //Realiza teste de compatibilidade com os plugins
                                        List <PluginBase> p1 = Plugins.GetPlugins <PluginBase>(rawAssembly);
                                        if (p1.Count > 0)
                                        {
                                            d += String.Format(infoTemplate2, "", "Status", "Arquivo válido");
                                        }
                                        else
                                        {
                                            d += String.Format(infoTemplate2, "", "Status", "Arquivo de plugin inválido");
                                        }

                                        foreach (PluginBase p in p1)
                                        {
                                            p2.Add(p.GetPluginName());
                                            p2Uri.Add(p.GetPluginId().AbsoluteUri);
                                        }
                                    }
                                    catch
                                    {
                                        d += String.Format(infoTemplate2, "", "Status", "Arquivo de plugin inválido");
                                    }

                                    d += String.Format(infoTemplate2, "", "Nome", mpF.FileName);
                                    d += String.Format(infoTemplate2, "", "Tamanho", mpF.Data.Length + " bytes");
                                    if (p2.Count > 0)
                                    {
                                        d += String.Format(infoTemplate2, "", "Plugins", String.Join(", ", p2));
                                    }
                                    else
                                    {
                                        d += String.Format(infoTemplate2, "", "Plugins", "Nenhum plugin encontrado no arquivo enviado");
                                    }

                                    if (p2.Count > 0)
                                    {
                                        using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                        {
                                            DataTable dt = database.Select("select * from plugin where enterprise_id in (0," + enterpriseId + ") and (assembly in ('" + String.Join("','", p2) + "') or uri in ('" + String.Join("','", p2Uri) + "'))");

                                            if (dt.Rows.Count > 0)
                                            {
                                                throw new Exception("Plugin/uri ja cadastrado no sistema");
                                            }
                                        }

                                        FileInfo newFile = new FileInfo(Path.Combine(pluginsDir.FullName, mpF.FileName));
                                        if (newFile.Exists)
                                        {
                                            newFile.Delete();
                                        }
                                        File.WriteAllBytes(newFile.FullName, rawAssembly);
                                    }
                                }
                                catch (Exception ex) {
                                    d  = String.Format(infoTemplate2, "", "Status", "Erro ao realizar o upload");
                                    d += String.Format(infoTemplate2, "", "Informação do erro", ex.Message);
                                }
                            }

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

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

                    break;

                case "add_new":
                    Dictionary <String, String> files = new Dictionary <string, string>();
                    foreach (String key in Request.Form.Keys)
                    {
                        if ((key != null) && (key.ToLower().IndexOf("file_name") == 0))
                        {
                            if (!files.ContainsKey(Request.Form[key].ToLower()))
                            {
                                files.Add(Request.Form[key].ToLower(), Request.Form[Request.Form[key]]);
                            }
                        }
                    }

                    if (files.Count == 0)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true);
                        break;
                    }

                    DirectoryInfo pluginsBase = null;
                    DirectoryInfo pluginsTemp = null;
                    try
                    {
                        using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                            pluginsBase = new DirectoryInfo(c.GetItem("pluginFolder"));

                        pluginsTemp = new DirectoryInfo(Path.Combine(pluginsBase.FullName, "temp\\" + ((EnterpriseData)Page.Session["enterprise_data"]).Id));

                        if (!pluginsTemp.Exists)
                        {
                            pluginsTemp.Create();
                        }
                    }
                    catch
                    {
                        pluginsTemp = null;
                    }

                    if (pluginsTemp == null)
                    {
                        contentRet = new WebJsonResponse("", "Diretório de plugins não encontrado", 3000, true);
                        break;
                    }

                    List <WebJsonResponse> multRet = new List <WebJsonResponse>();

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

                    Boolean hasError = false;
                    foreach (String f in files.Keys)
                    {
                        try
                        {
                            FileInfo assemblyFile = new FileInfo(Path.Combine(pluginsTemp.FullName, f));

                            if (!assemblyFile.Exists)
                            {
                                throw new Exception("Arquivo temporário não encontrado, refaça o upload");
                            }

                            Byte[]            rawAssembly = File.ReadAllBytes(assemblyFile.FullName);
                            List <PluginBase> p1          = Plugins.GetPlugins <PluginBase>(rawAssembly);
                            if (p1.Count == 0)
                            {
                                throw new Exception("Arquivo de plugin inválido");
                            }

                            foreach (PluginBase p in p1)
                            {
                                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                {
                                    DataTable dt = database.Select("select * from plugin where enterprise_id in (0," + enterpriseId + ") and (assembly = '" + p.GetPluginName() + "' or uri = '" + p.GetPluginId().AbsoluteUri + "')", null);

                                    if (dt.Rows.Count > 0)
                                    {
                                        throw new Exception("Plugin/uri ja cadastrado no sistema");
                                    }
                                }

                                FileInfo newF = new FileInfo(Path.Combine(pluginsBase.FullName, enterpriseId + "-" + assemblyFile.Name));
                                try
                                {
                                    assemblyFile.CopyTo(newF.FullName);

                                    DbParameterCollection par = new DbParameterCollection();
                                    par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId;
                                    par.Add("@name", typeof(String)).Value         = p.GetPluginName();
                                    par.Add("@scheme", typeof(String)).Value       = p.GetPluginId().Scheme;
                                    par.Add("@uri", typeof(String)).Value          = p.GetPluginId().AbsoluteUri;
                                    par.Add("@assembly", typeof(String)).Value     = newF.Name;

                                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                                        database.ExecuteNonQuery("INSERT INTO plugin ([enterprise_id],[name],[scheme],[uri],[assembly],[create_date]) VALUES(@enterprise_id, @name, @scheme, @uri, @assembly, getdate())", CommandType.Text, par);

                                    try
                                    {
                                        assemblyFile.Delete();
                                    }
                                    catch { }
                                }
                                catch (Exception ex) {
                                    try
                                    {
                                        newF.Delete();
                                    }
                                    catch { }



                                    throw ex;
                                }
                            }

                            multRet.Add(new WebJsonResponse(".file-item[id=file" + files[f] + "] .description", String.Format(infoTemplate3, "", "Status", "Plugin inserido com sucesso")));
                            multRet.Add(new WebJsonResponse(".file-item[id=file" + files[f] + "] .form-content", "<input type=\"hidden\" />"));
                        }
                        catch (Exception ex)
                        {
                            hasError = true;
                            multRet.Add(new WebJsonResponse(".file-item[id=file" + files[f] + "] .description", String.Format(infoTemplate3, "error", "Error", ex.Message)));
                        }
                    }

                    if (!hasError)
                    {
                        multRet.Clear();
                        multRet.Add(new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/plugin/"));
                    }

                    Retorno.Controls.Add(new LiteralControl(JSON.Serialize <List <WebJsonResponse> >(multRet)));
                    contentRet = null;

                    break;

                case "delete":

                    var reqDel = new
                    {
                        jsonrpc    = "1.0",
                        method     = "plugin.delete",
                        parameters = new
                        {
                            pluginid = pluginId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqDel);

                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData);

                    if (String.IsNullOrWhiteSpace(jData))
                    {
                        throw new Exception("");
                    }

                    RoleDeleteResult retDel = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retDel == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true);
                    }
                    else if (retDel.error != null)
                    {
                        contentRet = new WebJsonResponse("", retDel.error.data, 3000, true);
                    }
                    else if (!retDel.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
            }
            finally
            {
            }

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


                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Exemplo n.º 17
0
        private Int32 _Deploy(Int64 entityId, Int64 resourcePluginId)
        {
            //Busca todos os plugins e recursos a serem publicados
            DataTable dtPlugins = null;
            Dictionary <Int64, LicenseControl> licControl = null;
            DataTable dtEnt        = null;
            Int32     packageCount = 0;

            StringBuilder deployLog = new StringBuilder();

            try
            {
                dtPlugins = db.Select("select r.context_id, p.id, p.scheme, p.uri, p.assembly, p.create_date, rp.id resource_plugin_id, rp.deploy_individual_package, r.id resource_id, r.proxy_id, p1.name as proxy_name, p1.id proxy_id, p1.enterprise_id, rp.deploy_after_login, rp.password_after_login, rp.deploy_process, rp.deploy_all, rp.deploy_password_hash, rp.use_password_salt, rp.password_salt_end, rp.password_salt from plugin p with(nolock)  inner join resource_plugin rp with(nolock) on rp.plugin_id = p.id  inner join [resource] r on r.id = rp.resource_id inner join proxy p1 on r.proxy_id = p1.id  where " + (resourcePluginId > 0 ? " rp.id = " + resourcePluginId + " and " : "") + " r.enabled = 1 and rp.enabled = 1 and rp.enable_deploy = 1 order by rp.[order]");
                if ((dtPlugins == null) || (dtPlugins.Rows.Count == 0))
                {
                    if ((entityId > 0) || (resourcePluginId > 0))
                    {
                        throw new Exception("0 plugin to process");
                    }

                    //TextLog.Log(moduleSender, "\t0 plugin to process");
                    DebugLog(entityId, "0 plugin to process");
                    return(0);
                }

                DebugLog(entityId, dtPlugins.Rows.Count + " plugin to process");

                licControl = new Dictionary <long, LicenseControl>();

                String rolesText = "";

                //Lista todos os plugins e resources habilitados
                foreach (DataRow dr in dtPlugins.Rows)
                {
                    Boolean individualPackage = (Boolean)dr["deploy_individual_package"];

                    deployLog = new StringBuilder();

                    DebugLog(entityId, "proxy_name = " + dr["proxy_name"].ToString() + ", plugin = " + dr["uri"].ToString() + ", deploy_all? " + dr["deploy_all"].ToString());

                    ProxyConfig config = new ProxyConfig(true);
                    config.GetDBCertConfig(db.Connection, Int64.Parse(dr["enterprise_id"].ToString()), dr["proxy_name"].ToString());

                    DirectoryInfo proxyDir = new DirectoryInfo(Path.Combine(outDirBase.FullName, dr["proxy_id"].ToString() + "_" + dr["proxy_name"].ToString() + "\\" + Path.GetFileNameWithoutExtension(dr["assembly"].ToString()) + "\\rp" + dr["resource_plugin_id"].ToString()));

                    List <PluginConnectorBaseDeployPackage> packageList = new List <PluginConnectorBaseDeployPackage>();
                    List <Int64> roles = new List <Int64>();

                    Int64 enterpriseId = (Int64)dr["enterprise_id"];

                    LicenseControl lic = null;
                    if (!licControl.ContainsKey(enterpriseId))
                    {
                        lic = LicenseChecker.GetLicenseData(db.Connection, null, enterpriseId);
                        licControl.Add(enterpriseId, lic);
                    }
                    else
                    {
                        lic = licControl[enterpriseId];
                    }

                    if (!lic.Valid)
                    {
                        if (!lic.Notified)
                        {
                            db.AddUserLog(LogKey.Licence_error, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], (Int64)dr["enterprise_id"], 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "License error: " + lic.Error);
                        }
                        lic.Notified = true;
                        continue;
                    }


                    if (!(Boolean)dr["deploy_all"])
                    {
                        //Busca os "roles" top
                        String rolesSQL = "select rpr.* from resource_plugin_role rpr with(nolock) inner join resource_plugin rp on rpr.resource_plugin_id = rp.id where rp.resource_id =  " + dr["resource_id"].ToString() + " and rp.plugin_id = " + dr["id"];
                        DebugLog(entityId, "Role SQL = " + rolesSQL);

                        DataTable dtRoles = db.Select(rolesSQL);
                        if (dtRoles == null)
                        {
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                            continue;
                        }

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

                        //Busca toda a arvore de "roles" a se buscar
                        foreach (DataRow drR in dtRoles.Rows)
                        {
                            DataTable dtR = db.Select("select * from dbo.fn_selectRoleTree(" + drR["role_id"] + ")");
                            if (dtR == null)
                            {
                                continue;
                            }

                            foreach (DataRow drRT in dtR.Rows)
                            {
                                if (!roles.Contains((Int64)drRT["role_id"]))
                                {
                                    roleNames.Add(drRT["name"].ToString());
                                    roles.Add((Int64)drRT["role_id"]);
                                }
                            }
                        }

                        if (roles.Count == 0)
                        {
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Not found roles x identities to deploy");
                            continue;
                        }

                        //Para efeitos de log captura o nome dos roles
                        rolesText = String.Join(", ", roleNames);

                        dtRoles.Clear();
                        dtRoles = null;
                    }

                    //Seleciona todas as entidades do mesmo contexto
                    //Esta listagem considera somente as entidades pertencentes aos plugins de entrada
                    String sql = "select e.id, e.last_login, e.change_password, i.id identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join [resource_plugin] rp with(nolock) on i.resource_plugin_id = rp.id where i.deleted = 0 and e.deleted = 0 {0} and e.context_id = " + dr["context_id"] + (entityId > 0 ? " and e.id = " + entityId : "") + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by e.id, e.last_login, e.change_password, i.id";

                    if (!(Boolean)dr["deploy_all"])
                    {
                        sql = "select e.id, e.last_login, e.change_password, i.id identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join [resource_plugin] rp with(nolock) on i.resource_plugin_id = rp.id inner join identity_role ir with(nolock) on ir.identity_id = i.id  inner join (select rpr.role_id from	resource_plugin_role rpr with(nolock) inner join resource_plugin rp with(nolock) on rp.id = rpr.resource_plugin_id inner join resource r with(nolock) on r.id = rp.resource_id where r.id = "+ dr["resource_id"].ToString() + ") ro on ro.role_id =  ir.role_id where i.deleted = 0 and e.deleted = 0 {0} and ir.role_id in (" + String.Join(",", roles) + ")" + (entityId > 0 ? " and e.id = " + entityId : "") + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) and e.context_id = " + dr["context_id"] + " group by e.id, e.last_login, e.change_password, i.id";
                    }

                    DebugLog(entityId, String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));

                    //Lista todas as entidades e identidades para exportar
                    dtEnt = db.Select(String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));
                    if (dtEnt == null)
                    {
                        DebugLog(entityId, "SQL result is empty");
                        db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                        continue;
                    }

                    if (dtEnt.Rows.Count == 0)
                    {
                        DebugLog(entityId, "SQL result is empty, trying with all plugins");
                        DebugLog(entityId, String.Format(sql, ""));

                        //Lista todas as entidades e identidades para exportar
                        dtEnt = db.Select(String.Format(sql, ""));
                        if (dtEnt == null)
                        {
                            DebugLog(entityId, "SQL result is empty");
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                            continue;
                        }
                    }
                    sql = null;


                    if ((dtEnt.Rows.Count == 0) && ((Boolean)dr["deploy_all"]))
                    {
                        DebugLog(entityId, "SQL result is empty with all plugins, trying with only entity data");

                        sql = "select e.id, e.last_login, e.change_password, cast(0 as bigint) identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id cross join [resource_plugin] rp with(nolock) where e.deleted = 0 {0} and e.context_id = " + dr["context_id"] + (entityId > 0 ? " and e.id = " + entityId : "") + "  group by e.id, e.last_login, e.change_password";

                        DebugLog(entityId, String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));

                        //Lista todas as entidades e identidades para exportar
                        dtEnt = db.Select(String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1"));
                        if (dtEnt == null)
                        {
                            DebugLog(entityId, "SQL result is empty");
                            db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : ""));
                            continue;
                        }
                    }
                    sql = null;

                    DebugLog(entityId, "SQL result count " + dtEnt.Rows.Count);

                    if ((dtEnt.Rows.Count > 0) && (entityId == 0))
                    {
                        deployLog.AppendLine("Starting check to deploy " + dtEnt.Rows.Count + " identities for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users"));
                    }

                    Int32 total        = dtEnt.Rows.Count;
                    Int32 licError     = 0;
                    Int32 loguedIgnore = 0;
                    Int32 deploy       = 0;

                    //db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Deploy with " + dtEnt.Rows.Count + " identities for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users"));
                    foreach (DataRow drE in dtEnt.Rows)
                    {
                        //Checagens de licenciamento
                        lic.Count++;

                        if ((lic.Entities > 0) && (lic.Count > lic.Entities))
                        {
                            db.AddUserLog(LogKey.Licence_error, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "License error: License limit (" + lic.Entities + " entities) exceeded");
                            licError++;
                            continue;
                        }

                        try
                        {
                            if (((Boolean)dr["deploy_after_login"]) && (drE["last_login"] == DBNull.Value))
                            {
                                db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "User NOT addedd in deploy package because the user is not logged in yet");
                                loguedIgnore++;
                                continue;
                            }

                            //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "Identity addedd in deploy package");

                            PluginConnectorBaseDeployPackage newPkg = DeployPackage.GetPackage(db, (Int64)dr["proxy_id"], (Int64)dr["resource_plugin_id"], (Int64)drE["id"], (Int64)drE["identity_id"], (Boolean)dr["password_after_login"], (drE["change_password"] == DBNull.Value ? null : (DateTime?)drE["change_password"]), (dr["deploy_password_hash"] == DBNull.Value ? "none" : dr["deploy_password_hash"].ToString()), (Boolean)dr["use_password_salt"], (Boolean)dr["password_salt_end"], dr["password_salt"].ToString());
                            packageList.Add(newPkg);

                            deploy++;

#if DEBUG
                            try
                            {
                                db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Debug, 0, enterpriseId, 0, (Int64)dr["resource_id"], (Int64)dr["id"], newPkg.entityId, newPkg.identityId, "Package generated: " + newPkg.pkgId, SafeTrend.Json.JSON.Serialize <PluginConnectorBaseDeployPackage>(newPkg));
                            }
                            catch { }
#endif

                            packageCount++;
                        }
                        catch (Exception ex)
                        {
                            db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "Erro on deploy user: "******"Total identities: " + total);
                    deployLog.AppendLine("Ignored by licence check: " + licError);
                    deployLog.AppendLine("Ignored by first login rule: " + loguedIgnore);
                    deployLog.AppendLine("Published: " + deploy);

                    db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Deploy package generated for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users"), deployLog.ToString());
                }

                db.closeDB();
                db.Dispose();
            }
            catch (Exception ex)
            {
                DebugLog(entityId, "Erro on Deploy: " + ex.Message);
                throw ex;
            }
            finally
            {
                deployLog.Clear();
                deployLog = null;

                if (dtPlugins != null)
                {
                    dtPlugins.Clear();
                }
                dtPlugins = null;

                if (dtEnt != null)
                {
                    dtEnt.Clear();
                }
                dtEnt = null;

                if (licControl != null)
                {
                    try
                    {
                        List <Int64> k = new List <Int64>();
                        k.AddRange(licControl.Keys);

                        foreach (Int64 l in k)
                        {
                            if (licControl[l] != null)
                            {
                                licControl[l].Dispose();
                                licControl[l] = null;
                            }
                        }

                        k.Clear();
                    }
                    catch { }
                }
                licControl = null;
            }

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

            html += "<form id=\"serviceLogin\" name=\"serviceLogin\" method=\"post\" action=\"" + Session["ApplicationVirtualPath"] + "login2/recover/step1/\"><div class=\"login_form\">";

            LoginData login = LoginUser.LogedUser(this);

            if (login != null)
            {
                if (Session["last_page"] != null)
                {
                    Response.Redirect(Session["last_page"].ToString());
                    Session["last_page"] = null;
                }
                else
                {
                    Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "autoservice/", false);
                }
            }
            else if (Session["user_info"] == null || !(Session["user_info"] is Int64))
            {
                //Serviço não informado ou não encontrado
                html += "    <ul>";
                html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("invalid_session") + "</div>";
                html += "    </ul>";
            }
            else
            {
                Int64 entityId     = (Int64)Session["user_info"];
                Int64 enterpriseID = ((EnterpriseData)Page.Session["enterprise_data"]).Id;

                String err = "";


                if (Request.HttpMethod == "POST")
                {
                    String sentTo = Request["sentTo"];
                    if ((sentTo == null) || (sentTo == ""))
                    {
                        error = MessageResource.GetMessage("select_option");
                    }
                    else
                    {
                        using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        {
                            List <String> possibleData = new List <string>();
                            DataTable     c            = db.Select("select value from vw_entity_all_data where id = " + entityId);
                            if ((c != null) && (c.Rows.Count > 0))
                            {
                                foreach (DataRow dr in c.Rows)
                                {
                                    if (!possibleData.Contains(dr["value"].ToString().ToLower()))
                                    {
                                        possibleData.Add(dr["value"].ToString().ToLower());
                                    }
                                }

                                if (possibleData.Count > 0)
                                {
                                    DirectoryInfo pluginPath = new DirectoryInfo(Path.Combine(HostingEnvironment.MapPath("~"), "code_plugins"));
                                    if (!pluginPath.Exists)
                                    {
                                        pluginPath.Create();
                                    }

                                    List <CodeManagerPluginBase> plugins = CodePlugins.GetPlugins <CodeManagerPluginBase>(pluginPath.FullName);
                                    if (plugins.Count > 0)
                                    {
                                        CodeManagerPluginBase p = CodeManagerPluginBase.GetPluginByData(plugins, possibleData, sentTo);

                                        if (p != null)
                                        {
                                            try
                                            {
                                                DataTable tmp = db.Select(String.Format("select id, recovery_code from entity with(nolock) where deleted = 0 and id = {0}", entityId));
                                                if ((tmp == null) || (tmp.Rows.Count == 0))
                                                {
                                                    error = MessageResource.GetMessage("entity_not_found");
                                                }

                                                Dictionary <String, Object> config = new Dictionary <String, Object>();
                                                using (DataTable c1 = db.Select("select [key], [value] from code_plugin_par where enterprise_id = " + enterpriseID + " and uri = '" + p.GetPluginId().AbsoluteUri + "'"))
                                                {
                                                    if (c1 != null)
                                                    {
                                                        foreach (DataRow dr1 in c1.Rows)
                                                        {
                                                            CodeManagerPluginBase.FillConfig(p, ref config, dr1["key"].ToString(), dr1["value"]);
                                                        }
                                                    }

                                                    if (p.SendCode(config, possibleData, sentTo, tmp.Rows[0]["recovery_code"].ToString()))
                                                    {
                                                        Response.Redirect(Session["ApplicationVirtualPath"] + "login2/recover/step2/", false);
                                                        return;
                                                    }
                                                    else
                                                    {
                                                        error = "Erro enviando código de recuperação";
                                                    }
                                                }
                                                config.Clear();
                                                config = null;
                                            }
                                            catch (Exception ex)
                                            {
                                                error = ex.Message;
                                            }
                                        }
                                        else
                                        {
                                            error = MessageResource.GetMessage("option_not_found");
                                        }
                                    }
                                    else
                                    {
                                        error = MessageResource.GetMessage("option_not_found");
                                    }
                                }
                                else
                                {
                                    error = MessageResource.GetMessage("option_not_found");
                                }
                            }
                            else
                            {
                                error = MessageResource.GetMessage("option_not_found");
                            }

                            //Resgata todos os plugind possíveis


                            /*
                             * DataTable c = db.Select("select * from vw_entity_mails where mail like '%@%' and entity_id = " + entityId);
                             * if ((c != null) && (c.Rows.Count > 0))
                             * {
                             *  DataRow drSentTo = null;
                             *  foreach (DataRow dr in c.Rows)
                             *  {
                             *      String data = LoginUser.MaskData(dr["mail"].ToString(), true, false);
                             *      if (sentTo.ToString().ToLower() == data)
                             *      {
                             *          drSentTo = dr;
                             *          break;
                             *      }
                             *  }
                             *
                             *  if (drSentTo == null)
                             *      error = MessageResource.GetMessage("option_not_found");
                             *  else
                             *  {
                             *
                             *      //if (LoginUser.SendCode(entityId, drSentTo["value"].ToString(), (Boolean)drSentTo["is_mail"], (Boolean)drSentTo["is_sms"], out err))
                             *      if (LoginUser.SendCode(entityId, drSentTo["mail"].ToString(), true, false, out err))
                             *      {
                             *          Response.Redirect(Session["ApplicationVirtualPath"] + "login2/recover/step2/", false);
                             *          return;
                             *      }
                             *      else
                             *      {
                             *          error = err;
                             *      }
                             *
                             *  }
                             * }
                             * else
                             * {
                             *  error = MessageResource.GetMessage("option_not_found");
                             * }*/
                        }
                    }
                }

                LoginUser.NewCode(this, entityId, out err);
                if (err == "")
                {
                    using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                    {
                        List <CodeData> dataList     = new List <CodeData>();
                        List <String>   possibleData = new List <string>();
                        DataTable       c            = db.Select("select value from vw_entity_all_data where id = " + entityId);
                        if ((c != null) && (c.Rows.Count > 0))
                        {
                            foreach (DataRow dr in c.Rows)
                            {
                                if (!possibleData.Contains(dr["value"].ToString().ToLower()))
                                {
                                    possibleData.Add(dr["value"].ToString().ToLower());
                                }
                            }

                            if (possibleData.Count > 0)
                            {
                                DirectoryInfo pluginPath = new DirectoryInfo(Path.Combine(HostingEnvironment.MapPath("~"), "code_plugins"));
                                if (!pluginPath.Exists)
                                {
                                    pluginPath.Create();
                                }

                                List <CodeManagerPluginBase> plugins = CodePlugins.GetPlugins <CodeManagerPluginBase>(pluginPath.FullName);
                                if (plugins.Count > 0)
                                {
                                    foreach (CodeManagerPluginBase p in plugins)
                                    {
                                        try
                                        {
                                            Dictionary <String, Object> config = new Dictionary <String, Object>();
                                            using (DataTable c1 = db.Select("select [key], [value] from code_plugin_par where enterprise_id = " + enterpriseID + " and uri = '" + p.GetPluginId().AbsoluteUri + "'"))
                                            {
                                                if (c1 != null)
                                                {
                                                    foreach (DataRow dr1 in c1.Rows)
                                                    {
                                                        CodeManagerPluginBase.FillConfig(p, ref config, dr1["key"].ToString(), dr1["value"]);
                                                    }
                                                }

                                                //Verifica se existe as configs deste plugin e se estão válidas
                                                if (p.ValidateConfigFields(config))
                                                {
                                                    dataList.AddRange(p.ParseData(possibleData));
                                                }
                                            }
                                            config.Clear();
                                            config = null;
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                }
                            }
                        }

                        if (dataList.Count > 0)
                        {
                            html += "<ul>";
                            html += "    <li>";
                            html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">" + MessageResource.GetMessage("send_conf_to") + "</p>";
                            html += "    </li>";

                            foreach (CodeData data in dataList)
                            {
                                html += "    <li><p style=\"width:400px;padding:0 0 5px 10px;color:#000;\"><input name=\"sentTo\" type=\"radio\" value=\"" + data.DataId + "\">" + data.MaskedData + "</p></li>";
                            }

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

                            html += "    <li>";
                            html += "        <span class=\"forgot\"> <a href=\"/\">" + MessageResource.GetMessage("cancel") + "</a> " + MessageResource.GetMessage("or") + " </span>";
                            html += "            <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("send_code") + "</button>";
                            html += "    </li>";
                            html += "</ul>     ";
                        }
                        else
                        {
                            html += "<ul>";
                            html += "    <li>";
                            html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">No method available</p>";
                            html += "    </li>";
                            html += "    <li>";
                            html += "        <span class=\"forgot\"> <a href=\"/\">" + MessageResource.GetMessage("cancel") + "</a></span>";
                            html += "    </li>";
                            html += "</ul>     ";
                        }

                        /*
                         * //DataTable c = db.Select("select * from vw_entity_confirmations where enterprise_id = " + enterpriseID + " and  entity_id = " + entityId);
                         * DataTable c = db.Select("select * from vw_entity_mails where mail like '%@%' and entity_id = " + entityId);
                         * if ((c != null) && (c.Rows.Count > 0))
                         * {
                         *
                         *  html += "<ul>";
                         *  html += "    <li>";
                         *  html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">" + MessageResource.GetMessage("send_conf_to") + "</p>";
                         *  html += "    </li>";
                         *
                         *  foreach (DataRow dr in c.Rows)
                         *  {
                         *      //String data = LoginUser.MaskData(dr["value"].ToString(), (Boolean)dr["is_mail"], (Boolean)dr["is_sms"]);
                         *      String data = LoginUser.MaskData(dr["mail"].ToString(), true, false);
                         *      if (data != "")
                         *          html += "    <li><p style=\"width:400px;padding:0 0 5px 10px;color:#000;\"><input name=\"sentTo\" type=\"radio\" value=\"" + data + "\">" + data + "</p></li>";
                         *  }
                         *
                         *  if (error != "")
                         *  {
                         *      html += "    <ul>";
                         *      html += "        <li><div class=\"error-box\">" + error + "</div>";
                         *      html += "    </ul>";
                         *  }
                         *
                         *  html += "    <li>";
                         *  html += "        <span class=\"forgot\"> <a href=\"/\">" + MessageResource.GetMessage("cancel") + "</a> " + MessageResource.GetMessage("or") + " </span>";
                         *  html += "            <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("send_code") + "</button>";
                         *  html += "    </li>";
                         *  html += "</ul>     ";
                         * }
                         * else
                         * {
                         *
                         *  html += "<ul>";
                         *  html += "    <li>";
                         *  html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">No method available</p>";
                         *  html += "    </li>";
                         *  html += "    <li>";
                         *  html += "        <span class=\"forgot\"> <a href=\"/\">" + MessageResource.GetMessage("cancel") + "</a></span>";
                         *  html += "    </li>";
                         *  html += "</ul>     ";
                         * }*/
                    }
                }
                else
                {
                    html += "    <ul>";
                    html += "        <li><div class=\"error-box\">" + err + "</div>";
                    html += "    </ul>";
                }
            }

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

            holderContent.Controls.Add(new LiteralControl(html));
        }
Exemplo n.º 21
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.º 22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;



            try
            {
                LoginData login = LoginUser.LogedUser(this);

                String err = "";
                if (!EnterpriseIdentify.Identify(this, false, out err)) //Se houver falha na identificação da empresa finaliza a resposta
                {
                    ret = new WebJsonResponse("", err, 3000, true);
                }
                else if (login == null)
                {
                    ret = new WebJsonResponse("", MessageResource.GetMessage("expired_session"), 3000, true, "/login/");
                }
                else
                {
                    using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                    {
                        DataTable c = db.Select("select * from entity where deleted = 0 and id = " + login.Id);
                        if ((c != null) && (c.Rows.Count > 0))
                        {
                            String html    = "";
                            String content = "<div>{0}</div>";
                            html  = "";
                            html += "<form id=\"serviceRecover\" name=\"serviceRecover\" method=\"post\" action=\"/consoleapi/changepassword/\" onsubmit=\"return iam.GenericSubmit('#serviceRecover');\">";
                            html += "<div class=\"login_form\">";
                            html += "<h1>" + MessageResource.GetMessage("change_password_title") + "</h1> ";
                            html += "<ul>";
                            html += "    <li>";
                            html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">" + MessageResource.GetMessage("change_password_text") + "</p>";
                            html += "    </li>";
                            html += "    <li>";
                            html += "        <span class=\"inputWrap\">";
                            html += "			<span id=\"ph_current_password\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">"+ MessageResource.GetMessage("current_password") + "</span>";
                            html += "			<input type=\"password\" id=\"current_password\" tabindex=\"1\" name=\"current_password\" value=\"\" style=\"\" onkeyup=\"fnLogin.keyup('current_password');\" onfocus=\"$('#current_password').addClass('focus'); fnLogin.keyup('password');\" onblur=\"$('#current_password').removeClass('focus');\" />";
                            html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
                            html += "        </span>";
                            html += "    </li>";
                            html += "    <li>";
                            html += "        <span class=\"inputWrap\">";
                            html += "			<span id=\"ph_password\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">"+ MessageResource.GetMessage("new_password") + "</span>";
                            html += "			<input type=\"password\" id=\"password\" tabindex=\"1\" name=\"password\" value=\"\" style=\"\" onkeyup=\"fnLogin.keyup('password'); iam.passwordStrength('#password');\" onfocus=\"$('#password').addClass('focus'); fnLogin.keyup('password');\" onblur=\"$('#password').removeClass('focus');\" />";
                            html += "			<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
                            html += "        </span>";
                            html += "    </li>";
                            html += "    <li>";
                            html += "        <span class=\"inputWrap\">";
                            html += "			<span id=\"ph_password2\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">"+ MessageResource.GetMessage("new_password_confirm") + "</span>";
                            html += "			<input type=\"password\" id=\"password2\" tabindex=\"1\" name=\"password2\" value=\"\" style=\"\" onkeyup=\"fnLogin.keyup('password2');\" onfocus=\"$('#password2').addClass('focus'); fnLogin.keyup('password2');\" 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>";
                            html += "    <li>";
                            html += "        <span class=\"forgot\"> <a class=\"cancel\">" + MessageResource.GetMessage("cancel") + "</a></span>";
                            html += "        <input type=\"submit\" tabindex=\"4\" id=\"submitBtn\" value=\"" + MessageResource.GetMessage("change_password") + "\" class=\"action btn btn-success\" />";
                            html += "    </li>";
                            html += "</ul>     ";
                            html += "</div>";
                            html += "</form>";

                            ret = new WebJsonResponse("#pn-password .content", String.Format(content, html));
                        }
                        else
                        {
                            ret = new WebJsonResponse("", MessageResource.GetMessage("valid_username"), 3000, true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex);
                throw ex;
            }


            if (ret != null)
            {
                ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Exemplo n.º 23
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.º 24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;

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


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

                String err = "";
                entityId = LoginUser.FindUser(this, Request["userLogin"], out err);
                if (entityId > 0)
                {
                    Session["entityId"] = entityId;

                    LoginUser.NewCode(this, entityId, out err);
                    if (err == "")
                    {
                        String html = "";
                        using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        {
                            DataTable c = db.Select("select * from vw_entity_confirmations where enterprise_id = " + enterpriseID + " and  entity_id = " + entityId);
                            html += "<form id=\"serviceRecover\" name=\"serviceRecover\" method=\"post\" action=\"/consoleapi/recover2/\">";
                            if ((c != null) && (c.Rows.Count > 0))
                            {
                                html += "<div class=\"login_form\">";
                                html += "<input type=\"hidden\" name=\"do\" value=\"recover2\" />";
                                html += "<ul>";
                                html += "    <li>";
                                html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">" + MessageResource.GetMessage("send_conf_to") + "</p>";
                                html += "    </li>";

                                foreach (DataRow dr in c.Rows)
                                {
                                    String data = LoginUser.MaskData(dr["value"].ToString(), (Boolean)dr["is_mail"], (Boolean)dr["is_sms"]);
                                    if (data != "")
                                    {
                                        html += "    <li><p style=\"width:400px;padding:0 0 5px 10px;color:#000;\"><input name=\"sentTo\" type=\"radio\" value=\"" + data + "\">" + data + "</p></li>";
                                    }
                                }

                                html += "    <li>";
                                html += "        <span class=\"forgot\"> <a href=\"/\">" + MessageResource.GetMessage("cancel") + "</a> " + MessageResource.GetMessage("or") + " </span>";
                                html += "            <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("send_code") + "</button>";
                                html += "    </li>";
                                html += "</ul>     ";
                                html += "</div>";
                            }
                            else
                            {
                                html += "<div class=\"login_form\">";
                                html += "<input type=\"hidden\" name=\"do\" value=\"recover2\" />";
                                html += "<ul>";
                                html += "    <li>";
                                html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">No method available</p>";
                                html += "    </li>";
                                html += "    <li>";
                                html += "        <span class=\"forgot\"> <a href=\"/\">" + MessageResource.GetMessage("cancel") + "</a></span>";
                                html += "    </li>";
                                html += "</ul>     ";
                                html += "</div>";
                            }
                            html += "</form>";
                        }

                        //ret = new WebJsonResponse("recover1.aspx");
                        ret = new WebJsonResponse("#recover_container", html);
                    }
                    else
                    {
                        ret = new WebJsonResponse("", err, 3000, true);
                    }
                }
                else
                {
                    ret = new WebJsonResponse("", err, 3000, true);
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex);
                throw ex;
            }


            if (ret != null)
            {
                ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Exemplo n.º 25
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.º 26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;

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


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

                String userCode = Request["userCode"];
                if ((userCode == null) || (userCode == ""))
                {
                    ret = new WebJsonResponse("", MessageResource.GetMessage("type_code"), 3000, true);
                }
                else
                {
                    if (Session["entityId"] != null)
                    {
                        entityId = (Int64)Session["entityId"];
                    }
                    if (entityId > 0)
                    {
                        using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        {
                            DataTable c = db.Select("select * from entity where deleted = 0 and id = " + entityId + " and recovery_code = '" + Tools.Tool.TrataInjection(userCode) + "'");
                            if ((c != null) && (c.Rows.Count > 0))
                            {
                                Session["userCode"] = c.Rows[0]["recovery_code"].ToString();

                                String html = "";
                                html += "<form id=\"serviceRecover\" name=\"serviceRecover\" method=\"post\" action=\"/consoleapi/recover4/\">";
                                html += "<div class=\"login_form\">";
                                html += "<input type=\"hidden\" name=\"do\" value=\"recover4\" />";
                                html += "<ul>";
                                html += "    <li>";
                                html += "        <p style=\"width:100%;padding:0 0 5px 0;color:#000;\">" + MessageResource.GetMessage("new_password_title") + "</p>";
                                html += "    </li>";
                                html += "    <li>";
                                html += "        <span class=\"inputWrap\">";
                                //html += "			<span id=\"ph_password\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">" + MessageResource.GetMessage("new_password") + "</span>";
                                html += "			<input type=\"password\" id=\"password\" tabindex=\"1\" name=\"password\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("new_password") + "\" onkeyup=\"iamadmin.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 += "			<span id=\"ph_password2\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">" + MessageResource.GetMessage("new_password_confirm") + "</span>";
                                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>";
                                html += "    <li>";
                                html += "        <span class=\"forgot\"> <a href=\"/\">" + MessageResource.GetMessage("cancel") + "</a> " + MessageResource.GetMessage("or") + " </span>";
                                html += "        <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("change_password") + "</button>";
                                html += "    </li>";
                                html += "</ul>     ";
                                html += "</div>";
                                html += "</form>";
                                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
        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.º 28
0
        public String UserFlow()
        {
            String userId = "";

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

            EnterpriseData ent = (EnterpriseData)Page.Session["enterprise_data"];

            FlowData flowData = new FlowData();

            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
            {
                DataTable dtEntity = db.Select("select e.*, c.name context_name from entity e inner join context c on e.context_id = c.id where e.id = " + userId);
                if (dtEntity == null)
                {
                    return("");
                }

                Node eNode = flowData.AddNode(dtEntity.Rows[0]["full_name"].ToString(), 0, 1);

                Node ctxNode = flowData.AddNode("Contexto: " + dtEntity.Rows[0]["context_name"].ToString(), 1, 1);
                flowData.AddConnection(eNode, ctxNode, "");

                Node entNode = flowData.AddNode("Entidade", 2, 1);
                flowData.AddConnection(ctxNode, entNode, "");

                DataTable dtIdentity = db.Select("select ROW_NUMBER() OVER (ORDER BY r.name, i.id) AS [row_number], i.id identity_id, r.name resource_name, p.name from [identity] i inner join resource_plugin rp on i.resource_plugin_id = rp.id inner join resource r on rp.resource_id = r.id inner join plugin p on rp.plugin_id = p.id where i.entity_id = " + userId);

                foreach (DataRow drI in dtIdentity.Rows)
                {
                    Node nIdentity = flowData.AddNode("Identidade " + drI["row_number"], 3, 1, true);
                    flowData.AddConnection(entNode, nIdentity, "");

                    Node nSubIdentity = flowData.AddNode(drI["resource_name"].ToString(), 4, 1);
                    flowData.AddConnection(nIdentity, nSubIdentity, "");

                    DataTable dtRole = db.Select("select r.name role_name from identity_role ir inner join role r on ir.role_id = r.id where ir.identity_id = " + drI["identity_id"] + " order by r.name");

                    foreach (DataRow drRole in dtRole.Rows)
                    {
                        Node nRole = flowData.AddNode("Perfil", 5, 1, true);
                        flowData.AddConnection(nSubIdentity, nRole, "");

                        Node nRoleName = flowData.AddNode(drRole["role_name"].ToString(), 6, 1);
                        flowData.AddConnection(nRole, nRoleName, "");
                    }
                }


                Node systemNode = flowData.AddNode("Sistema", 1, 1);
                flowData.AddConnection(eNode, systemNode, "");

                Node nSysRole = flowData.AddNode("Perfis de sistema", 2, 1);
                flowData.AddConnection(systemNode, nSysRole, "");

                DataTable dtSysRole = db.Select("select r.* from sys_entity_role er inner join sys_role r on er.role_id = r.id where er.entity_id = " + userId);

                if ((dtSysRole == null) || (dtSysRole.Rows.Count == 0))
                {
                    Node nRoleName = flowData.AddNode("Nenhum perfil", 3, 1);
                    flowData.AddConnection(nSysRole, nRoleName, "");
                }
                else
                {
                    foreach (DataRow drRole in dtSysRole.Rows)
                    {
                        Node nRoleName = flowData.AddNode(drRole["name"].ToString(), 3, 1);
                        flowData.AddConnection(nSysRole, nRoleName, "");

                        if ((Boolean)drRole["sa"])
                        {
                            nRoleName.name += "\n(Administrador)";
                        }
                        else
                        {
                            DataTable dtSysEnt = db.Select("select * from enterprise e where e.id = " + drRole["enterprise_id"]);

                            foreach (DataRow drEnt in dtSysEnt.Rows)
                            {
                                Node nRoleEntName = flowData.AddNode(drEnt["name"].ToString(), 4, 1);
                                flowData.AddConnection(nRoleName, nRoleEntName, "");

                                if ((Boolean)drRole["ea"])
                                {
                                    nRoleEntName.name += "\n(Administrador)";
                                }
                            }
                        }
                    }
                }
            }

            return(flowData.ToJson());
        }
Exemplo n.º 29
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.º 30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Request.InputStream.Position = 0;

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

                JsonGeneric data = new JsonGeneric();
                data.FromJsonString(req.data);

                if (data.data.Count == 0)
                {
                    return;
                }

                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) //Não encontrou o proxy
                    {
                        return;
                    }

                    String uri = Tools.Tool.TrataInjection(data.data[0][data.GetKeyIndex("uri")]);

                    DataTable dt = db.Select("select * from plugin where uri = '" + uri + "'");

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

                    DirectoryInfo pluginsDir = null;

                    using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                        pluginsDir = new DirectoryInfo(c.GetItem("pluginFolder"));

                    if (pluginsDir == null)
                    {
                        throw new Exception("Parâmtro 'pluginFolder' não encontrado");
                    }

                    if (pluginsDir.Exists)
                    {
                        FileInfo f = new FileInfo(Path.Combine(pluginsDir.FullName, dt.Rows[0]["assembly"].ToString()));

                        if (f.Exists)
                        {
                            Byte[] fData    = File.ReadAllBytes(f.FullName);
                            String fileHash = CATools.SHA1Checksum(fData);

                            Int32 ci = data.GetKeyIndex("checksum");
                            if ((ci != -1) && (data.data[0][ci] == fileHash))
                            {
                                ReturnHolder.Controls.Add(new LiteralControl("{ \"name\":\"" + f.Name + "\", \"status\":\"updated\"}"));
                            }
                            else
                            {
                                String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));
                                using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass), fData))
                                    ReturnHolder.Controls.Add(new LiteralControl("{ \"name\":\"" + f.Name + "\", \"status\":\"outdated\", \"date\":\"" + f.LastWriteTimeUtc.ToString("yyyy-MM-dd HH:mm:ss") + "\", \"content\":\"" + Convert.ToBase64String(cApi.ToBytes()) + "\"}"));
                            }

                            fData = new Byte[0];
                        }
                    }

                    /*
                     * ProxyConfig config = new ProxyConfig();
                     * config.GetDBConfig(IAMDatabase.GetWebConnection(), ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host);
                     *
                     * if (config.fqdn != null)
                     * {
                     *  ReturnHolder.Controls.Add(new LiteralControl(config.ToJsonString()));
                     * }*/
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex);
                throw ex;
            }
        }