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

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

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

                    db.AddUserLog(LogKey.User_NewRecoveryCode, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, entityId, 0, MessageResource.GetMessage("new_recovery_code") + " (" + code + ")", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
                }
        }
        catch (Exception ex)
        {
            error = MessageResource.GetMessage("internal_error");
            Tools.Tool.notifyException(ex, page);
            return;
        }
        finally
        {
        }
    }
Exemple #2
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);
        }
    }
Exemple #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Request.InputStream.Position = 0;

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

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

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

                        db.ExecuteNonQuery("update proxy set last_sync = getdate(), address = '" + Tools.Tool.GetIPAddress() + "', config = 0 where id = " + config.proxyID, System.Data.CommandType.Text, null);
                        ReturnHolder.Controls.Add(new LiteralControl(config.ToJsonString()));
                    }
                    else
                    {
                        db.AddUserLog(LogKey.API_Error, DateTime.Now, "ProxyAPI", UserLogLevel.Warning, 0, ((EnterpriseData)Page.Session["enterprise_data"]).Id, 0, 0, 0, 0, 0, "Proxy not found " + req.host, req.ToString());
                    }
                }
            }
            catch (Exception ex) {
                Tools.Tool.notifyException(ex, this);
                //throw ex;
            }
        }
Exemple #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;


            try
            {
                LoginResult auth = LoginUser.AuthUser(this, Request["userLogin"], Request["password"]);

                if ((auth.Status) && (auth.ChangePassword) && (Session["login"] is LoginData))
                {
                    Session["entity_id"] = ((LoginData)Session["login"]).Id;
                    Session["login"]     = null;
                    ret = new WebJsonResponse("/login/changepassword/");
                }
                else if ((auth.Status) && (Session["login"] is LoginData))
                {
                    Int64 enterpriseId = 0;

                    LoginData login = (LoginData)Session["login"];

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

                    ret = new WebJsonResponse(Session["ApplicationVirtualPath"] + "autoservice/");

                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                    {
                        try
                        {
                            using (IAMRBAC rbac = new IAMRBAC())
                                if (rbac.UserAdmin(database, login.Id, enterpriseId))
                                {
                                    ret = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/");
                                }
                        }
                        catch { }
                    }
                }
                else
                {
                    ret = new WebJsonResponse("", auth.Text, 3000, true);
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex);
                throw ex;
            }


            if (ret != null)
            {
                ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Exemple #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;


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

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

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

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

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


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

            if (!EnterpriseIdentify.Identify(Page, false, true)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                Page.Response.Status     = "403 Access denied";
                Page.Response.StatusCode = 403;
                Page.Response.End();
                return;
            }
            //}

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

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


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

                WebPageAPI.Execute(database, this, eLogs);
            }
        }
Exemple #7
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)
            {
                if (Session["last_page"] != null)
                {
                    Response.Redirect(Session["last_page"].ToString());
                    Session["last_page"] = null;
                }
                else
                {
                    Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "autoservice/");
                }
            }
            else
            {
                try
                {
                    AuthBase authPlugin = null;
                    try
                    {
                        authPlugin = AuthBase.GetPlugin(new Uri(((EnterpriseData)Session["enterprise_data"]).AuthPlugin));
                    }
                    catch { }

                    if (authPlugin == null)
                    {
                        throw new Exception("Plugin não encontrado");
                    }

                    LoginResult tst = null;

                    using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        tst = authPlugin.Auth(db, this);
                }
                catch (Exception ex)
                {
                    Tools.Tool.notifyException(ex, this);
                    throw ex;
                }
            }
        }
Exemple #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod == "POST")
            {
                if (!EnterpriseIdentify.Identify(this, true)) //Se houver falha na identificação da empresa finaliza a resposta
                {
                    return;
                }

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

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

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

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

                    try
                    {
                        using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                            db.AddUserLog(LogKey.API_Error, null, "ProxyAPI", UserLogLevel.Error, 0, (((Page.Session["enterprise_data"]) != null && (Page.Session["enterprise_data"] is EnterpriseData) && (((EnterpriseData)Page.Session["enterprise_data"]).Id != null)) ? ((EnterpriseData)Page.Session["enterprise_data"]).Id : 0), 0, 0, 0, 0, 0, "Proxy API error: " + ex.Message, Tools.Tool.getExceptionText(ex, this));
                    }
                    catch { }
                }
            }
            else
            {
                ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(false, "Invalid http method", "")));
            }
        }
Exemple #9
0
        public static void UpdateUri(Page page)
        {
            if (page.Session["Uri"] == null)
            {
                Int64 enterpriseId = 0;

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

                if (enterpriseId == 0)
                {
                    return;
                }


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

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

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

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

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

                    page.Session["Uri"] = url;
                }
                catch
                {
                    page.Session["Uri"] = null;
                }
            }
        }
