Exemplo n.º 1
0
        private string Verify(System.Web.HttpRequestBase Request, string ApiKey)
        {
            // Read the nonce from the request
            var nonce       = Request.Headers["x-authy-signature-nonce"];
            var method      = Request.HttpMethod;
            var url         = Request.Url.AbsoluteUri;
            var bodyRequest = new string [];

            foreach (string key in Request.Form.Keys)
            {
                bodyRequest.Add(key + "=" + Request.Form[key]);
            }
            // Sort the params
            var params = String.join("&", bodyRequest.Sort());

            // concatenate all together and separate by '|'
            var data = $"{nonce}|{method}|{url}|{params}";

            // compute the signature
            var encoding = new System.Text.ASCIIEncoding();

            byte[] ApiKeyBytes = encoding.GetBytes(ApiKey);
            byte[] DataBytes   = encoding.GetBytes(data);
            using (var hmacsha256 = new HMACSHA256(ApiKeyBytes))
            {
                // Read the Authy Signature from the request
                var sig = Request.Headers["x-authy-signature"];

                // compare the message signature with your calculated signature
                byte[] hashmessage = hmacsha256.ComputeHash(DataBytes);
                return(Convert.ToBase64String(hashmessage) == sig);
            }
        }
Exemplo n.º 2
0
        public static string GetClientIpAddress(System.Web.HttpRequestBase request)
        {
            try
            {
                var userHostAddress = request.UserHostAddress;

                // Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
                // Could use TryParse instead, but I wanted to catch all exceptions
                System.Net.IPAddress.Parse(userHostAddress);

                var xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];

                if (string.IsNullOrEmpty(xForwardedFor))
                    return userHostAddress;

                // Get a list of public ip addresses in the X_FORWARDED_FOR variable
                var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();

                // If we found any, return the last one, otherwise return the user host address
                return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
            }
            catch (Exception)
            {
                // Always return all zeroes for any failure (my calling code expects it)
                return "0.0.0.0";
            }
        }
