コード例 #1
0
ファイル: ResponseFilter.cs プロジェクト: ajbeaven/i18n
 public ResponseFilter(
     System.Web.HttpContextBase httpContext, 
     Stream outputStream,
     IEarlyUrlLocalizer earlyUrlLocalizer,
     INuggetLocalizer nuggetLocalizer)
 {
     m_httpContext = httpContext;
     m_outputStream = outputStream;
     m_earlyUrlLocalizer = earlyUrlLocalizer;
     m_nuggetLocalizer = nuggetLocalizer;
 }
コード例 #2
0
        public PluginBuilder(Assembly assembly
			, Microsoft.Practices.Unity.IUnityContainer container
			, System.Web.HttpContextBase context
			, Models.WebSiteSettings webSiteSettings)
        {
            this.assembly = assembly;
            this.m_Container = container;
            this.m_HttpContext = context;
            this.m_WebSiteSettings = webSiteSettings;

            foreach (Type type in assembly.GetExportedTypes())
            {
                if (!type.IsAbstract && typeof(PluginInit).IsAssignableFrom(type))
                {
                    pluginTypes.Add(type);
                }
            }
        }
コード例 #3
0
        public static bool IsUserInRole(string securityType, string roleKey, System.Web.HttpContextBase context)
        {
            // anonymous user
            if (context.User == null)
            {
                return(false);
            }

            switch (securityType)
            {
            case "role":
                return(ResourceBase.IsUserInRole(context.User, roleKey) || context.User.IsInRole(roleKey));

            case "group":
                RestNetUser rUser = (RestNetUser)context.User.Identity;
                return(rUser.isInRole(roleKey));

            case "none":
                return(true);

            default:
                throw ErrorHandler.HttpConfigurationError("The RestNetSecurityType setting in web.config contains an unknown value. Valid values are 'role', 'group', or 'none'");
            }
        }
コード例 #4
0
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            var roles = System.Web.Security.Roles.GetRolesForUser();
            var user  = WebMatrix.WebData.WebSecurity.CurrentUserName;

            var inRoles = Roles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var inUsers = Users.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var exRoles = ExcludeRoles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var exUsers = ExcludeUsers.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            bool result0 = WebMatrix.WebData.WebSecurity.IsAuthenticated;
            bool result1 = inRoles.Contains("*") || roles.Any(r => inRoles.Contains(r));
            bool result2 = inUsers.Contains("*") || inUsers.Contains(user);
            bool result3 = !exRoles.Contains("*") && roles.All(r => !exRoles.Contains(r));
            bool result4 = !exUsers.Contains("*") && !exUsers.Contains(user);

            bool result = result0 && (result1 || result2) && (result3 && result4);

            if (result == false)
            {
                TongJi.Web.Notifications.Notification.EnqueueMessage(string.Format("您所在的用户组没有访问此功能模块的权限,请咨询您的管理员。"));
            }
            return(result);
        }
コード例 #5
0
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            if (!CurrentRequestData.CurrentUser.IsActive)
            {
                return(false);
            }
            object idVal;

            if (httpContext.Request.RequestContext.RouteData.Values.TryGetValue("id", out idVal))
            {
                int id;
                if (int.TryParse(Convert.ToString(idVal), out id))
                {
                    var o = MrCMSApplication.Get <ISession>().Get(_type, id);
                    if (o == null)
                    {
                        return(false);
                    }

                    return(new TypeACLRule().CanAccess(CurrentRequestData.CurrentUser, _operation, o.GetType().FullName));
                }
            }
            return(false);
        }