Exemple #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            MAutoservice mClass = ((MAutoservice)this.Master);

            Tools.Tool.UpdateUri(this);

            LoginData login   = LoginUser.LogedUser(this.Page);
            Boolean   isAdmin = false;

            if (login != null)
            {
                IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString());
                try
                {
                    Int64 enterpriseId = 0;

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


                    using (IAMRBAC rbac = new IAMRBAC())
                        isAdmin = rbac.HasAdminConsole(database, login.Id, enterpriseId);
                }
                catch { }
            }

            String html = "";

            html += "<ul class=\"home\">";

            if (isAdmin)
            {
                html += "    <li><a href=\"" + Session["ApplicationVirtualPath"] + "admin/\"><div class=\"btn c2\"><div class=\"inner\"><i class=\"icon-change\"></i><span>Admin</span></div></div></a></li>";
            }

            html += "    <li><a href=\"" + Session["ApplicationVirtualPath"] + "autoservice/user/\"><div class=\"btn c3\"><div class=\"inner\"><i class=\"icon-profile\"></i><span>Informações gerais</span></div></div></a></li>";
            html += "    <li><a href=\"" + Session["ApplicationVirtualPath"] + "autoservice/user/changepassword/\"><div class=\"btn c1\"><div class=\"inner\"><i class=\"icon-key\"></i><span>Alterar senha</span></div></div></a></li>";
            html += "    <li><a href=\"" + Session["ApplicationVirtualPath"] + "autoservice/access_request/\"><div class=\"btn c5\"><div class=\"inner\"><i class=\"icon-page\"></i><span>Requisição de acesso</span></div></div></a></li>";
            html += "    <li><a href=\"" + Session["ApplicationVirtualPath"] + "logout/\"><div class=\"btn c4\"><div class=\"inner\"><i class=\"icon-exit\"></i><span>Desconectar</span></div></div></a></li>";
            html += "</ul>";

            contentHolder.Controls.Add(new LiteralControl(html));
        }
Exemple #11
0
        public static EnterpriseData EnterpriseByService(Page page, String service)
        {
            if (String.IsNullOrEmpty(service))
            {
                return(null);
            }

            DbParameterCollection par = null;

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

                using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    DataTable dt = db.ExecuteDataTable("select * from [cas_service] s inner join enterprise e on s.enterprise_id = e.id where s.service_uri = @svc", CommandType.Text, par);

                    if ((dt != null) && (dt.Rows.Count > 0))
                    {
                        EnterpriseData data = new EnterpriseData();
                        data.Host = page.Request.Url.Host.ToLower();

                        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"];

                        return(data);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
            finally
            {
                par = null;
            }
        }
Exemple #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Session.Abandon();

            try
            {
                AuthBase authPlugin = null;
                try
                {
                    authPlugin = AuthBase.GetPlugin(new Uri(((EnterpriseData)Session["enterprise_data"]).AuthPlugin));
                }
                catch { }

                if (authPlugin == null)
                {
                    Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "autoservice/", false);
                    return;
                }
                else
                {
                    using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        authPlugin.Logout(db, this);
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex, this);
                throw ex;
            }

            /*
             * try
             * {
             *  String service = HttpUtility.UrlEncode(Request.Url.Scheme + "://" + Request.Url.Host + (Request.Url.Port != 80 ? ":" + Request.Url.Port : "") + "/login/");
             *
             *  using (ServerDBConfig conf = new ServerDBConfig(IAMDatabase.GetWebConnection()))
             *  {
             *      Response.Redirect(((EnterpriseData)Session["enterprise_data"]).CasService.TrimEnd("/".ToCharArray()) + "/logout/?service=" + service, false);
             *  }
             * }
             * catch(Exception ex)
             * {
             *  Response.Redirect("/");
             * }*/
        }
Exemple #13
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
        {
        }
    }
Exemple #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Request.InputStream.Position = 0;

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

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

                        if (config.fqdn != null) //Encontrou o proxy
                        {
                            if ((req.data != null) && (req.data != ""))
                            {
                                String dData = req.data;

                                try
                                {
                                    dData = Encoding.UTF8.GetString(Convert.FromBase64String(dData));
                                }
                                catch { }

                                String header = "Proxy: " + req.host + Environment.NewLine;
                                header += "IP: " + Tools.Tool.GetIPAddress() + Environment.NewLine;
                                header += "Data: " + Environment.NewLine + Environment.NewLine;

                                Tools.Tool.sendEmail("Proxy log received from " + req.host + " " + DateTime.Now.ToString("yyyy-MM-dd"), conf.GetItem("to"), header + dData, false);
                            }

                            ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", "Request received with " + (req.data != null ? req.data.Length.ToString() : "0") + " bytes and proxy found")));
                        }
                    }
            }
            catch (Exception ex) {
                Tools.Tool.notifyException(ex);
                throw ex;
            }
        }
Exemple #15
0
        public static Boolean ServiceExists(String service)
        {
            if (String.IsNullOrEmpty(service))
            {
                return(false);
            }

            DbParameterCollection par = null;

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

                DataTable dt = null;

                using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                    dt = db.ExecuteDataTable("select * from [cas_service] where service_uri = @svc", CommandType.Text, par);

                if ((dt != null) && (dt.Rows.Count > 0))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
                par = null;
            }
        }
Exemple #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Request.InputStream.Position = 0;

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

                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    ProxyFetchData fetchData = new ProxyFetchData();
                    fetchData.GetDBData(database.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host);

                    if (fetchData.proxy_id > 0) //Encontrou o proxy
                    {
                        ReturnHolder.Controls.Add(new LiteralControl("{ \"response\":\"success\", \"data\":\"" + Convert.ToBase64String(fetchData.ToBytes()) + "\"}"));
                    }
                }
            }
            catch (Exception ex) {
                Tools.Tool.notifyException(ex, this);
                throw ex;
            }
        }
Exemple #17
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));
        }
Exemple #18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!EnterpriseIdentify.Identify(Page, false, true)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                Page.Response.Status     = "403 Access denied";
                Page.Response.StatusCode = 403;
                Page.Response.End();
                return;
            }
            else
            {
                String proxyName = "";
                String version   = "";
                Int32  pid       = 0;
                try
                {
                    proxyName = Request.Headers["X-SAFEID-PROXY"];
                }
                catch { }

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

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

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

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

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


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

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

                                files = outDir.GetDirectories().Length;

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

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

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

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



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

                Page.Response.HeaderEncoding = Encoding.UTF8;
                ReturnHolder.Controls.Add(new LiteralControl("{\"config\":" + rConfig + ",\"files\":" + files + ",\"fetch\":" + fetch + ",\"restart\":" + (restart ? "1" : "0") + "}"));
            }
        }
