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



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


                if (isMail)
                {
                    Tools.Tool.sendEmail("Password recover code", sendTo, "Code: " + tmp.Rows[0]["recovery_code"].ToString(), false);
                }
            }
            return(true);
        }
        catch (Exception ex) {
            error = ex.Message;
            return(false);
        }
    }
Exemplo n.º 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!EnterpriseIdentify.Identify(this)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                return;
            }

            String html = "";

            html += "<div id=\"recover_container\"><form id=\"serviceRecover\" name=\"serviceRecover\" method=\"post\" action=\"/consoleapi/recover1/\">";
            html += "<div class=\"login_form\">";
            html += "    <input type=\"hidden\" name=\"do\" value=\"recover1\" />";
            html += "    <ul>";
            html += "        <li>";
            html += "            <p style=\"width:270px;padding:0 0 20px 0;color:#000;\">" + MessageResource.GetMessage("login_recover_message") + "</p>";
            html += "        </li>";
            html += "        <li>";
            html += "            <span class=\"inputWrap\">";
            //html += "			    <span id=\"ph_userLogin\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">" + MessageResource.GetMessage("login_user_name") + "</span>";
            html += "			    <input type=\"text\" id=\"userLogin\" tabindex=\"1\" name=\"userLogin\" value=\"\" style=\"\"  placeholder=\""+ MessageResource.GetMessage("login_user_name") + "\" onfocus=\"$('#userLogin').addClass('focus');\" onblur=\"$('#userLogin').removeClass('focus');\" />";
            html += "			    <span id=\"ph_userLoginIcon\" onclick=\"$('#userLogin').focus();\"></span>";
            html += "            </span>";
            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("login_recover_btn_recover") + "</button>";
            html += "        </li>";
            html += "    </ul>     ";
            html += "</div>";
            html += "</form>";
            html += "</div>";

            holderContent.Controls.Add(new LiteralControl(html));
        }
Exemplo n.º 3
0
        public override string ToString()
        {
            String ret = "";

            switch (Type)
            {
            case TimeAccessType.Never:
                ret += MessageResource.GetMessage("never");
                break;

            case TimeAccessType.Always:
                ret += MessageResource.GetMessage("always");
                break;

            case TimeAccessType.SpecificTime:
                CultureInfo ci = Thread.CurrentThread.CurrentCulture;

                ret += StartTime.ToString("HH:mm") + " - " + EndTime.ToString("HH:mm") + " " + MessageResource.GetMessage("in") + " ";
                List <String> week = new List <string>();
                foreach (DayOfWeek w in WeekDay)
                {
                    week.Add(ci.DateTimeFormat.GetDayName(w));
                }
                ret += String.Join(", ", week);
                break;

            default:
                ret += MessageResource.GetMessage("not_defined");
                break;
            }

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

            try
            {
                String p = Tools.Tool.TrataInjection(Request["password"]);

                PasswordStrength pwdcheck = new PasswordStrength();
                pwdcheck.SetPassword(p);

                Color cor = pwdcheck.GetStrengthColor();

                ret = new WebJsonResponse("#passwordStrength", "<label>" + MessageResource.GetMessage("password_strength") + "</label><div class=\"form-group-content\"><span>" + pwdcheck.GetPasswordStrength() + "</span><div class=\"bar\" style=\"background: rgb(" + cor.R + "," + cor.G + "," + cor.B + ")\"></div></div>");
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex);
                throw ex;
            }


            if (ret != null)
            {
                ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Exemplo n.º 5
0
    static public void NewCode(Page page, Int64 entityId, out String error)
    {
        error = "";
        try
        {
            if (entityId == 0)
            {
                return;
            }

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

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

                    db.AddUserLog(LogKey.User_NewRecoveryCode, null, "AutoService", UserLogLevel.Info, 0, 0, 0, 0, 0, entityId, 0, MessageResource.GetMessage("new_recovery_code") + " (" + code + ")", "{ \"ipaddr\":\"" + Tools.Tool.GetIPAddress() + "\"} ");
                }
        }
        catch (Exception ex)
        {
            error = MessageResource.GetMessage("internal_error");
            Tools.Tool.notifyException(ex, page);
            return;
        }
        finally
        {
        }
    }