Exemplo n.º 3
0
        private bool _updDireccionEstudiante(System.Web.HttpRequestBase dtaFrmEstudiante)
        {
            bool rst = true;

            try
            {
                string[] dpaDirEstudiante = new string[] { dtaFrmEstudiante["ddl_DUPais"].ToString().Trim(),
                                                           dtaFrmEstudiante["ddl_DUProvincias"].ToString().Trim(),
                                                           dtaFrmEstudiante["ddl_DUCiudades"].ToString().Trim(),
                                                           dtaFrmEstudiante["ddl_DUParroquias"].ToString().Trim() };

                this.dtaDireccionEstudiante.dir_callePrincipal   = dtaFrmEstudiante["txtDirCallePrincipal"].ToString().Trim();
                this.dtaDireccionEstudiante.dir_calleTransversal = dtaFrmEstudiante["txtDirCalleSecundaria"].ToString().Trim();
                this.dtaDireccionEstudiante.dir_dpa         = dpaDirEstudiante;
                this.dtaDireccionEstudiante.dir_numero      = dtaFrmEstudiante["txtDirNumeroCasa"].ToString().Trim();
                this.dtaDireccionEstudiante.dir_procedencia = dtaFrmEstudiante["txtDirReferencia"].ToString().Trim();
                this.dtaDireccionEstudiante.dir_referencia  = dtaFrmEstudiante["txtDirReferencia"].ToString().Trim();
            }
            catch (Exception ex) {
                Errores err = new Errores();
                err.SetError(ex, "_updDireccionEstudiante");
                rst = false;
            }

            return(rst);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Automatically detects the IP of the user from the Request object
        /// filling the acknowledgedFromIP field, and detectedIPs with
        /// all the ones detected with name (because there are several sources
        /// of the IP, and at some cases the one that looks 'the best' may not
        /// be the correct one, so we still store everything we know.
        ///
        /// More info: https://stackoverflow.com/questions/735350/how-to-get-a-users-client-ip-address-in-asp-net
        /// </summary>
        public void DetectIP(System.Web.HttpRequestBase request)
        {
            // Is the same as request.ServerVariables["REMOTE_ADDR"]
            // and means the client that reaches this server; but may
            // be a proxy and not the original source
            var directClientIP = N.DW(request.UserHostAddress);

            // List of IPs as result of proxies forwarding the request
            string forwardedIPs = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            // The first one is the client, others are just proxies
            string forwardedClientIP = null;

            if (!string.IsNullOrEmpty(forwardedIPs))
            {
                forwardedClientIP = N.DW(forwardedIPs.Split(',')[0]);
            }

            // Noticed by a cluster
            var insideClusterIP = N.DW(request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"]);

            // Storing all of them
            detectedIPs = "Remote_addr=" + directClientIP + ", Cluster=" + insideClusterIP + ", Forwarded=" + forwardedIPs;

            // Get the best guess
            acknowledgedFromIP = insideClusterIP ?? forwardedClientIP ?? directClientIP;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Autentica Usuário na base de dados local
        /// Gera token
        /// </summary>
        /// <param name="username">login</param>
        /// <param name="password">senha</param>
        /// <param name="request">System.WebHttpResponseBase request</param>
        /// <returns></returns>
        public Status AutenticaUsuario(string username, string password, System.Web.HttpRequestBase request)
        {
            // 1. Verifica se o usuário existe na base de dados
            Usuario user = unit.UsuarioRepository.All().SingleOrDefault(x => x.Login == username);

            if (user != null)
            {
                var  passwordMD5 = password.ComputeHash(Infra.HashHelper.eHashType.MD5);
                bool autenticado = unit.UsuarioRepository.All()
                                   .Any(x =>
                                        x.Login.Equals(username, StringComparison.InvariantCultureIgnoreCase) &&
                                        x.Senha.Equals(passwordMD5));

                if (autenticado)
                {
                    return new Status {
                               Succeeded = true, Message = "Autenticado com sucesso.", Token = tokenManager.GerarToken(user.Id, request).Hash
                    }
                }
                ;
                else
                {
                    return new Status {
                               Succeeded = false, Message = "Usuário ou senha incorreta.", Token = null
                    }
                };
            }

            return(new Status {
                Succeeded = false, Message = "Usuario não encontrado na base de dados.", Token = null
            });
        }
Exemplo n.º 6
0
        /// <summary>
        /// 获取Htpp请求中的IP地址
        /// </summary>
        /// <param name="httpRequest">Http请求</param>
        /// <returns></returns>
        public static string GetContextIP(this System.Web.HttpRequestBase httpRequest)
        {
            if (httpRequest == null || httpRequest.ServerVariables == null)
            {
                return(string.Empty);
            }

            string stream = httpRequest.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(stream))
            {
                stream = httpRequest.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(stream))
            {
                stream = httpRequest.UserHostAddress;
            }

            if (string.IsNullOrEmpty(stream))
            {
                return(string.Empty);
            }

            var ip = stream.Split(new[] { ',', '|', ';' }, StringSplitOptions.RemoveEmptyEntries).ElementAt(0);

            return(ObjectExtension.IsIP(ip) ? ip : string.Empty);
        }
    internal static Dictionary <string, string> Deserialize(System.Web.HttpRequestBase Request)
    {
        Request.InputStream.Position = 0;
        string Json = new StreamReader(Request.InputStream).ReadToEnd();

        return(new JavaScriptSerializer().Deserialize <Dictionary <string, string> >(Json));
    }
Exemplo n.º 8
0
        internal async Task <string> Generate(System.Web.HttpRequestBase Request, DbConnectionSklad db, int DirCustomersID, Classes.Account.Login.Field field)
        {
            #region Параметры

            pID = Request.Params["pID"];

            pLanguage = Convert.ToInt32(Request.Params["pLanguage"]);
            DateS     = Convert.ToDateTime(Convert.ToDateTime(Request.Params["DateS"]).ToString("yyyy-MM-dd 00:00:00"));
            DatePo    = Convert.ToDateTime(Convert.ToDateTime(Request.Params["DatePo"]).ToString("yyyy-MM-dd 23:59:59"));

            OnlySum = false;
            bool bOnlySum = Boolean.TryParse(Request.Params["OnlySum"], out OnlySum);

            #endregion


            string ret = "";

            if (OnlySum)
            {
                ret = await mOnlySum(db, field);
            }
            else
            {
                ret = await mAllReport(db, field);
            }

            return(ret);
        }
Exemplo n.º 9
0
        public NotifyResponse Notify(System.Web.HttpRequestBase Request)
        {
            //测试
            //string result = "acct=olb9MuLyENyjsUtzwqw9s9ZuaL3c&appid=00008692&chnltrxid=4200000119201805246599107754&cusid=142581072993330&cusorderid=LYZ_20180524115717445&outtrxid=LYZ_20180524115717445&paytime=20180524115806&sign=4D6CF5879D691B5E663C1CDF9306548C&termauthno=LQT&termrefnum=4200000119201805246599107754&termtraceno=0&trxamt=1&trxcode=VSP501&trxdate=20180524&trxid=111857690000305187&trxstatus=0000";

            //生产
            string result = Request.Form.ToString();

            if (!string.IsNullOrWhiteSpace(result))
            {
                Dictionary <String, String> dic = new Dictionary <string, string>();

                foreach (var m in result.Split('&'))
                {
                    var value = m.Split('=');
                    dic.Add(value[0], value[1]);
                }

                if (IsVerify(dic))
                {
                    return(JsonHelper.Deserialize <NotifyResponse>(JsonHelper.Serialize(dic)));
                }
            }

            return(null);
        }
Exemplo n.º 10
0
        public HttpStatusCode StartHandshake(System.Web.HttpRequestBase request, HandshakeModel model)
        {
            request.InputStream.Seek(0, SeekOrigin.Begin);
            string jsonData = new StreamReader(request.InputStream).ReadToEnd();

            string hash = request.Headers["x-hash"];

            if (!HashIsOkHandshake(hash, jsonData))
            {
                var    myHash       = Security.Hash.GenerateHash(AppInformation.Instance.HandshakeUrl, jsonData);
                string errorMessage = GetErrorHandshakeHashNotOk(model, jsonData, hash, myHash);
                Error.ErrorLogger.ErrorOccurred(errorMessage);

                return(HttpStatusCode.ServiceUnavailable);
            }

            var repo       = RepositoryContainer.ConnectionRepo;
            var connection = repo.GetForApiPublic(model.api_public);

            if (connection != null)
            {
                string errorMessage = $"Trying to do a handshake with {model.api_public}, but there is already a connection for this exact api_public.";

                Error.ErrorLogger.ErrorOccurred(errorMessage);

                return(HttpStatusCode.ServiceUnavailable);
            }

            repo.AddConnection(model.api_public, model.api_secret, model.api_root, model.return_url);

            return(HttpStatusCode.OK);
        }
Exemplo n.º 11
0
        public PaymentInfo ProcessNotify(System.Web.HttpRequestBase context)
        {
            //Post方式
            NameValueCollection         coll  = context.Form;
            Dictionary <string, string> paras = new Dictionary <string, string>();

            foreach (string key in coll.AllKeys)
            {
                paras.Add(key, coll[key]);
            }
            Notify      notify   = new Notify(WorkDirectory);
            PaymentInfo info     = new PaymentInfo();
            string      notifyid = notify.GetNotifyId(paras);
            bool        isSign   = notify.Verify(paras, notifyid, (string)coll["sign"], _config, false);

            if (isSign)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(coll["notify_data"]);
                string out_trade_no = xmlDoc.SelectSingleNode("/notify/out_trade_no").InnerText;
                string trade_no     = xmlDoc.SelectSingleNode("/notify/trade_no").InnerText;
                string trade_status = xmlDoc.SelectSingleNode("/notify/trade_status").InnerText;
                string notify_time  = xmlDoc.SelectSingleNode("/notify/notify_time").InnerText;
                if (trade_status == "TRADE_FINISHED" || trade_status == "TRADE_SUCCESS")
                {
                    info.OrderIds  = out_trade_no.Split(',').Select(item => long.Parse(item));
                    info.TradNo    = trade_no;
                    info.TradeTime = DateTime.Parse(notify_time);
                    info.ResponseContentWhenFinished = "success";
                }
            }
            return(info);
        }
Exemplo n.º 12
0
        private bool _updDatosPersonalesEstudiante(System.Web.HttpRequestBase dtaFrmEstudiante)
        {
            bool rst = true;

            try
            {
                //  Informacion de persona
                this.dtaEstudiante.eci_id = Convert.ToInt32(dtaFrmEstudiante["ddlEstadoCivil"].ToString().Trim());
                this.dtaEstudiante.etn_id = Convert.ToInt32(dtaFrmEstudiante["ddlEtnia"].ToString().Trim());
                this.dtaEstudiante.tsa_id = Convert.ToInt32(dtaFrmEstudiante["ddlTipoSangre"].ToString().Trim());
                this.dtaEstudiante.gen_id = Convert.ToInt32(dtaFrmEstudiante["ddlGenero"].ToString().Trim());
                this.dtaEstudiante.per_telefonoCelular  = dtaFrmEstudiante["txtTelefonoCelular"].ToString().Trim();
                this.dtaEstudiante.per_telefonoCasa     = dtaFrmEstudiante["txtTelefonoFijo"].ToString().Trim();
                this.dtaEstudiante.per_emailAlternativo = dtaFrmEstudiante["txtCorreoAlternativo"].ToString().Trim();

                string DPA_FN = dtaFrmEstudiante["ddl_FNPais"].ToString().Trim() + "|" +
                                dtaFrmEstudiante["ddl_FNProvincias"].ToString().Trim() + "|" +
                                dtaFrmEstudiante["ddl_FNCiudades"].ToString().Trim() + "|" +
                                dtaFrmEstudiante["ddl_FNParroquias"].ToString().Trim();
            }catch (Exception ex) {
                Errores err = new Errores();
                err.SetError(ex, "_updDatosPersonalesEstudiante");
                rst = false;
            }

            return(rst);
        }
Exemplo n.º 13
0
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            if (filterContext.Result is INoCompressResult)
            {
                return;
            }

            System.Web.HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];

            if (string.IsNullOrEmpty(acceptEncoding))
            {
                return;
            }

            acceptEncoding = acceptEncoding.ToUpperInvariant();

            System.Web.HttpResponseBase response = filterContext.HttpContext.Response;

            if (acceptEncoding.Contains("GZIP"))
            {
                response.AppendHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("DEFLATE"))
            {
                response.AppendHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }
Exemplo n.º 14
0
        public PaymentInfo ProcessReturn(System.Web.HttpRequestBase context)
        {
            //Get方式
            NameValueCollection         coll  = context.QueryString;
            Dictionary <string, string> paras = new Dictionary <string, string>();

            foreach (string key in coll.AllKeys)
            {
                paras.Add(key, coll[key]);
            }
            if (_config == null)
            {
                _config = _Config;
            }
            Notify      notify   = new Notify(WorkDirectory);
            string      notifyid = notify.GetNotifyId(paras);
            bool        isSign   = notify.Verify(paras, notifyid, (string)coll["sign"], _config);//验证签名
            PaymentInfo info     = new PaymentInfo();

            if (isSign)
            {
                info.OrderIds = coll["out_trade_no"].Split(',').Select(item => long.Parse(item));
                info.TradNo   = coll["trade_no"];
            }
            return(info);
        }
Exemplo n.º 15
0
        public static CookieContainer GetCookieContainer(this System.Web.HttpRequestBase sourceHttpRequest, string applicationGatewayFqdn)
        {
            var sourceCookies = sourceHttpRequest.Cookies;

            if (sourceCookies.Count == 0)
            {
                return(null);
            }
            else
            {
                var domain          = new Uri(applicationGatewayFqdn).Host;
                var cookieContainer = new CookieContainer();
                for (var i = 0; i < sourceCookies.Count; i++)
                {
                    var cSource = sourceCookies[i];
                    if (cSource != null)
                    {
                        var cookieTarget = new Cookie()
                        {
                            Domain = domain,
                            Name   = cSource.Name,
                            Path   = cSource.Path,
                            Secure = cSource.Secure,
                            Value  = cSource.Value
                        };
                        cookieContainer.Add(cookieTarget);
                    }
                }

                return(cookieContainer);
            }
        }
