Example #1
0
        public static EnterpriseData EnterpriseByService(Page page, String service)
        {
            if (String.IsNullOrEmpty(service))
            {
                return(null);
            }

            DbParameterCollection par = null;

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

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

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

                        data.Host     = dt.Rows[0]["fqdn"].ToString().ToLower();
                        data.Name     = dt.Rows[0]["name"].ToString();
                        data.Language = dt.Rows[0]["language"].ToString();
                        data.Id       = (Int64)dt.Rows[0]["id"];

                        return(data);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
            finally
            {
                par = null;
            }
        }
        public Customer360Controller(
            HomeDeliveryRepository homeDeliveryRepository,
            LoyaltyRepository loyaltyRepository,
            LoyaltyCsvExportService loyaltyCsvExportService,
            LoyaltyCsvImportService loyaltyCsvImportService,
            ILogger <Customer360Controller> logger,
            EnterpriseData enterpriseData,
            OnlineStoreRepository onlineStoreRepository)
        {
            _homeDeliveryRepository  = homeDeliveryRepository;
            _loyaltyRepository       = loyaltyRepository;
            _loyaltyCsvExportService = loyaltyCsvExportService;
            _loyaltyCsvImportService = loyaltyCsvImportService;
            _logger                = logger;
            _enterpriseData        = enterpriseData;
            _onlineStoreRepository = onlineStoreRepository;

            // make sure all the appropriate tables/databases exist
            _enterpriseData.EnsureSchemas();
        }
Example #3
0
        public String Plugin()
        {
            String pluginId = "";

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

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

            FlowData flowData = new FlowData();

            DataTable dtPlugins = null;

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

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

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

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

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

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

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

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

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

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

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

                    Node roleNode = null;

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

            return(flowData.ToJson());
        }
Example #5
0
        public String UserFlow()
        {
            String userId = "";

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

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

            FlowData flowData = new FlowData();

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

            return(flowData.ToJson());
        }
Example #6
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()));
            }
        }