コード例 #6
0
ファイル: UserAuthorize.cs プロジェクト: Jaylala03/OJCMS
 protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
 {
     if (httpContext.User.Identity.IsAuthenticated)
     {
         var    routeData       = ((MvcHandler)httpContext.Handler).RequestContext.RouteData;
         object currentAreaName = string.Empty;
         routeData.Values.TryGetValue("area", out currentAreaName);
         object currentControllerName = string.Empty;
         routeData.Values.TryGetValue("controller", out currentControllerName);
         object currentActionName = string.Empty;
         routeData.Values.TryGetValue("action", out currentActionName);
         //if (currentControllerName.ToString(true).ToLower() == Constants.CommonConstants.DefaultControllerName.ToLower() && currentActionName.ToString(true).ToLower() == Constants.CommonConstants.DefaultActionName.ToLower())
         //{
         //    return true;
         //}
         Worker loggedInWorker = WebHelper.CurrentSession.Content.LoggedInWorker;
         if (loggedInWorker == null)
         {
             IWorkerRepository workerRepository = DependencyResolver.Current.GetService(typeof(IWorkerRepository)) as IWorkerRepository;
             loggedInWorker = workerRepository.Find(httpContext.User.Identity.Name);
             WebHelper.CurrentSession.Content.LoggedInWorker = loggedInWorker;
         }
         if (loggedInWorker != null)
         {
             if (loggedInWorker.ID == loggedInWorker.CreatedByworkerID)
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
     }
     return(base.AuthorizeCore(httpContext));
 }
コード例 #7
0
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            IPrincipal user = httpContext.User;

            if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
            {
                return(false);
            }

            var users = RoleNamesSplit.SelectMany(_ => Config.RoleConfig.GetUsers(_)).ToList();

            if (users.Count > 0 && (users.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase) || users.Contains("*", StringComparer.OrdinalIgnoreCase)))
            {
                return(true);
            }

            var roles = RoleNamesSplit.SelectMany(_ => Config.RoleConfig.GetRoles(_)).ToList();

            if (roles.Count > 0 && (roles.Any(user.IsInRole) || roles.Contains("*", StringComparer.OrdinalIgnoreCase))) //TODO: Only allow wildcard in users?
            {
                return(true);
            }

            //Not sure about this.
            if (Config.RoleConfig.DefaultAllow)
            {
                return(true);
            }

            return(false);
        }
コード例 #8
0
        /// <summary>
        /// 验证核心
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            try
            {
                MyInfo = new AdminState(httpContext).GetUserInfo();

                if (MyInfo == null || !(bool)MyInfo.InJob)
                {
                    return(false);
                }

                //判断权限
                if (PermissionId > 0)
                {
                    return(PermissionManager.CheckPermission(MyInfo, PermissionId));
                }
                else if (!string.IsNullOrEmpty(PermissionUrl))
                {
                    var urls = PermissionUrl.TrimEnd(',').ToLower().Split(',');
                    foreach (var url in urls)
                    {
                        //有一个Url允许,则通过
                        if (PermissionManager.CheckPermission(MyInfo, url))
                        {
                            return(true);
                        }
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                Tools.Tool.LogHelper.WriteLog(typeof(PermissionFilterAttribute), ex, 0, "");
                return(false);
            }
        }
コード例 #9
0
 public virtual new void PostMapRequestHandler(System.Web.HttpContextBase context)
 {
 }
コード例 #10
0
 public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     return(values.ContainsKey(ContentRoute.ContentItemKey) == false);
 }
コード例 #11
0
 public OrganizationHandler(System.Web.HttpContextBase HttpContext, bool isValidate)
 {
     // TODO: Complete member initialization
     this.HttpContext = HttpContext;
     this.isValidate  = isValidate;
 }
コード例 #12
0
 public void OnPreSiteRequestExecute(Site site, System.Web.HttpContextBase httpContext)
 {
     //traceListenser.WriteLine(string.Format("Process {0}.", httpContext.Request.RawUrl));
     //traceListenser.Flush();
 }
コード例 #13
0
        public string GetCurrentCulture(System.Web.HttpContextBase requestContext)
        {
            var cultureName = _underlyingCultureManager.GetCurrentCulture(requestContext);

            return(LookupForMasterCulture(cultureName));
        }
コード例 #14
0
 /// <summary>
 /// Check that current user is  in allowed roles
 /// </summary>
 /// <param name="httpContext"></param>
 /// <returns></returns>
 private bool UserIsAllowedByRole(System.Web.HttpContextBase httpContext)
 {
     return(httpContext.Request.IsAuthenticated &&
            (this.allowedRoles.Any(r => r == "*" || httpContext.User.IsInRole(r))));
 }
コード例 #15
0
        public bool LoginCustomer(string email, string password, ref string errorMessage, System.Web.HttpContextBase context, ref string userId, MerchantTribeApplication app)
        {
            bool result = false;

            try
            {
                SystemOperationResult op = ValidateUser(email, password);
                if (op.Success == false)
                {
                    errorMessage = op.Message;
                    return(false);
                }

                CustomerAccount u = Customers.FindByEmail(email);
                if (u == null)
                {
                    errorMessage = "Please check your email address and password and try again.";
                    return(false);
                }

                userId = u.Bvin;

                Cookies.SetCookieString(WebAppSettings.CookieNameAuthenticationTokenCustomer(app.CurrentStore.Id),
                                        u.Bvin,
                                        context, false, new EventLog());
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
                EventLog.LogEvent(ex);
                errorMessage = "Unknown login error. Contact administrator for assistance.";
            }

            return(result);
        }