Exemple #19
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()));
            }
        }
Exemple #20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse contentRet = null;

            Int64 userId = 0;

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

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

            String action = "";

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

            if ((userId == 0) && (action != "add_user"))
            {
                contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                action     = "";
            }

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

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

                    Int64 rpId = 0;
                    try
                    {
                        rpId = Int64.Parse((String)Request.Form["resource_plugin"]);

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


                    String[] fItems = (String.IsNullOrEmpty(Request.Form["field_id"]) ? new String[0] : Request.Form["field_id"].Split(",".ToCharArray()));
                    if (fItems.Length == 0)
                    {
                        contentRet = new WebJsonResponse("", "Nenhum campo mapeado", 3000, false);
                        break;
                    }


                    List <Dictionary <String, String> > properties = new List <Dictionary <String, String> >();

                    WebJsonResponse iError = null;
                    foreach (String sfId in fItems)
                    {
                        Int64 fId = 0;
                        try
                        {
                            fId = Int64.Parse(sfId);
                            String[] values = (String.IsNullOrEmpty(Request.Form[sfId]) ? new String[0] : Request.Form[sfId].Split(",".ToCharArray()));

                            foreach (String v in values)
                            {
                                if (!String.IsNullOrWhiteSpace(v))
                                {
                                    Dictionary <String, String> newItem = new Dictionary <string, string>();
                                    newItem.Add("field_id", fId.ToString());
                                    newItem.Add("value", v.Trim());

                                    properties.Add(newItem);
                                }
                            }
                        }
                        catch
                        {
                            iError = new WebJsonResponse("", "Campo '" + fId + "' inválido", 3000, false);
                            break;
                        }
                    }

                    if (iError != null)
                    {
                        contentRet = iError;
                        break;
                    }


                    if (properties.Count == 0)
                    {
                        contentRet = new WebJsonResponse("", "Nenhum campo mapeado", 3000, false);
                        break;
                    }

                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.new",
                        parameters = new
                        {
                            resourcepluginid = rpId,
                            properties       = properties
                        },
                        id = 1
                    });


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


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

                    GetResult retNew = JSON.Deserialize <GetResult>(jData);
                    if (retNew == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retNew.error != null)
                    {
                        contentRet = new WebJsonResponse("", retNew.error.data, 3000, true);
                    }
                    else if (retNew.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/users/" + retNew.result.info.userid + "/");
                    }
                    break;


                case "deploy":

                    var reqD = new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.deploy",
                        parameters = new
                        {
                            userid = userId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqD);

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


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

                    Logs retD = JSON.Deserialize <Logs>(jData);
                    if (retD == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retD.error != null)
                    {
                        contentRet = new WebJsonResponse("", retD.error.data, 3000, true);
                    }
                    else if (retD.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("", "Dados do usuário enviados para replicação", 3000, false);
                    }
                    break;

                case "change_container":

                    String containerId = Request.Form["container"];
                    if (String.IsNullOrEmpty(containerId))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("select_container"), 3000, true);
                        break;
                    }

                    var reqAdd = new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.changecontainer",
                        parameters = new
                        {
                            containerid = containerId,
                            userid      = userId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqAdd);

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

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

                    BooleanResult retCCont = JSON.Deserialize <BooleanResult>(jData);
                    if (retCCont == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retCCont.error != null)
                    {
                        contentRet = new WebJsonResponse("", retCCont.error.data, 3000, true);
                        //Tools.Tool.notifyException(new Exception(retAdd.error.data + retAdd.error.debug), this);
                    }
                    else if (!retCCont.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/users/" + userId);
                    }

                    break;

                case "change_property":

                    List <Dictionary <String, String> > prop = new List <Dictionary <String, String> >();
                    String[] findex = (String.IsNullOrEmpty(Request.Form["field_index"]) ? new String[0] : Request.Form["field_index"].Split(",".ToCharArray()));
                    foreach (String sfId in findex)
                    {
                        if ((!String.IsNullOrEmpty(Request.Form["field_id_" + sfId])) && (!String.IsNullOrEmpty(Request.Form["field_value_" + sfId])))
                        {
                            Int64 fieldId = Int64.Parse(Request.Form["field_id_" + sfId]);

                            Dictionary <String, String> newItem = new Dictionary <string, string>();
                            newItem.Add("field_id", fieldId.ToString());
                            newItem.Add("value", Request.Form["field_value_" + sfId]);

                            prop.Add(newItem);
                        }
                    }

                    rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.changeproperty",
                        parameters = new
                        {
                            userid     = userId,
                            properties = prop
                        },
                        id = 1
                    });

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

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

                    GetResult retChange = JSON.Deserialize <GetResult>(jData);
                    if (retChange == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retChange.error != null)
                    {
                        contentRet = new WebJsonResponse("", retChange.error.data, 3000, true);
                    }
                    else if (retChange.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/users/" + retChange.result.info.userid + "/property/");
                    }
                    break;

                case "resetpwd":

                    var tmpReq = new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.resetpassword",
                        parameters = new
                        {
                            userid      = userId,
                            must_change = true
                        },
                        id = 1
                    };

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

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

                    Logs ret = JSON.Deserialize <Logs>(jData);
                    if (ret == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (ret.error != null)
                    {
                        contentRet = new WebJsonResponse("", ret.error.data, 3000, true);
                    }
                    else if (ret.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("", "Senha do usuário redefinida para o padrão do sistema", 3000, false);
                    }

                    break;

                case "lock":
                case "unlock":

                    var unReq = new
                    {
                        jsonrpc    = "1.0",
                        method     = "user." + (action == "lock" ? "lock" : "unlock"),
                        parameters = new
                        {
                            userid = userId
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(unReq);

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

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

                    Logs unRet = JSON.Deserialize <Logs>(jData);
                    if (unRet == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (unRet.error != null)
                    {
                        contentRet = new WebJsonResponse("", unRet.error.data, 3000, true);
                    }
                    else if (unRet.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse("", "Usuário " + (action == "lock" ? "Bloqueado" : "Desbloqueado") + " com sucesso", 5000, false);
                    }

                    break;

                case "delete_identity":

                    var reqDel = new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.deleteidentity",
                        parameters = new
                        {
                            userid     = userId,
                            identityid = (String)RouteData.Values["filter"]
                        },
                        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("identity_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("identity_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;

                case "unlock_identity":

                    rData = JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "user.unlockidentity",
                        parameters = new
                        {
                            userid     = userId,
                            identityid = (String)RouteData.Values["filter"]
                        },
                        id = 1
                    });

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

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

                    RoleDeleteResult retUnlockIdentity = JSON.Deserialize <RoleDeleteResult>(jData);
                    if (retUnlockIdentity == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("identity_not_found"), 3000, true);
                    }
                    else if (retUnlockIdentity.error != null)
                    {
                        contentRet = new WebJsonResponse("", retUnlockIdentity.error.data, 3000, true);
                    }
                    else if (!retUnlockIdentity.result)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("identity_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()));
            }
        }
Exemple #21
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());
        }