Exemplo n.º 16
0
        public static MvcHtmlString AuthorizedReturnToListLink(this HtmlHelper htmlHelper, string linkText, string actionName, object htmlAttributes)
        {
            string area       = htmlHelper.ViewContext.RouteData.Values["area"] as string;
            string controller = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
            string url        = UrlHelper.GenerateUrl(null, actionName, controller, new System.Web.Routing.RouteValueDictionary(new
            {
                area = area
            }), System.Web.Routing.RouteTable.Routes, htmlHelper.ViewContext.RequestContext, false);

            System.Web.HttpRequestBase request = htmlHelper.ViewContext.HttpContext.Request;
            MvcHtmlString result;

            if (Authorization.Instance.IsAuthrized(htmlHelper.ViewContext.HttpContext, url))
            {
                TagBuilder builder = new TagBuilder("a");
                if (htmlAttributes != null)
                {
                    builder.MergeAttributes <string, object>(new System.Web.Routing.RouteValueDictionary(htmlAttributes));
                }
                builder.MergeAttribute("href", url);
                builder.InnerHtml = htmlHelper.Encode(linkText);
                result            = MvcHtmlString.Create(builder.ToString());
            }
            else
            {
                result = MvcHtmlString.Empty;
            }
            return(result);
        }
Exemplo n.º 17
0
        /// <summary>
        /// 请求参数Get,Post
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static List <string> RequestParams(this System.Web.HttpRequestBase Request)
        {
            var rs = new List <string>();

            rs.AddRange(Request.Form.AllKeys);
            rs.AddRange(Request.QueryString.AllKeys);
            return(rs.Distinct().ToList());
        }
Exemplo n.º 18
0
        public override ClienteViewModel CreateRepository(System.Web.HttpRequestBase Request = null)
        {
            ClienteViewModel c = base.CreateRepository(Request);

            c.dt_inclusao     = Funcoes.Brasilia();
            c.ind_tipo_pessoa = "PJ";
            return(c);
        }