Exemplo n.º 6
0
        public static LoginResult Grant(String service, HttpCookie cookie)
        {
            if ((cookie == null) || (String.IsNullOrEmpty(cookie.Value)))
            {
                return(new LoginResult(false, MessageResource.GetMessage("invalid_ticket")));
            }

            return(Grant(service, cookie.Value, false));
        }
Exemplo n.º 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;


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

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

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

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

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


            if (ret != null)
            {
                Retorno.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Exemplo n.º 8
0
 public override string ToString()
 {
     if (this.data_type == Filters.DataType.DateTime)
     {
         return(field_name + " " + MessageResource.GetMessage(condition_type.ToString().ToLower(), condition_type.ToString()).ToLower() + " " + MessageResource.FormatDate(((DateTime)data), false));
     }
     else
     {
         return(field_name + " " + MessageResource.GetMessage(condition_type.ToString().ToLower(), condition_type.ToString()).ToLower() + " " + data.ToString());
     }
 }
Exemplo n.º 9
0
 /// <summary>
 /// Returns a textual description of the stregth of the password
 /// </summary>
 /// <returns></returns>
 public string GetPasswordStrength()
 {
     if (dtDetails != null)
     {
         return((String)dtDetails.Rows[0][3]);
     }
     else
     {
         String unk = "";
         try
         {
             unk = MessageResource.GetMessage("unknow");
         }
         catch { unk = ""; }
         return(unk == "" || unk == null ? "Unknown" : unk);
     }
 }
Exemplo n.º 10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse ret = null;



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

                String err = "";
                if (!EnterpriseIdentify.Identify(this, false, out err)) //Se houver falha na identificação da empresa finaliza a resposta
                {
                    ret = new WebJsonResponse("", err, 3000, true);
                }
                else if (login == null)
                {
                    ret = new WebJsonResponse("", MessageResource.GetMessage("expired_session"), 3000, true, "/login/");
                }
                else
                {
                    String container = Request.Form["container"];
                    String field     = Request.Form["field"];
                    String id        = field + Guid.NewGuid().ToString();

                    String html    = "";
                    String content = "<div >{0}</div>";

                    html = "teste ok - " + field;

                    ret = new WebJsonResponse(container, String.Format(content, html), true);
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex);
                throw ex;
            }


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

    static public Int64 FindUser(Page page, String username, out String error)
    {
        try
        {
            if ((username == null) || (username.Trim() == ""))
            {
                error = MessageResource.GetMessage("valid_username");
                return(0);
            }
            using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
            {
                DataTable tmp = db.Select(String.Format("select id, locked from vw_entity_logins with(nolock) where (login = '******' or value = '{0}') group by id, locked", Tools.Tool.TrataInjection(username)));
                if ((tmp == null) || (tmp.Rows.Count == 0))
                {
                    error = MessageResource.GetMessage("valid_username");
                    return(0);
                }
                else if (tmp.Rows.Count > 1)
                {
                    error = MessageResource.GetMessage("ambiguous_id");
                    return(0);
                }
                else if ((Boolean)tmp.Rows[0]["locked"])
                {
                    error = MessageResource.GetMessage("user_locked");
                    return(0);
                }
                else
                {
                    error = "";
                    return((Int64)tmp.Rows[0]["id"]);
                }
            }
        }
        catch (Exception ex)
        {
            error = MessageResource.GetMessage("internal_error");
            Tools.Tool.notifyException(ex, page);
            return(0);
        }
        finally
        {
        }
    }