Exemple #22
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());
        }
Exemple #23
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());
        }
Exemple #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!EnterpriseIdentify.Identify(this.Page)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                return;
            }

            login = LoginUser.LogedUser(this.Page);

/*#if DEBUG
 *          if (login == null)
 *          {
 *              //Somente para debug na maquina de devel
 *              if (Request.Url.Host == "localhost")
 *              {
 *                  login = new LoginData();
 *                  login.EnterpriseId = 1;
 *                  login.FullName = "Helvio Junior";
 *                  login.Alias = "helvio";
 *                  login.Login = "******";
 *                  login.Id = 937;
 *                  Session["login"] = login;
 *              }
 *          }
 #endif*/

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

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

            if (login != null)
            {
                userName = login.FullName;

                try
                {
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        using (IAMRBAC rbac = new IAMRBAC())
                            isAdmin = rbac.UserAdmin(database, login.Id, enterpriseId);
                }
                catch { }
            }

            //Identifica a página atual com objetivo de mostrar o ícone como selecionado no rodapé
            String scriptName             = Request.Params["SCRIPT_NAME"].ToLower();
            String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();

            if (ApplicationVirtualPath == "/")
            {
                ApplicationVirtualPath = "";
            }

            if (ApplicationVirtualPath != "")
            {
                scriptName = scriptName.Replace(ApplicationVirtualPath, "");
            }

            l1         = l2 = l3 = false;
            scriptName = scriptName.Trim("/ ".ToCharArray());
            switch (scriptName.ToLower())
            {
            case "autoservice":
                l1 = true;
                break;
            }
        }