コード例 #16
0
        //public static bool DeletePerson(Guid Id, ElasticClient client = null)
        //{
        //    if (client == null)
        //        client = Lib.ES.Manager.GetESClient();
        //    var res = client
        //        .Delete<Lib.Data.Person>(Id);
        //    return res.IsValid;
        //}

        public static void LogQueryError <T>(Nest.ISearchResponse <T> esReq, string text = "", System.Web.HttpContextBase httpContext = null, Exception ex = null)
            where T : class
        {
            Elasticsearch.Net.ServerError serverErr = esReq.ServerError;
            ESLogger.Error(new Devmasters.Core.Logging.LogMessage()
                           .SetMessage("ES query error: " + text
                                       + "\n\nCause:" + serverErr?.Error?.ToString()
                                       + "\n\nDetail:" + esReq.DebugInformation
                                       + "\n\n\n"
                                       )
                           .SetException(ex)
                           .SetCustomKeyValue("URL", httpContext?.Request?.RawUrl)
                           .SetCustomKeyValue("Stack-trace", System.Environment.StackTrace)
                           .SetCustomKeyValue("Referer", httpContext?.Request?.UrlReferrer?.AbsoluteUri)
                           .SetCustomKeyValue("User-agent", httpContext?.Request?.Browser?.Browser)
                           .SetCustomKeyValue("IP", httpContext?.Request?.UserHostAddress + " " + System.Web.HttpContext.Current?.Request?.UserHostName)
                           );
        }
コード例 #17
0
ファイル: TranslateSvc.cs プロジェクト: neo725/i18n
        public TranslateSvc_HttpContextBase(System.Web.HttpContextBase context)
        {
            if (context == null) { throw new ArgumentNullException("context"); }

            m_context = context;
        }
コード例 #18
0
ファイル: QuickBook.cs プロジェクト: dmarckmann/CompositeWeb
 public void Init(System.Web.HttpContextBase context)
 {
     _context = context;
 }
コード例 #19
0
 /// <summary>
 /// Conditionally installs the i18n response filter.
 /// </summary>
 /// <param name="context">The HttpContext context.</param>
 public static void InstallResponseFilter(System.Web.HttpContextBase context)
 {
     InstallResponseFilter(context, null);
 }
コード例 #20
0
 public RequestContext(System.Web.HttpContextBase httpContext, RouteData routeData)
 {
 }
コード例 #21
0
        //protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        //{
        //    return !this.isHandlerDisabled && (!this.requiresAuthentication || this.UserIsAllowed(httpContext));
        //}

        /// <summary>
        /// Check that current user is in allowed roles AND in allowed usernames
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        private bool UserIsAllowed(System.Web.HttpContextBase httpContext)
        {
            return(this.UserIsAllowedByRole(httpContext) && this.UserIsAllowedByName(httpContext));
        }
コード例 #22
0
 public bool IsAuthorized(System.Web.HttpContextBase httpContext)
 {
     return(true);
 }
コード例 #23
0
       protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
           {
 // your logic here
                return GetUsersecurityLevel();
             }
コード例 #24
0
 public override string GetLoggedInUserName(System.Web.HttpContextBase context)
 {
     return(LoggedInUserId);
 }
コード例 #25
0
 public override string GetLoggedInUserName(System.Web.HttpContextBase context)
 {
     throw new NotImplementedException();
 }