Exemplo n.º 12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!EnterpriseIdentify.Identify(this)) //Se houver falha na identificação da empresa finaliza a resposta
            {
                return;
            }

            LoginData login = LoginUser.LogedUser(this);

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

            String html = "";

            html += "<div class=\"login_form\">";
            html += "    <ul>";
            html += "        <li>";
            html += "            <span class=\"inputWrap\">";
            //html += "				<span id=\"ph_userLogin\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">" + MessageResource.GetMessage("login_user_name") + "</span>";
            html += "				<input type=\"text\" id=\"userLogin\" tabindex=\"1\" name=\"userLogin\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("login_user_name") + "\" onfocus=\"$('#userLogin').addClass('focus');\" onblur=\"$('#userLogin').removeClass('focus');\" />";
            html += "				<span id=\"ph_userLoginIcon\" onclick=\"$('#userLogin').focus();\"></span>";
            html += "            </span>";
            html += "        </li>";
            html += "        <li>";
            html += "            <span class=\"inputWrap\">";
            //html += "				<span id=\"ph_password\" class=\"noSel\" style=\"position: absolute; z-index: 1; top: 13px; left: 53px; color: rgb(204, 204, 204); display: block;\">" + MessageResource.GetMessage("login_password") + "</span>";
            html += "				<input type=\"password\" id=\"password\" tabindex=\"2\" name=\"password\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("login_password") + "\" onfocus=\"$('#password').addClass('focus');\" onblur=\"$('#password').removeClass('focus');\" />";
            html += "				<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
            html += "			</span>";
            html += "        </li>";
            //html += "        <li><div class=\"error-box\">fdsafdas</div>";
            html += "        </li>";
            html += "        <li>";
            html += "            <span class=\"forgot\"> <a href=\"/recover/\">" + MessageResource.GetMessage("login_forgot") + "</a> </span>";
            html += "            <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("login_log") + "</button>";
            html += "        </li>";
            html += "    </ul>     ";
            html += "</div>";
            holderContent.Controls.Add(new LiteralControl(html));
        }
Exemplo n.º 13
0
        public override string ToString()
        {
            String ret = "";

            FilterSelector lastSelector = FilterSelector.AND;

            if (filter_rules != null)
            {
                foreach (FilterCondition f in filter_rules)
                {
                    if (ret != "")
                    {
                        ret += " " + MessageResource.GetMessage(lastSelector.ToString().ToLower(), lastSelector.ToString()).ToLower() + " ";
                    }
                    ret         += f.ToString();
                    lastSelector = f.Selector;
                }
            }

            return((ret != "" ? "(" : "") + ret + (ret != "" ? ")" : ""));
        }
Exemplo n.º 14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Response.ContentType     = "application/x-javascript; charset=UTF-8";
            Page.Response.ContentEncoding = Encoding.UTF8;

            StringBuilder text = new StringBuilder();

            text.AppendLine("/*! SafeId v1.0.0 | (c) 2013 SafeTrend.com.br.");
            text.AppendLine("//@ Variaveis de ambiente Javascript");
            text.AppendLine("//@ Variaveis necessárias para que os scripts identifiquem o root da aplicação");
            text.AppendLine("*/");
            text.AppendLine("");
            text.AppendLine("var ApplicationVirtualPath = '" + HostingEnvironment.ApplicationVirtualPath + "'");
            text.AppendLine("var LoadingText = '" + MessageResource.GetMessage("loading_mobile") + "'");

            Byte[] bRet = Encoding.UTF8.GetBytes(text.ToString());
            Page.Response.Status     = "200 OK";
            Page.Response.StatusCode = 200;
            Page.Response.OutputStream.Write(bRet, 0, bRet.Length);
            Page.Response.OutputStream.Flush();
        }
Exemplo n.º 15
0
        public override string ToString()
        {
            String ret = "";

            FilterSelector lastSelector = FilterSelector.OR;

            if (filter_groups != null)
            {
                foreach (FilterGroup g in filter_groups)
                {
                    if (ret != "")
                    {
                        ret += " " + MessageResource.GetMessage(lastSelector.ToString().ToLower(), lastSelector.ToString()).ToLower() + " ";
                    }

                    ret         += g.ToString();
                    lastSelector = g.Selector;
                }
            }

            return(ret);
        }
Exemplo n.º 16
0
        public override string ToString()
        {
            try
            {
                CultureInfo ci   = Thread.CurrentThread.CurrentCulture;
                String      ret  = "";
                DateTime    date = DateTime.ParseExact(startdate, "yyyy-MM-dd", null);

                ret += MessageResource.GetMessage(Trigger.ToString().ToLower()) + " ";
                switch (Trigger)
                {
                case ScheduleTtiggers.Annually:
                    string tmp     = date.ToString("d", ci).Replace(date.ToString("yyyy", ci), string.Empty);
                    char   last    = tmp[tmp.Length - 1];
                    char[] trimmer = char.IsDigit(last) ? new char[] { tmp[0] } : new char[] { last };
                    ret += tmp.Trim(trimmer) + " ";
                    break;

                case ScheduleTtiggers.Monthly:
                    ret += MessageResource.GetMessage("day") + " " + date.Day + " ";
                    break;

                case ScheduleTtiggers.Weekly:
                    ret += ci.DateTimeFormat.GetDayName(date.DayOfWeek).ToLower() + " ";
                    break;

                default:
                    break;
                }
                ret += " " + MessageResource.GetMessage("in") + " ";
                ret += triggertime + (Repeat > 0 ? ", " + MessageResource.GetMessage("after_triggered") + " " + repeat + " " + MessageResource.GetMessage("minute") + "(s)" : "");

                return(ret);
            }
            catch
            {
                return(Trigger.ToString() + " in " + triggertime + (Repeat > 0 ? ", after triggered repeat every " + repeat + " minute(s)" : ""));
            }
        }