Exemple #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod != "POST")
            {
                return;
            }

            String area = "";

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

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

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

            LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
            LMenu menu2 = new LMenu("Empresa", ApplicationVirtualPath + "admin/enterprise/");
            LMenu menu3 = new LMenu(ent.Name, ApplicationVirtualPath + "admin/enterprise/");

            WebJsonResponse contentRet = null;

            String              html               = "";
            String              eHtml              = "";
            String              error              = "";
            String              filter             = "";
            HashData            hashData           = new HashData(this);
            EnterpriseGetResult selectedEnterprise = null;

            //No caso específico da empresa (que não possibilita que o usuário selecione outra)
            //O ID se tornará o filtro
            if (!String.IsNullOrWhiteSpace((String)RouteData.Values["id"]))
            {
                filter = (String)RouteData.Values["id"];
            }

            String errorTemplate = "<span class=\"empty-results\">{0}</span>";

            if (area.ToLower() != "search")
            {
                try
                {
                    var tmpReq = new
                    {
                        jsonrpc    = "1.0",
                        method     = "enterprise.get",
                        parameters = new
                        {
                            enterpriseid = ent.Id
                        },
                        id = 1
                    };

                    String rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                    String jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


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

                    selectedEnterprise = JSON.Deserialize <EnterpriseGetResult>(jData);
                    if (selectedEnterprise == null)
                    {
                        error = MessageResource.GetMessage("enterprise_not_found");
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (selectedEnterprise.error != null)
                    {
                        error = selectedEnterprise.error.data;
                        selectedEnterprise = null;
                    }
                    else if (selectedEnterprise.result == null || selectedEnterprise.result.info == null)
                    {
                        error = MessageResource.GetMessage("enterprise_not_found");
                        selectedEnterprise = null;
                    }
                    else
                    {
                        menu3.Name = selectedEnterprise.result.info.name;
                    }
                }
                catch (Exception ex)
                {
                    error = MessageResource.GetMessage("api_error");
                    Tools.Tool.notifyException(ex, this);
                    selectedEnterprise = null;
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }
            }

            switch (area)
            {
            case "":
            case "content":
                if (selectedEnterprise != null)
                {
                    switch (filter)
                    {
                    case "":
                    case "info":

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

                        if (filter == "" || filter == "info")
                        {
                            if (hashData.GetValue("edit") == "1")
                            {
                                html += "<form  id=\"form_enterprise_change\"  method=\"POST\" action=\"" + ApplicationVirtualPath + "admin/enterprise/action/change/\">";
                                html += "<h3>Informações gerais</h3>";
                                html += "<div class=\"no-tabs pb10\">";

                                html += String.Format(infoTemplate, "Nome", "<input id=\"name\" name=\"name\" placeholder=\"Digite o nome da empresa\" type=\"text\"\" value=\"" + selectedEnterprise.result.info.name + "\">");
                                html += String.Format(infoTemplate, "Host principal", selectedEnterprise.result.info.fqdn);
                                html += String.Format(infoTemplate, "Criado em", MessageResource.FormatDate(((DateTime) new DateTime(1970, 1, 1)).AddSeconds(selectedEnterprise.result.info.create_date), false));

                                //Resgata a listagem dos plugins de autenticação disponíveis
                                List <AuthBase> plugins = AuthBase.GetPlugins <AuthBase>();
                                String          select  = "";
                                select += "<select id=\"auth_plugin\" name=\"auth_plugin\" >";

                                foreach (AuthBase p in plugins)
                                {
                                    select += "<option selector=\"" + p.GetPluginId().AbsoluteUri.Replace("/", "").Replace(":", "") + "\" value=\"" + p.GetPluginId().AbsoluteUri + "\" " + (p.Equal(new Uri(selectedEnterprise.result.info.auth_plugin)) ? "selected=\"selected\"" : "") + ">" + p.GetPluginName() + "</option>";
                                }

                                select += "</select>";

                                html += String.Format(infoTemplate, "Serviço de autenticação", select);

                                //Caso tenha algum paràmetro p/ o plugin exibe
                                foreach (AuthBase p in plugins)
                                {
                                    AuthConfigFields[] fields = p.GetConfigFields();
                                    if (fields.Length > 0)
                                    {
                                        html += "<div class=\"auth_cont " + p.GetPluginId().AbsoluteUri.Replace("/", "").Replace(":", "") + "\" " + (p.Equal(new Uri(selectedEnterprise.result.info.auth_plugin)) ? "" : "style=\"display:none;\"") + ">";
                                        foreach (AuthConfigFields f in fields)
                                        {
                                            String value = "";

                                            try
                                            {
                                                foreach (EnterpriseAuthPars par in selectedEnterprise.result.auth_parameters)
                                                {
                                                    if (par.key == f.Key)
                                                    {
                                                        value = par.value;
                                                    }
                                                }
                                            }
                                            catch { }

                                            html += String.Format(infoTemplate, f.Name, "<input id=\"f_" + f.Key + "\" name=\"f_" + f.Key + "\" placeholder=\"" + f.Description + "\" type=\"text\"\" value=\"" + value + "\">");
                                        }
                                        html += "</div>";
                                    }
                                }

                                html += "<div class=\"clear-block\"></div></div>";
                            }
                            else
                            {
                                html += "<h3>Informações gerais<div class=\"btn-box\"><div class=\"a-btn ico icon-change\" onclick=\"iamadmin.changeHash( 'edit/1' );\">Editar</div></div></h3>";
                                html += "<div class=\"no-tabs pb10\">";

                                html += String.Format(infoTemplate, "Nome", selectedEnterprise.result.info.name);
                                html += String.Format(infoTemplate, "Host principal", selectedEnterprise.result.info.fqdn);
                                html += String.Format(infoTemplate, "Criado em", MessageResource.FormatDate(((DateTime) new DateTime(1970, 1, 1)).AddSeconds(selectedEnterprise.result.info.create_date), false));

                                try
                                {
                                    AuthBase plugin = AuthBase.GetPlugin(new Uri(selectedEnterprise.result.info.auth_plugin));
                                    html += String.Format(infoTemplate, "Serviço de autenticação", plugin.GetPluginName());


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

                                            try
                                            {
                                                foreach (EnterpriseAuthPars par in selectedEnterprise.result.auth_parameters)
                                                {
                                                    if (par.key == f.Key)
                                                    {
                                                        value = par.value;
                                                    }
                                                }
                                            }
                                            catch { }

                                            html += String.Format(infoTemplate, f.Name, value);
                                        }
                                    }
                                }
                                catch
                                {
                                    html += String.Format(infoTemplate, "Serviço de autenticação", "Erro ao carregar informações do plugin");
                                }


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

                            html += "<h3>Hosts complementares</h3>";
                            html += "<div class=\"no-tabs pb10\">";


                            if (hashData.GetValue("edit") == "1")
                            {
                                html += "<div id=\"enterprise_hosts\">";

                                if (selectedEnterprise.result.fqdn_alias != null)
                                {
                                    for (Int32 i = 1; i <= selectedEnterprise.result.fqdn_alias.Count; i++)
                                    {
                                        html += String.Format(infoTemplate, "Host " + i, "<input id=\"host_" + i + "\" name=\"host_" + i + "\" placeholder=\"Digite o host\" type=\"text\"\" value=\"" + selectedEnterprise.result.fqdn_alias[i - 1] + "\">");
                                    }
                                }

                                html += "</div>";         //Div enterprise_hosts

                                html += String.Format(infoTemplate, "", "<div class=\"a-btn blue secondary floatleft\" onclick=\"iamfnc.addHostField()\">Adicionar host</div>");
                                jsAdd = "iamfnc = $.extend({}, iamfnc, { addHostField: function() { var host = 'host_'+ new Date().getTime(); $('#enterprise_hosts').append('" + String.Format(infoTemplate, "Host ", "<input id=\"'+ host +'\" name=\"'+ host +'\" placeholder=\"Digite o host\" type=\"text\">") + "'); } });";

                                jsAdd += "$('#auth_plugin').change(function() { $('.auth_cont').css('display','none'); $('.' + $('#auth_plugin option:selected').attr('selector') ).css('display','block'); });";
                            }
                            else
                            {
                                if (selectedEnterprise.result.fqdn_alias != null)
                                {
                                    for (Int32 i = 1; i <= selectedEnterprise.result.fqdn_alias.Count; i++)
                                    {
                                        html += String.Format(infoTemplate, "Host " + i, selectedEnterprise.result.fqdn_alias[i - 1]);
                                    }
                                }
                            }


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

                            if (hashData.GetValue("edit") == "1")
                            {
                                html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button>    <a class=\"button link floatleft\" onclick=\"iamadmin.changeHash( 'edit/0' );\">Cancelar</a></form>";
                            }
                        }

                        contentRet    = new WebJsonResponse("#content-wrapper", html);
                        contentRet.js = jsAdd;
                        break;


                    case "flow":

                        String js2 = "";
                        if (filter == "" || filter == "flow")
                        {
                            html += "<h3>Fluxo de dados</h3>";
                            html += "<div id=\"enterpriseChart\"></div>";
                            js2   = "$('#enterpriseChart').flowchart({load_uri: '" + ApplicationVirtualPath + "admin/chartdata/flow/enterprise/'});";
                        }

                        contentRet    = new WebJsonResponse("#content-wrapper", html);
                        contentRet.js = js2;
                        break;
                    }
                }
                else
                {
                    contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                }
                break;

            case "sidebar":
                if (menu1 != null)
                {
                    html += "<div class=\"section-nav-header\">";
                    html += "    <div class=\"crumbs\">";
                    html += "        <div class=\"subject subject-color\">";
                    html += "            <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>";
                    html += "        </div>";
                    if (menu2 != null)
                    {
                        html += "        <div class=\"topic topic-color\">";
                        html += "            <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>";
                        html += "        </div>";
                    }
                    html += "    </div>";
                    if (menu3 != null)
                    {
                        html += "    <div class=\"crumbs tutorial-title\">";
                        html += "        <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>";
                        html += "    </div>";
                    }
                    html += "</div>";
                }


                if (selectedEnterprise != null)
                {
                    html += "<ul class=\"user-profile\">";
                    html += "<li " + (filter == "" ? "class=\"bold\"" : "") + "><span><a href=\"" + ApplicationVirtualPath + "admin/enterprise/\">Todas as informações</a></span></li>";
                    html += "<li " + (filter == "flow" ? "class=\"bold\"" : "") + "><span><a href=\"" + ApplicationVirtualPath + "admin/enterprise/flow\">Fluxo</a></span></li>";
                    html += "</ul>";
                }

                contentRet = new WebJsonResponse("#main aside", html);
                break;

            case "mobilebar":
                break;

            case "buttonbox":
                break;
            }

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

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Exemple #26
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 fieldId = 0;

            if (action != "add_field")
            {
                try
                {
                    fieldId = Int64.Parse((String)RouteData.Values["id"]);

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

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

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

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

                    var reqDel = new
                    {
                        jsonrpc    = "1.0",
                        method     = "field.delete",
                        parameters = new
                        {
                            fieldid = fieldId
                        },
                        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("");
                    }

                    FieldDeleteResult retDel = JSON.Deserialize <FieldDeleteResult>(jData);
                    if (retDel == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("field_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("field_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse();
                    }
                    break;

                case "add_field":

                    String name = Request.Form["field_name"];
                    if (String.IsNullOrEmpty(name))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("invalid_name"), 3000, true);
                        break;
                    }

                    String data_type = Request.Form["data_type"];
                    if (String.IsNullOrEmpty(data_type))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("select_data_type"), 3000, true);
                        break;
                    }


                    var reqN = new
                    {
                        jsonrpc    = "1.0",
                        method     = "field.new",
                        parameters = new
                        {
                            name         = name,
                            data_type    = data_type,
                            public_field = (!String.IsNullOrEmpty(Request.Form["public"]) ? true : false),
                            user_field   = (!String.IsNullOrEmpty(Request.Form["user"]) ? true : false)
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqN);

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

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

                    FieldGetResult retN = JSON.Deserialize <FieldGetResult>(jData);
                    if (retN == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("field_not_found"), 3000, true);
                    }
                    else if (retN.error != null)
                    {
                        contentRet = new WebJsonResponse("", retN.error.data, 3000, true);
                    }
                    else if (retN.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("field_not_found"), 3000, true);
                    }
                    else if (retN.result == null || retN.result.info == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("field_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/field/" + retN.result.info.field_id + "/");
                    }
                    break;

                case "change":

                    String name1 = Request.Form["name"];
                    if (String.IsNullOrEmpty(name1))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("invalid_name"), 3000, true);
                        break;
                    }

                    String data_type1 = Request.Form["data_type"];
                    if (String.IsNullOrEmpty(data_type1))
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("select_data_type"), 3000, true);
                        break;
                    }


                    var reqC = new
                    {
                        jsonrpc    = "1.0",
                        method     = "field.change",
                        parameters = new
                        {
                            fieldid      = fieldId,
                            name         = name1,
                            data_type    = data_type1,
                            public_field = (!String.IsNullOrEmpty(Request.Form["public"]) ? true : false),
                            user_field   = (!String.IsNullOrEmpty(Request.Form["user"]) ? true : false)
                        },
                        id = 1
                    };

                    rData = JSON.Serialize2(reqC);

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

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

                    FieldGetResult retC = JSON.Deserialize <FieldGetResult>(jData);
                    if (retC == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("field_not_found"), 3000, true);
                    }
                    else if (retC.error != null)
                    {
                        contentRet = new WebJsonResponse("", retC.error.data, 3000, true);
                    }
                    else if (retC.result == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("field_not_found"), 3000, true);
                    }
                    else if (retC.result == null || retC.result.info == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("field_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/field/" + retC.result.info.field_id + "/");
                    }
                    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()));
            }
        }