コード例 #26
0
        /// <summary>
        /// Implements the Early Url Localization logic.
        /// <see href="https://docs.google.com/drawings/d/1cH3_PRAFHDz7N41l8Uz7hOIRGpmgaIlJe0fYSIOSZ_Y/edit?usp=sharing"/>
        /// </summary>
        public void ProcessIncoming(
            System.Web.HttpContextBase context)
        {
            // Is URL explicitly excluded from localization?
            if (!m_urlLocalizer.FilterIncoming(context.Request.Url))
            {
                return;
            }             // YES. Continue handling request.

            bool allowRedirect =
                context.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase) ||
                context.Request.HttpMethod.Equals("HEAD", StringComparison.OrdinalIgnoreCase);

            // NO. Is request URL localized?
            string urlNonlocalized;
            string langtag = m_urlLocalizer.ExtractLangTagFromUrl(context, context.Request.RawUrl, UriKind.Relative, true, out urlNonlocalized);

            if (langtag == null)
            {
                // NO.
                // langtag = best match between
                // 1. Inferred user languages (cookie and Accept-Language header)
                // 2. App Languages.
                LanguageTag lt = context.GetInferredLanguage();

                // If redirection allowed...redirect user agent (browser) to localized URL.
                // The principle purpose of this redirection is to ensure the browser is showing the correct URL
                // in its address field.
                if (allowRedirect)
                {
                    RedirectWithLanguage(context, context.Request.RawUrl, lt.ToString(), m_urlLocalizer);
                    return;
                }

                // Otherwise, handle the request under the language infered above but without doing the redirect.
                // NB: this will mean that the user agent (browser) won't have the correct URL displayed;
                // however, this typically won't be an issue because we are talking about POST, PUT and DELETE methods
                // here which are typically not shown to the user.
                else
                {
                    context.SetPrincipalAppLanguageForRequest(lt);
                    return; // Continue handling request.
                }
            }

            // YES. Does langtag EXACTLY match an App Language?
            LanguageTag appLangTag = LanguageHelpers.GetMatchingAppLanguage(langtag);

            if (appLangTag.IsValid() &&
                appLangTag.Equals(langtag))
            {
                // YES. Establish langtag as the PAL for the request.
                context.SetPrincipalAppLanguageForRequest(appLangTag);

                // Rewrite URL for this request.
                context.RewritePath(urlNonlocalized);

                // Continue handling request.
                return;
            }

            // NO. Does langtag LOOSELY match an App Language?
            else if (appLangTag.IsValid() &&
                     !appLangTag.Equals(langtag))
            {
                // YES. Localize URL with matching App Language.
                // Conditionally redirect user agent to localized URL.
                if (allowRedirect)
                {
                    RedirectWithLanguage(context, urlNonlocalized, appLangTag.ToString(), m_urlLocalizer);
                    return;
                }
            }
            // NO. Do nothing to URL; expect a 404 which corresponds to language not supported.
            // Continue handling request.
        }
コード例 #27
0
 public void OnPostSiteRequestExecute(Site site, System.Web.HttpContextBase httpContext)
 {
     //traceListenser.WriteLine(string.Format("Process finised {0}, response length {1}.", httpContext.Request.RawUrl, httpContext.Response.Filter.Length));
     //traceListenser.Flush();
 }