Exemplo n.º 17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            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=\"" + Session["ApplicationVirtualPath"] + "autoservice/\">" + MessageResource.GetMessage("return_default") + "</a></span>";
            html += "    </li>";
            html += "</ul>     ";

            html += "</div>";

            holderContent.Controls.Add(new LiteralControl(html));
        }
Exemplo n.º 18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            html += "<div id=\"recover_container\"><form id=\"serviceRecover\" name=\"serviceRecover\" method=\"post\"><div class=\"login_form\">";

            if (Session["user_info"] == null || !(Session["user_info"] is CASUserInfo))
            {
                //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
            {
                Session["userCode"] = null;

                CASUserInfo userInfo = (CASUserInfo)Session["user_info"];

                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=\"" + Session["ApplicationVirtualPath"] + "cas/login/?service=" + HttpUtility.UrlEncode(userInfo.Service.AbsoluteUri) + "\">" + MessageResource.GetMessage("return_default") + "</a></span>";
                html += "    </li>";
                html += "</ul>     ";
            }

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

            holderContent.Controls.Add(new LiteralControl(html));
        }
Exemplo n.º 19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            html += "<form id=\"serviceLogin\" name=\"serviceLogin\" method=\"post\" action=\"/cas/login/?" + Request.QueryString + "\"><div class=\"login_form\">";


            Uri svc = null;

            try
            {
                svc = new Uri(Request.QueryString["service"]);
            }
            catch { }

            using (DbBase db = DbBase.InstanceFromConfig(ConfigurationManager.ConnectionStrings["CASDatabase"]))
            {
                CASConnectorBase connector = CASUtils.GetService(db, this, null);

                if (connector == null)//Nunca deve ser nulo, em caso de não encontrado deve retornar um Emptylugin
                {
                    //Serviço não informado ou não encontrado
                    html += "    <ul>";
                    html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("service_invalid_uri") + "</div>";
                    html += "    </ul>";
                }
                else
                {
                    String ticket = (!String.IsNullOrEmpty(Request.QueryString["ticket"]) ? Request.QueryString["ticket"].ToString() : "");
                    connector.DestroyTicket(ticket, null);

                    HttpCookie tgc = Request.Cookies["TGC-SafeID"];
                    if (tgc != null)
                    {
                        connector.DestroyTicket(tgc);
                    }

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

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

                        cookie.Expires = DateTime.Now.AddDays(-30);

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

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

                        cookie.Expires = DateTime.Now.AddDays(-30);

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


                    error = MessageResource.GetMessage("logout_text");
                    String url = (!String.IsNullOrEmpty(Request.QueryString["url"]) ? Request.QueryString["url"].ToString() : "");
                    try
                    {
                        Uri tmp = new Uri(url);
                        error = "<a href=\"" + tmp.AbsoluteUri + "\">" + String.Format(MessageResource.GetMessage("logout_text_url"), tmp.AbsoluteUri) + "</a>";
                    }
                    catch { }

                    if (String.IsNullOrEmpty(url) && svc != null)
                    {
                        Response.Redirect(svc.AbsoluteUri, false);
                        return;
                    }

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

                html += "</div></form>";
            }
            holderContent.Controls.Add(new LiteralControl(html));
        }
Exemplo n.º 20
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()));
            }
        }
Exemplo n.º 21
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()));
            }
        }
Exemplo n.º 22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

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

            LoginData login = LoginUser.LogedUser(this);

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

                String err = "";


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

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

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

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

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

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

                            //Resgata todos os plugind possíveis


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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


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

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


            if (ret != null)
            {
                ReturnHolder.Controls.Add(new LiteralControl(ret.ToJSON()));
            }
        }