Exemple #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.HttpMethod != "POST")
            {
                return;
            }

            String area = "";

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

            Int64 enterpriseId = 0;

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

            Boolean newItem = false;

            if ((RouteData.Values["new"] != null) && (RouteData.Values["new"] == "1"))
            {
                newItem = true;
            }

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

            LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/");
            LMenu menu2 = new LMenu("Proxy", ApplicationVirtualPath + "admin/proxy/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));
            LMenu menu3 = new LMenu("Proxy", ApplicationVirtualPath + "admin/proxy/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""));

            WebJsonResponse contentRet = null;

            String html  = "";
            String eHtml = "";
            String js    = null;

            String errorTemplate = "<span class=\"empty-results\">{0}</span>";

            //Verifica se está sendo selecionada uma role
            Int64 proxyId = 0;

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

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

            String         error    = "";
            ProxyGetResult retProxy = null;
            String         filter   = "";
            HashData       hashData = new HashData(this);


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

            if ((proxyId > 0) && (area.ToLower() != "search"))
            {
                try
                {
                    String rData = SafeTrend.Json.JSON.Serialize2(new
                    {
                        jsonrpc    = "1.0",
                        method     = "proxy.get",
                        parameters = new
                        {
                            proxyid = proxyId
                        },
                        id = 1
                    });
                    String jData = "";
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        jData = WebPageAPI.ExecuteLocal(database, this, rData);


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

                    retProxy = JSON.Deserialize <ProxyGetResult>(jData);
                    if (retProxy == null)
                    {
                        error = MessageResource.GetMessage("proxy_not_found");
                        //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true);
                    }
                    else if (retProxy.error != null)
                    {
                        error    = retProxy.error.data;
                        retProxy = null;
                    }
                    else if (retProxy.result == null || retProxy.result.info == null)
                    {
                        error    = MessageResource.GetMessage("proxy_not_found");
                        retProxy = null;
                    }
                    else
                    {
                        menu3.Name = retProxy.result.info.name;
                    }
                }
                catch (Exception ex)
                {
                    error = MessageResource.GetMessage("api_error");
                    Tools.Tool.notifyException(ex, this);
                    retProxy = null;
                    //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true);
                }
            }

            switch (area)
            {
            case "":
            case "search":
            case "content":
                if (newItem)
                {
                    html  = "<h3>Adição de proxy</h3>";
                    html += "<form id=\"form_add_proxy\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/proxy/action/add_proxy/\"><div class=\"no-tabs pb10\">";
                    html += "<div class=\"form-group\"><label>Nome</label><input id=\"proxy_name\" name=\"proxy_name\" placeholder=\"Digite o nome do proxy\" type=\"text\"\"></div>";
                    html += "<div class=\"clear-block\"></div></div>";
                    html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Adicionar</button>    <a href=\"" + ApplicationVirtualPath + "admin/proxy/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>";

                    contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                }
                else
                {
                    if (retProxy == null)
                    {
                        Int32   page     = 1;
                        Int32   pageSize = 20;
                        Boolean hasNext  = true;

                        Int32.TryParse(Request.Form["page"], out page);

                        if (page < 1)
                        {
                            page = 1;
                        }

                        String proxyTemplate = "<div id=\"proxy-list-{0}\" data-id=\"{0}\" data-name=\"{1}\" data-total=\"{2}\" class=\"app-list-item\">";
                        proxyTemplate += "<table>";
                        proxyTemplate += "   <tbody>";
                        proxyTemplate += "       <tr>";
                        proxyTemplate += "           <td class=\"col1\">";
                        proxyTemplate += "               <span id=\"total_{0}\" class=\"total \">{2}</span>";
                        proxyTemplate += "               <a href=\"" + ApplicationVirtualPath + "admin/resource/#proxy/{0}\">";
                        proxyTemplate += "                   <div class=\"app-btn a-btn\"><span class=\"a-btn-inner\">Ver recursos</span></div>";
                        proxyTemplate += "               </a>";
                        proxyTemplate += "           </td>";
                        proxyTemplate += "           <td class=\"col2\">";
                        proxyTemplate += "               <div class=\"title\"><span class=\"name field-editor\" id=\"proxy_name_{0}\" data-id=\"{0}\" data-function=\"iamadmin.editTextField('#proxy_name_{0}',null,proxyNameEdit);\">{1}</span><span class=\"date\">{3}</span><div class=\"clear-block\"></div></div>";
                        proxyTemplate += "               <div class=\"description\">";
                        proxyTemplate += "                   <div class=\"first\">{4}</div>";
                        proxyTemplate += "               </div>";
                        proxyTemplate += "               <div class=\"links\">";
                        proxyTemplate += "                   <div class=\"last\">{5}</div>";
                        proxyTemplate += "               </div>";
                        proxyTemplate += "           </td>";
                        proxyTemplate += "       </tr>";
                        proxyTemplate += "   </tbody>";
                        proxyTemplate += "</table></div>";

                        js += "proxyNameEdit = function(thisId, changedText) { iamadmin.changeName(thisId,changedText); };";

                        html += "<div id=\"box-container\" class=\"box-container\">";

                        String query = "";
                        try
                        {
                            String rData = "";

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

                            if (String.IsNullOrWhiteSpace(query) && !String.IsNullOrWhiteSpace(hashData.GetValue("query")))
                            {
                                query = hashData.GetValue("query");
                            }

                            if (String.IsNullOrWhiteSpace(query))
                            {
                                var tmpReq = new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "proxy.list",
                                    parameters = new
                                    {
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                };

                                rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                            }
                            else
                            {
                                var tmpReq = new
                                {
                                    jsonrpc    = "1.0",
                                    method     = "proxy.search",
                                    parameters = new
                                    {
                                        text      = query,
                                        page_size = pageSize,
                                        page      = page
                                    },
                                    id = 1
                                };

                                rData = SafeTrend.Json.JSON.Serialize2(tmpReq);
                            }

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


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

                            ProxyListResult ret2 = JSON.Deserialize <ProxyListResult>(jData);
                            if (ret2 == null)
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("proxy_not_found"));
                                hasNext = false;
                            }
                            else if (ret2.error != null)
                            {
#if DEBUG
                                eHtml += String.Format(errorTemplate, ret2.error.data + ret2.error.debug);
#else
                                eHtml += String.Format(errorTemplate, ret2.error.data);
#endif
                                hasNext = false;
                            }
                            else if (ret2.result == null || (ret2.result.Count == 0 && page == 1))
                            {
                                eHtml  += String.Format(errorTemplate, MessageResource.GetMessage("proxy_not_found"));
                                hasNext = false;
                            }
                            else
                            {
                                foreach (ProxyData proxy in ret2.result)
                                {
                                    String text = "";
                                    if (proxy.last_sync > 0)
                                    {
                                        DateTime lastSync = new DateTime(1970, 1, 1).AddSeconds(proxy.last_sync);
                                        TimeSpan ts       = DateTime.Now - lastSync;
                                        if (ts.TotalSeconds > 60)
                                        {
                                            text = "<span class=\"red-text\">Última conexão a " + MessageResource.FormatTs(ts) + " através do endereço " + proxy.last_sync_address + ". Versão: " + proxy.last_sync_version + "</span>";
                                        }
                                        else
                                        {
                                            text = "On-line através do endereço " + proxy.last_sync_address + ". Versão: " + proxy.last_sync_version + ". Pid: " + proxy.last_sync_pid;
                                        }
                                    }
                                    else
                                    {
                                        text = "<span class=\"red-text\">Nunca se conectou no servidor</span>";
                                    }

                                    String links = "";
                                    links += (proxy.resource_qty > 0 ? "" : "<a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/proxy/" + proxy.proxy_id + "/action/delete/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente o proxy '" + proxy.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Apagar</div></a>");
                                    links += "<a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/proxy/" + proxy.proxy_id + "/action/restart/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Reset\" confirm-text=\"Deseja reiniciar o proxy '" + proxy.name + "' no servidor remoto?\" ok=\"Reiniciar\" cancel=\"Cancelar\"><div class=\"ico icon-loop\">Reiniciar</div></a>";

                                    links += "<a href=\"" + ApplicationVirtualPath + "admin/proxy/" + proxy.proxy_id + "/direct/download/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-download-alt\">Download (instalador e configuração)</div></a>";

                                    html += String.Format(proxyTemplate, proxy.proxy_id, proxy.name, proxy.resource_qty, (proxy.create_date > 0 ? "Criado em " + MessageResource.FormatDate(new DateTime(1970, 1, 1).AddSeconds(proxy.create_date), true) : ""), text, links);
                                }

                                if (ret2.result.Count < pageSize)
                                {
                                    hasNext = false;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error"));
                        }

                        if (page == 1)
                        {
                            html += "</div>";

                            html += "<span class=\"empty-results content-loading proxy-list-loader hide\"></span>";

                            contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html));
                        }
                        else
                        {
                            contentRet = new WebJsonResponse("#content-wrapper #box-container", (eHtml != "" ? eHtml : html), true);
                        }

                        contentRet.js = js + "$( document ).unbind('end_of_scroll');";

                        if (hasNext)
                        {
                            contentRet.js += "$( document ).bind( 'end_of_scroll.loader_role', function() { $( document ).unbind('end_of_scroll.loader_role'); $('.proxy-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'" + (!String.IsNullOrWhiteSpace(query) ? query : "") + "' }, function(){ $('.proxy-list-loader').addClass('hide'); } ); });";
                        }
                    }
                    else    //Esta sendo selecionado o proxy
                    {
                        if (error != "")
                        {
                            contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error));
                        }
                        else
                        {
                        }
                    }
                }

                break;

            case "sidebar":
                if (menu1 != null)
                {
                    html += "<div class=\"sep\"><div class=\"section-nav-header\">";
                    html += "    <div class=\"crumbs\">";
                    html += "        <div class=\"subject subject-color\">";
                    html += "            <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>";
                    html += "        </div>";
                    if (menu2 != null)
                    {
                        html += "        <div class=\"topic topic-color\">";
                        html += "            <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>";
                        html += "        </div>";
                    }
                    html += "    </div>";
                    if (menu3 != null)
                    {
                        html += "    <div class=\"crumbs tutorial-title\">";
                        html += "        <h2 class=\"title tutorial-color\">" + menu3.Name + "</h2>";
                        html += "    </div>";
                    }
                    html += "</div></div>";
                }

                if (!newItem)
                {
                    html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/proxy/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Novo proxy</button></div>";
                }

                contentRet = new WebJsonResponse("#main aside", html);
                break;

            case "mobilebar":
                break;


            case "buttonbox":
                break;
            }

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

                Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON()));
            }
        }
Exemple #28
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()));
            }
        }
Exemple #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));
            }
        }
Exemple #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!EnterpriseIdentify.Identify(this.Page)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                return;
            }

            login = LoginUser.LogedUser(this.Page);

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

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

            if (login != null)
            {
                try
                {
                    using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                        using (IAMRBAC rbac = new IAMRBAC())
                            isAdmin = rbac.HasAdminConsole(database, login.Id, enterpriseId);
                }
                catch { }
            }


            if (!isAdmin)
            {
                Response.Redirect(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath + "autoservice/");
            }

            //Identifica a página atual com objetivo de mostrar o ícone como selecionado no rodapé
            String scriptName             = Request.Params["SCRIPT_NAME"].ToLower();
            String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString();

            if (ApplicationVirtualPath == "/")
            {
                ApplicationVirtualPath = "";
            }

            if (ApplicationVirtualPath != "")
            {
                scriptName = scriptName.Replace(ApplicationVirtualPath, "");
            }


            l1         = l2 = l3 = false;
            scriptName = scriptName.Trim("/ ".ToCharArray());
            switch (scriptName.ToLower())
            {
            case "admin":
                l1 = true;
                break;
            }
        }