Example #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            WebJsonResponse contentRet = null;

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

            String action = "";

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

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

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

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

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

                    AuthBase plugin = null;
                    try
                    {
                        plugin = AuthBase.GetPlugin(new Uri(auth_plugin));
                        if (plugin == null)
                        {
                            throw new Exception();
                        }
                    }
                    catch {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("invalid_auth_service"), 3000, true);
                        break;
                    }

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

                    AuthConfigFields[] fields = plugin.GetConfigFields();
                    if (fields.Length > 0)
                    {
                        WebJsonResponse err = null;

                        foreach (AuthConfigFields f in fields)
                        {
                            String value = Request.Form["f_" + f.Key];
                            if (!String.IsNullOrEmpty(value))
                            {
                                pgValues.Add(f.Key, value);
                            }

                            if (f.Required && !pgValues.ContainsKey(f.Key))
                            {
                                err = new WebJsonResponse("", MessageResource.GetMessage("required_field") + " " + f.Name, 3000, true);
                                break;
                            }
                        }

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

                    List <String> hosts = new List <String>();
                    foreach (String key in Request.Form.Keys)
                    {
                        if (key.ToLower().IndexOf("host_") == 0)
                        {
                            String[] ht = Request.Form[key].ToString().Split(",".ToCharArray());
                            foreach (String host in ht)
                            {
                                if (!String.IsNullOrWhiteSpace(host))
                                {
                                    hosts.Add(host);
                                }
                            }
                        }
                    }


                    var reqD = new
                    {
                        jsonrpc    = "1.0",
                        method     = "enterprise.change",
                        parameters = new
                        {
                            enterpriseid   = ent.Id,
                            name           = name,
                            auth_plugin    = auth_plugin,
                            fqdn_alias     = hosts.ToArray(),
                            auth_paramters = pgValues
                        },
                        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("");
                    }

                    RoleGetResult retD = JSON.Deserialize <RoleGetResult>(jData);
                    if (retD == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("enterprise_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("enterprise_not_found"), 3000, true);
                    }
                    else if (retD.result == null || retD.result.info == null)
                    {
                        contentRet = new WebJsonResponse("", MessageResource.GetMessage("enterprise_not_found"), 3000, true);
                    }
                    else
                    {
                        contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/enterprise/");
                    }
                    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()));
            }
        }
        private static async Task Main()
        {
            Console.CancelKeyPress += (s, e) => { Environment.Exit(-1); };

            // Keeper SDK needs a storage to save configuration
            // such as: last login name, device token, etc
            var configuration = new JsonConfigurationStorage("test.json");


            var prompt = "Enter Email Address: ";

            if (!string.IsNullOrEmpty(configuration.LastLogin))
            {
                Console.WriteLine($"Default Email Address: {configuration.LastLogin}");
            }

            Console.Write(prompt);
            var username = Console.ReadLine();

            if (string.IsNullOrEmpty(username))
            {
                if (string.IsNullOrEmpty(configuration.LastLogin))
                {
                    Console.WriteLine("Bye.");
                    return;
                }

                username = configuration.LastLogin;
            }

            var inReadLine = false;

            var authFlow = new AuthSync(configuration);

            authFlow.UiCallback = new AuthSyncCallback(() =>
            {
                if (!inReadLine)
                {
                    return;
                }
                if (authFlow.Step.State == AuthState.Connected || authFlow.Step.State == AuthState.Error)
                {
                    Console.WriteLine("Press <Enter>");
                }
                else
                {
                    PrintStepHelp(authFlow.Step);
                    PrintStepPrompt(authFlow.Step);
                }
            },
                                                       Console.WriteLine);

            // Login to Keeper
            Console.WriteLine("Logging in...");

            var lastState = authFlow.Step.State;
            await authFlow.Login(username);

            while (!authFlow.IsCompleted)
            {
                if (authFlow.Step.State != lastState)
                {
                    PrintStepHelp(authFlow.Step);
                }

                lastState = authFlow.Step.State;
                PrintStepPrompt(authFlow.Step);
                inReadLine = true;
                var cmd = ReadInput();
                inReadLine = false;
                if (string.IsNullOrEmpty(cmd))
                {
                    continue;
                }

                try
                {
                    await ProcessCommand(authFlow, cmd);
                }
                catch (KeeperAuthFailed)
                {
                    Console.WriteLine("Invalid username or password");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            if (authFlow.Step is ErrorStep es)
            {
                Console.WriteLine(es.Message);
            }
            if (!authFlow.IsAuthenticated())
            {
                return;
            }

            var auth  = authFlow;
            var vault = new VaultOnline(auth);

            Console.WriteLine("\nRetrieving records...");
            await vault.SyncDown();

            Console.WriteLine($"Hello {username}!");
            Console.WriteLine($"Vault has {vault.RecordCount} records.");

            // Find record with title "Google"
            var search = vault.Records.FirstOrDefault(x => string.Compare(x.Title, "Google", StringComparison.InvariantCultureIgnoreCase) == 0);

            // Create a record if it does not exist.
            if (search == null)
            {
                search = new PasswordRecord
                {
                    Title    = "Google",
                    Login    = "******",
                    Password = "******",
                    Link     = "https://google.com",
                    Notes    = "Stores google credentials"
                };
                search = await vault.CreateRecord(search);
            }

            var nsd3 = vault.LoadNonSharedData <NonSharedData3>(search.Uid);

            nsd3.Data1 = "1";
            nsd3.Data3 = "3";
            await vault.StoreNonSharedData(search.Uid, nsd3);

            var nsd2 = vault.LoadNonSharedData <NonSharedData2>(search.Uid);

            nsd2.Data2 = "2";
            await vault.StoreNonSharedData(search.Uid, nsd2);

            // Update record.
            search.SetCustomField("Security Token", "11111111");
            search = await vault.UpdateRecord(search);

            // find file attachment.
            var attachment = search.Attachments
                             .FirstOrDefault(x => string.Compare(x.Title, "google", StringComparison.InvariantCultureIgnoreCase) == 0);

            if (attachment == null)
            {
                // Upload local file "google.txt".
                // var uploadTask = new FileAttachmentUploadTask("google.txt")
                var fileContent = Encoding.UTF8.GetBytes("Google");
                using (var stream = new MemoryStream(fileContent))
                {
                    var uploadTask = new AttachmentUploadTask(stream)
                    {
                        Title    = "Google",
                        Name     = "google.txt",
                        MimeType = "text/plain"
                    };
                    await vault.UploadAttachment(search, uploadTask);

                    await vault.UpdateRecord(search, false);
                }
            }
            else
            {
                // Download attachment into the stream
                // The stream could be a local file "google.txt"
                // using (var stream = File.OpenWrite("google.txt"))
                using (var stream = new MemoryStream())
                {
                    await vault.DownloadAttachment(search, attachment.Id, stream);
                }

                // Delete attachment. Remove it from the record
                search.Attachments.Remove(attachment);
                await vault.UpdateRecord(search, false);
            }

            // Find shared folder with name "Google".
            var sharedFolder = vault.SharedFolders
                               .FirstOrDefault(x => string.Compare(x.Name, "Google", StringComparison.InvariantCultureIgnoreCase) == 0);

            if (sharedFolder == null)
            {
                // Create shared folder.
                var folder = await vault.CreateFolder("Google",
                                                      null,
                                                      new SharedFolderOptions
                {
                    ManageRecords = true,
                    ManageUsers   = false,
                    CanEdit       = false,
                    CanShare      = false,
                });

                vault.TryGetSharedFolder(folder.FolderUid, out sharedFolder);
            }

            // Add user to shared folder.
            try
            {
                await vault.PutUserToSharedFolder(sharedFolder.Uid,
                                                  "*****@*****.**",
                                                  UserType.User,
                                                  new SharedFolderUserOptions
                {
                    ManageRecords = false,
                    ManageUsers   = false,
                });
            }
            catch (Exception e)
            {
                Console.WriteLine($"Add user to Shared Folder error: {e.Message}");
            }


            // Add record to shared folder.
            await vault.MoveRecords(new[] { new RecordPath {
                                                RecordUid = search.Uid
                                            } }, sharedFolder.Uid, true);

            if (auth.AuthContext.IsEnterpriseAdmin)
            {
                // Load enterprise data.
                var enterprise = new EnterpriseData(auth);
                await enterprise.GetEnterpriseData();

                // Find team with name "Google".
                var team = enterprise.Teams
                           .FirstOrDefault(x => string.Compare(x.Name, "Google", StringComparison.InvariantCultureIgnoreCase) == 0);
                if (team == null)
                {
                    // Create team.
                    team = await enterprise.CreateTeam(new EnterpriseTeam
                    {
                        Name            = "Google",
                        RestrictEdit    = false,
                        RestrictSharing = true,
                        RestrictView    = false,
                    });
                }

                if (team != null)
                {
                    // Add users to the "Google" team.
                    await enterprise.AddUsersToTeams(
                        new[] { "*****@*****.**", "*****@*****.**" },
                        new[] { team.Uid },
                        Console.WriteLine);
                }
            }

            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }
Example #9
0
    static public Boolean Identify(Page Page, Boolean JsonReturn, Boolean supressReturn, out String errorText)
    {
        try
        {
            Boolean busca = false;

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

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

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

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

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

                try
                {
                    DataTable dt = null;

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

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

                        Page.Session["enterprise_data"] = data;

                        errorText = "";

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

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

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

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

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


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

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

            return(false);
        }
    }