コード例 #1
0
 /// <summary>
 /// Gets institution host location
 /// </summary>
 /// <param name="useSsl">Use SSL</param>
 /// <returns>Institution host location</returns>
 public virtual string GetInstitutionHost(bool useSsl)
 {
     return(ConfigurationHelper.GetSiteUrl());
 }
コード例 #2
0
        /// <summary>
        /// Gets the institution code. This returns null IF HTTP context or request or session is not available.
        /// If we return null, then requestAvailable is false. If central, we return the default code
        /// </summary>
        /// <returns></returns>
        /// <exception cref="GeneralException"></exception>
        public virtual string GetInstitutionCode(out bool requestAvailable)
        {
            string core = Utilities.INST_DEFAULT_CODE;

            if (IsRequestAvailable(_httpContext))
            {
                requestAvailable = true;
                string instCode;
                var    httpSession = _httpContext.Session;
                var    routeData   = _httpContext.Request.RequestContext?.RouteData?.Values;
                if (routeData == null || routeData.Count < 2 || httpSession == null)
                {
                    // This can happen when we invoke this before MVC is activated.
                    #region Pre-MVC
                    if (routeData.ContainsKey("institution"))
                    {
                        return(Convert.ToString(routeData["institution"]));
                    }

                    var url     = GetThisPageUrl(false, false).ToLowerInvariant();
                    var siteUrl = ConfigurationHelper.GetSiteUrl().ToLowerInvariant();
                    url = url.Replace(siteUrl, string.Empty);
                    if (string.IsNullOrWhiteSpace(url))
                    {
                        return(core);
                    }

                    var segments = url.Split('/');
                    switch (segments.Length)
                    {
                    // This code HEAVILY relies on the url templates setup in
                    // MultiTenancyFramework.Mvc.InstitutionRouteConfig.RegisterRoutes
                    case 1:
                        if (new[] { "home", "error" }.Contains(segments[0]))
                        {
                            instCode = core;
                        }
                        else
                        {
                            instCode = segments[0];
                        }
                        break;

                    case 2:
                        if (new[] { "home", "error" }.Contains(segments[1]))
                        {
                            instCode = segments[0];
                        }
                        else
                        {
                            instCode = core;
                        }
                        break;

                    case 3:
                        int id;
                        if (int.TryParse(segments[2], out id))
                        {
                            instCode = core;
                        }
                        else
                        {
                            instCode = segments[0];
                        }
                        break;

                    case 4:
                    default:
                        instCode = segments[0];
                        break;
                    }
                    #endregion
                }
                else
                {
                    #region MVC-Specific
                    instCode = Convert.ToString(routeData["institution"]) ?? core;
                    if (string.IsNullOrWhiteSpace(instCode) || instCode.Equals(core, StringComparison.OrdinalIgnoreCase))
                    {
                        return(core);
                    }

                    // The request may be from a non-existent institution, so we check if we have it in session
                    if (httpSession != null && httpSession[SS_CODE] != null)
                    {
                        var codeInSession = Convert.ToString(httpSession[SS_CODE]); //ClaimsPrincipal.Current.FindFirst("ic")?.Value; //
                        if (!instCode.Equals(codeInSession, StringComparison.OrdinalIgnoreCase))
                        {
                            var error = $"codeInSession ({codeInSession}) != instCode ({instCode}).";
                            var ex    = new LogOutUserException(error);
                            throw ex;
                        }
                        return(codeInSession);
                    }
                    #endregion
                }

                // if it's a tenant
                if (!string.IsNullOrWhiteSpace(instCode) && !instCode.Equals(core, StringComparison.OrdinalIgnoreCase))
                {
                    var query = new GetInstitutionByCodeQuery
                    {
                        Code = instCode,
                    };
                    var inst = Utilities.QueryProcessor.Process(query);
                    if (inst == null)
                    {
                        if (IsStaticResource())
                        {
                            instCode = core;
                        }
                        else
                        {
                            throw new GeneralException($"The code: {instCode} does not belong to any institution on our system.", ExceptionType.UnidentifiedInstitutionCode);
                        }
                    }
                }
                _httpContext.Request.RequestContext.RouteData.Values["institution"] = instCode;
                if (_httpContext.Session != null)
                {
                    _httpContext.Session[SS_CODE] = instCode;
                }

                return(instCode); // return inst.Code;
            }

            requestAvailable = false;
            return(null);
        }
コード例 #3
0
        /// <summary>
        /// Get context IP address
        /// </summary>
        /// <returns>URL referrer</returns>
        public virtual string GetCurrentIpAddress()
        {
            if (!IsRequestAvailable(_httpContext))
            {
                return(string.Empty);
            }

            var result = "";

            try
            {
                if (_httpContext.Request.Headers != null)
                {
                    //The X-Forwarded-For (XFF) HTTP header field is a de facto standard
                    //for identifying the originating IP address of a client
                    //connecting to a web server through an HTTP proxy or load balancer.
                    var forwardedHttpHeader = "X-FORWARDED-FOR";
                    if (!string.IsNullOrWhiteSpace(ConfigurationHelper.AppSettingsItem <string>("ForwardedHTTPheader")))
                    {
                        //but in some cases server use other HTTP header
                        //in these cases an administrator can specify a custom Forwarded HTTP header
                        //e.g. CF-Connecting-IP, X-FORWARDED-PROTO, etc
                        forwardedHttpHeader = ConfigurationHelper.AppSettingsItem <string>("ForwardedHTTPheader");
                    }

                    //it's used for identifying the originating IP address of a client connecting to a web server
                    //through an HTTP proxy or load balancer.
                    string xff = _httpContext.Request.Headers.AllKeys
                                 .Where(x => forwardedHttpHeader.Equals(x, StringComparison.InvariantCultureIgnoreCase))
                                 .Select(k => _httpContext.Request.Headers[k])
                                 .FirstOrDefault();

                    //if you want to exclude private IP addresses, then see http://stackoverflow.com/questions/2577496/how-can-i-get-the-clients-ip-address-in-asp-net-mvc
                    if (!string.IsNullOrWhiteSpace(xff))
                    {
                        string lastIp = xff.Split(',')[0];
                        result = lastIp;
                    }
                }

                if (string.IsNullOrWhiteSpace(result))
                {
                    result = _httpContext.Request.UserHostAddress;
                }
            }
            catch { }

            if (string.IsNullOrWhiteSpace(result)) // should never happen
            {
                result = IPResolver.GetIP4Address();
            }

            //some validation
            if (result == "::1")
            {
                result = "127.0.0.1";
            }
            //remove port
            if (!string.IsNullOrWhiteSpace(result))
            {
                int index = result.IndexOf(":", StringComparison.InvariantCultureIgnoreCase);
                if (index > 0)
                {
                    result = result.Substring(0, index);
                }
            }
            return(result);
        }