Exemplo n.º 25
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()));
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Método privado para processamento do método 'user.resetpassword'
        /// </summary>
        /// <param name="sqlConnection">Conexão com o banco de dados MS-SQL</param>
        /// <param name="parameters">Dicionário (String, Object) contendo todos os parâmetros necessários</param>
        private Dictionary <String, Object> change(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            Dictionary <String, Object> result = new Dictionary <String, Object>();

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

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

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

            Int64 enterpriseid = 0;

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


            DbParameterCollection par = new DbParameterCollection();

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

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

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

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

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

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

            foreach (String key in parameters.Keys)
            {
                switch (key.ToLower())
                {
                case "name":
                    String name = parameters["name"].ToString();
                    if (!String.IsNullOrWhiteSpace(name))
                    {
                        par.Add("@name", typeof(String)).Value = name;
                        if (updateFields != "")
                        {
                            updateFields += ", ";
                        }
                        updateFields += "name = @name";
                        update        = true;
                    }
                    else
                    {
                        Error(ErrorType.InvalidRequest, "Parameter name is empty.", "", null);
                        return(null);
                    }
                    break;

                case "auth_plugin":

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

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


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

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

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


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

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

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

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

                        pluginUri = plugin.GetPluginId();

                        updateAuthPars = true;

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

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

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

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

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

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

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

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

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


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

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

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

            //Atualiza a busca com os dados atualizados
            return(get(database, parameters));
        }
Exemplo n.º 27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            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
            {
                if (Request.HttpMethod == "POST")
                {
                    try
                    {
                        Int64 userId = LoginUser.FindUser(this, Request["username"], out error);
                        if (userId > 0)
                        {
                            Session["user_info"] = userId;

                            Response.Redirect(Session["ApplicationVirtualPath"] + "login2/recover/step1/", false);
                            return;
                        }

                        /*else if ((user.Emails == null) || (user.Emails.Count == 0))
                         * {
                         *  error = MessageResource.GetMessage("user_email_list");
                         * }
                         * else
                         * {
                         *  error = user.ErrorText;
                         * }*/
                    }
                    catch (Exception ex)
                    {
                        Tools.Tool.notifyException(ex);
                        error = MessageResource.GetMessage("internal_error");
                    }
                }


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

                html += "    <ul>";
                html += "        <li>";
                html += "            <p style=\"width:270px;padding:0 0 20px 0;color:#000;\">" + MessageResource.GetMessage("login_recover_message") + "</p>";
                html += "        </li>";
                html += "        <li>";
                html += "            <span class=\"inputWrap\">";
                html += "				<input type=\"text\" id=\"username\" tabindex=\"1\" name=\"username\" value=\""+ Request["username"] + "\" style=\"\" placeholder=\"" + MessageResource.GetMessage("login_user_name") + "\" onfocus=\"$('#username').addClass('focus');\" onblur=\"$('#username').removeClass('focus');\" />";
                html += "				<span id=\"ph_userLoginIcon\" onclick=\"$('#username').focus();\"></span>";
                html += "            </span>";
                html += "        </li>";

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

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

                html += "</div></form>";
                holderContent.Controls.Add(new LiteralControl(html));
            }
        }
Exemplo n.º 28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Boolean renew   = (!String.IsNullOrEmpty(Request["renew"]) && (Request["renew"].ToString().ToLower() == "true"));
            Boolean gateway = (!String.IsNullOrEmpty(Request["gateway"]) && (Request["gateway"].ToString().ToLower() == "true"));
            Boolean warn    = (!String.IsNullOrEmpty(Request["warn"]) && (Request["warn"].ToString().ToLower() == "true"));

            if (renew || warn)
            {
                gateway = false;
            }

            if (warn)
            {
                renew = true;
            }

            String html  = "";
            String error = "";

            html += "<form id=\"serviceLogin\" name=\"serviceLogin\" method=\"post\" action=\"/cas/login/?" + Request.QueryString + "\"><div class=\"login_form\">";

            try
            {
                Session.Remove("cas_ticket");
            }
            catch { }


            Uri svc = null;

            try
            {
                svc = new Uri(Request.QueryString["service"]);
            }
            catch { }

            using (DbBase db = DbBase.InstanceFromConfig(ConfigurationManager.ConnectionStrings["CASDatabase"]))
            {
                CASConnectorBase connector = CASUtils.GetService(db, this, svc);

                if ((connector == null) || (connector is EmptyPlugin))
                {
                    //Serviço não informado ou não encontrado
                    html += "    <ul>";
                    html += "        <li><div class=\"error-box\">" + MessageResource.GetMessage("service_invalid_uri") + "</div>";
                    html += "    </ul>";
                }
                else
                {
                    if (Request.HttpMethod == "GET")
                    {
                        //Serviço encontrado

                        //verifica se há cookie com token
                        HttpCookie tgc = Request.Cookies["TGC-SafeID"];
                        if (tgc != null)
                        {
                            //Verifica autenticação através do cookie
                            if (connector.Grant(tgc, renew, warn).Success)
                            {
                                Redirect(tgc.Value);//Autenticado redireciona
                                return;
                            }
                        }
                        else if (gateway)//é Gateway, ou seja não mostra opção do usuário digitar a senha
                        {
                            Redirect("");
                            return;
                        }
                    }
                    else
                    {
                        //Valida usuário e senha
                        try
                        {
                            if (String.IsNullOrEmpty(Request["username"]) || String.IsNullOrEmpty(Request["password"]))
                            {
                                error = MessageResource.GetMessage("valid_username_pwd");
                            }
                            else
                            {
                                CASTicketResult casTicket = connector.Grant(Request["username"], Request["password"]);
                                CASUtils.ClearCookie(Page);
                                if ((casTicket.Success) && (casTicket.ChangePasswordNextLogon))
                                {
                                    //Cria a sessão com as informações necessárias e redireciona
                                    Session["cas_ticket"] = casTicket;
                                    Response.Redirect(Session["ApplicationVirtualPath"] + "cas/changepassword/", false);
                                    return;
                                }
                                else if (casTicket.Success)
                                {
                                    connector.SaveTicket(casTicket);//Salva o token recebido

                                    //Salva o token no cookie
                                    CASUtils.AddCoockie(this, casTicket);

                                    Redirect(casTicket.GrantTicket);//Autenticação OK redireciona
                                    return;
                                }
                                else
                                {
                                    error = casTicket.ErrorText;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                            Tools.Tool.notifyException(ex);
                            error = MessageResource.GetMessage("internal_error");
                        }
                    }

                    html += "    <ul>";
                    html += "        <li>";
                    html += "            <span class=\"inputWrap\">";
                    html += "				<input type=\"text\" id=\"username\" tabindex=\"1\" name=\"username\" value=\""+ Request["username"] + "\" style=\"\" placeholder=\"" + MessageResource.GetMessage("login_user_name") + "\" onfocus=\"$('#username').addClass('focus');\" onblur=\"$('#username').removeClass('focus');\" />";
                    html += "				<span id=\"ph_usernameIcon\" onclick=\"$('#username').focus();\"></span>";
                    html += "            </span>";
                    html += "        </li>";
                    html += "        <li>";
                    html += "            <span class=\"inputWrap\">";
                    html += "				<input type=\"password\" id=\"password\" tabindex=\"2\" name=\"password\" value=\"\" style=\"\" placeholder=\""+ MessageResource.GetMessage("login_password") + "\" onfocus=\"$('#password').addClass('focus');\" onblur=\"$('#password').removeClass('focus');\" />";
                    html += "				<span id=\"ph_passwordIcon\" onclick=\"$('#password').focus();\"></span>";
                    html += "			</span>";
                    html += "        </li>";
                    if (error != "")
                    {
                        html += "        <li><div class=\"error-box\">" + error + "</div>";
                    }
                    html += "        </li>";
                    html += "        <li>";
                    html += "            <span class=\"forgot\"> <a href=\"" + Session["ApplicationVirtualPath"] + "cas/recover/?service=" + HttpUtility.UrlEncode(connector.Service.AbsoluteUri) + "\">" + MessageResource.GetMessage("login_forgot") + "</a> </span>";
                    html += "            <button tabindex=\"4\" id=\"submitBtn\" class=\"action button floatright\">" + MessageResource.GetMessage("login_log") + "</button>";
                    html += "        </li>";
                    html += "    </ul>     ";
                }

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

            holderContent.Controls.Add(new LiteralControl(html));
        }
Exemplo n.º 29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String html  = "";
            String error = "";

            LoginData login = LoginUser.LogedUser(this);

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

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

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

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

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

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

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

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

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

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

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

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


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

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