コード例 #28
0
        /// <summary>
        /// Helper for localizing an individual URL string for a particular langtag value
        /// and URL of the current request.
        /// </summary>
        /// <param name="url">Subject URL to be localized.</param>
        /// <param name="langtag">Language with which to localize the URL.</param>
        /// <param name="requestUrl">URL of the current HTTP request being handled.</param>
        /// <returns>
        /// String describing the new localized URL, or null if the URL was not localized,
        /// either because it was already localized, or because it is from another host, or is explicitly
        /// excluded from localization by the filter.
        /// </returns>
        protected string LocalizeUrl(System.Web.HttpContextBase context, string url, string langtag, Uri requestUrl, bool incomingUrl)
        {
            // If URL has prefix indicating it should be excluded from localization...return unlocalized URL
            if (url.StartsWith(IgnoreLocalizationUrlPrefix))
            {
                return(url.Substring(IgnoreLocalizationUrlPrefix.Length));
            }

            // If URL is already localized...leave matched token alone.
            string urlNonlocalized;

            if (m_urlLocalizer.ExtractLangTagFromUrl(context, url, UriKind.RelativeOrAbsolute, incomingUrl, out urlNonlocalized) != null)
            {
                return(null);
            }                  // original

            // If URL is invalid...leave matched token alone.
            // NB: Uri.IsWellFormedUriString has odd URI fragment handling: if a valid URI contains a fragment
            // then it returns false. Go figure!
            if (!url.Contains("#") &&
                !Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
            {
                return(null);
            }                  // original

            // If URL is not local (i.e. remote host)...leave matched token alone.
            if (requestUrl != null && !requestUrl.IsLocal(url))
            {
                return(null);
            }                  // original

            // Is URL explicitly excluded from localization?
            if (!m_urlLocalizer.FilterOutgoing(url, requestUrl))
            {
                return(null);
            }                  // original

            // If url is un-rooted...make it rooted based on any current request URL.
            // This is to resolve problems caused to i18n with resource URL paths relative to the
            // current page (see issue #286).
            // By un-rooted we mean the url is not absolute (i.e. it starts from the path component),
            // and that that path component itself is a relative path (i.e. it doesn't start with a /).
            // In doing so we also eliminate any "../..", "./", etc.
            // Examples:
            //      url (before)                            requestUrl                  url (after)
            //      -------------------------------------------------------------------------------------------------------------------
            //      content/fred.jpg                        http://example.com/blog/    /blog/content/fred.jpg              (changed)
            //      content/fred.jpg                        http://example.com/blog     /content/fred.jpg                   (changed)
            //      /content/fred.jpg                       http://example.com/blog/    /content/fred.jpg                   (unchanged)
            //      http://example.com/content/fred.jpg     http://example.com/blog/    http://example.com/content/fred.jpg (unchanged)
            // See also test cases in ResponseFilterTests.ResponseFilter_can_patch_html_urls.
            //
            if (requestUrl != null)
            {
                bool urlIsUnrooted = !url.StartsWith("/") &&
                                     (!url.Contains(":") || !Uri.IsWellFormedUriString(url, UriKind.Absolute));
                // NB: the above is somewhat elaborate so as to avoid an object allocation
                // in all but edge cases. Note also that Uri.IsWellFormedUriString internally
                // simply does a Uri.TryCreate (at least as of .NET 4.6.1).
                if (urlIsUnrooted)
                {
                    Uri newUri = new Uri(requestUrl, url);
                    url = newUri.PathAndQuery + newUri.Fragment;
                    // NB: if there is no fragment then newUri.Fragment == ""
                }
            }

            // Localize the URL.
            return(m_urlLocalizer.SetLangTagInUrlPath(context, url, UriKind.RelativeOrAbsolute, langtag));
        }
コード例 #29
0
 /// <summary>
 /// 获取DbContext
 /// </summary>
 /// <param name="httpContext"></param>
 /// <returns></returns>
 public static TDbContext GetDbContext <TDbContext>(this System.Web.HttpContextBase httpContext)
     where TDbContext : System.Data.Entity.DbContext, new()
 {
     return(InnerGetDbContext <TDbContext>());
 }
コード例 #30
0
        public string ProcessOutgoing(
            string entity,
            string langtag,
            System.Web.HttpContextBase context)
        {
            // The goal here to localize same-host URLs in the entity body and so save a redirect
            // on subsequent requests to those URLs by the user-agent (i.e. Early URL Localization
            // of the subsequent request).
            // We patch all URLs in the entity which are:
            //  1. same-host
            //  2. are not already localized
            //  3. are not excluded by custom filtering
            // Examples of attributes containing urls include:
            //   <script src="..."> tags
            //   <img src="..."> tags
            //   <a href="..."> tags
            //   <link href="..."> tags
            // A full list is available here: http://www.w3.org/TR/REC-html40/index/attributes.html
            //

            Uri requestUrl = context != null ? context.Request.Url : null;

            // Localize urls in HTTP headers.
            if (context != null)
            {
                foreach (string hdr in m_httpHeadersContainingUrls)
                {
                    string hdrval = context.Response.Headers[hdr];
                    if (!hdrval.IsSet())
                    {
                        continue;
                    }
                    string urlNew = LocalizeUrl(context, hdrval, langtag, requestUrl, false);
                    if (urlNew == null)
                    {
                        continue;
                    }
                    context.Response.Headers[hdr] = urlNew;
                }
            }

            // Localize urls in the response body (entity).
            return(m_regexHtmlUrls.Replace(
                       entity,
                       delegate(Match match)
            {
                try {
                    string url = match.Groups[2].Value;
                    string urlNew = LocalizeUrl(context, url, langtag, requestUrl, false);
                    // If URL was not changed...leave matched token alone.
                    if (urlNew == null)
                    {
                        return match.Groups[0].Value;
                    }                                       // original

                    // Rebuild and return matched token.
                    string res = string.Format("{0}{1}{2}",
                                               match.Groups[1].Value,
                                               urlNew,
                                               match.Groups[3].Value);
                    return res;
                }
                catch (System.UriFormatException) {
                    return match.Groups[0].Value;     // original
                }
            }));
        }
 protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
 {
     return(true);
 }
コード例 #32
0
        bool?IAuthorizationBehavior.OverrideAuthorize(CommonJobsAuthorizeAttribute authorizeAttribute, System.Web.HttpContextBase httpContext)
        {
            //No setear la configuración representa un usuario no autenticado
            if (ForcedGroups == null)
            {
                return(false);
            }

            if (String.IsNullOrEmpty(authorizeAttribute.Roles))
            {
                return(true);
            }

            var required = authorizeAttribute.Roles.ToRoleList();

            return(ForcedGroups.Intersect(required).Any());
        }
コード例 #33
0
 public virtual new void PostResolveRequestCache(System.Web.HttpContextBase context)
 {
 }
コード例 #34
0
 public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     return(this.routeDirection == routeDirection);
 }