Exemplo n.º 19
0
 public ApiProxy(System.Web.HttpRequestBase Request)
 {
     if (Request.Cookies["access_token"] != null)
     {
         _authToken = "Bearer " + Request.Cookies["access_token"].Value;
     }
     this.Request = Request;
 }
Exemplo n.º 20
0
        /// <summary>
        /// Get <see cref="OrderFlow"/> with same name as application host name.
        /// </summary>
        private OrderFlow GetOrderFlowFromHostname(System.Web.HttpRequestBase request)
        {
            var hostname = request.Url.Authority;

            var orderFlow = GlobalOrderFlows.OrderFlows.GetOrderFlow(hostname);

            return(orderFlow);
        }
Exemplo n.º 21
0
        public static object GetByKeyword(System.Web.HttpRequestBase request)
        {
            string fieldname = request.Params["fieldname"].ToString();
            string keyword   = request.Params["keyword"].ToString();
            string tablename = request.Params["tablename"] != null ? request.Params["tablename"].ToString() : "";

            return(GetByKeyword(request, fieldname, keyword, tablename));
        }
Exemplo n.º 22
0
 public ApiProxy(System.Web.HttpRequestBase Request)
 {
     if (Request.Cookies["access_token"] != null)
     {
         _authToken = "Bearer " + Request.Cookies["access_token"].Value;
     }
     this.Request = Request;
 }
 private void MyAsync(System.Web.HttpRequestBase req)
 {
     System.Threading.Thread.Sleep(5000);
     foreach (var item in req.Cookies)
     {
         System.Diagnostics.Debug.WriteLine(item);
     }
 }
Exemplo n.º 24
0
        public static string GetMethod(this HttpRequest request)
        {
#if NETFRAMEWORK
            return(request.HttpMethod);
#else
            return(request.Method);
#endif
        }
Exemplo n.º 25
0
        public static string GetFormValue(this HttpRequest request, string key)
        {
#if NETFRAMEWORK
            return(request.Form[key]);
#else
            return(request.HasFormContentType && request.Form[key] != StringValues.Empty ? request.Form[key].ToString() : "");
#endif
        }
Exemplo n.º 26
0
        public static string AbsoluteUrl(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues = null)
        {
            UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
            string    url       = urlHelper.Action(actionName, controllerName, routeValues);

            System.Web.HttpRequestBase request = urlHelper.RequestContext.HttpContext.Request;

            return(String.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Host, url));
        }
Exemplo n.º 27
0
        public ITokenContext FromHttpRequest(System.Web.HttpRequestBase request)
        {
            if (request.HttpMethod.ToUpperInvariant() != "POST")
            {
                throw new OAuthFatalException(TokenEndpointResources.InvalidHttpMethodTokenRequest);
            }

            return(CreateContext(request.QueryString, request.Form, request.Headers));
        }
Exemplo n.º 28
0
 public override DocInternoViewModel CreateRepository(System.Web.HttpRequestBase Request)
 {
     return(new DocInternoViewModel()
     {
         dt_arquivo = DateTime.Today,
         dt_novo = DateTime.Today.AddDays(10),
         descricao = ""
     });
 }
Exemplo n.º 29
0
        /// <summary>
        /// 获取请求urlHost
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetHostRequest(System.Web.HttpRequestBase request)
        {
            string urlHost = request.Url.Host;

            if (!request.Url.IsDefaultPort && Code.ConfigHelp.configHelp.ISOPENPORT)
            {
                urlHost = request.Url.Authority;
            }
            return(urlHost);
        }
Exemplo n.º 30
0
 bool IgnoreExisting(System.Web.HttpRequestBase request)
 {
     // N2 has a history of requiring the start page's template to be located at /Default.aspx.
     // Since a previous version this is no longer required with the consequence of /Default.aspx
     // beeing required only for igniting an asp.net web request when accessing /. With the new
     // behaviour access to the default document (/ or /Default.aspx) will be rewritten to which-
     // ever template the current start page specifies. The previous behaviour can be restored
     // by configuring n2 to ignore existing files.
     return(ignoreExistingFiles || (!File.Exists(request.PhysicalPath) && !Directory.Exists(request.PhysicalPath)));
 }
Exemplo n.º 31
0
        public bool IsMatch(System.Web.HttpRequestBase httpRequest)
        {
            var matched = false;

            if (httpRequest.UserLanguages != null)
            {
                matched = httpRequest.UserLanguages.Contains(this.LanguageName, StringComparer.OrdinalIgnoreCase);
            }
            return(matched);
        }