public string GetRouteDescriptorKey(HttpContextBase httpContext, RouteBase routeBase) { var route = routeBase as Route; var dataTokens = new RouteValueDictionary(); if (route != null) { dataTokens = route.DataTokens; } else { var routeData = routeBase.GetRouteData(httpContext); if (routeData != null) { dataTokens = routeData.DataTokens; } } var keyBuilder = new StringBuilder(); if (route != null) { keyBuilder.AppendFormat("url={0};", route.Url); } // the data tokens are used in case the same url is used by several features, like *{path} (Rewrite Rules and Home Page Provider) if (dataTokens != null) { foreach (var key in dataTokens.Keys) { keyBuilder.AppendFormat("{0}={1};", key, dataTokens[key]); } } return keyBuilder.ToString().ToLowerInvariant(); }
protected override void Context() { AccountService = MockRepository.GenerateStub<IAccountService>(); Identity = new FakeIdentity(Username); _user = new FakePrincipal(Identity, null); HttpRequest = MockRepository.GenerateStub<HttpRequestBase>(); HttpContext = MockRepository.GenerateStub<HttpContextBase>(); HttpContext.Stub(x => x.Request).Return(HttpRequest); HttpContext.User = _user; _httpResponse = MockRepository.GenerateStub<HttpResponseBase>(); _httpResponse.Stub(x => x.Cookies).Return(new HttpCookieCollection()); HttpContext.Stub(x => x.Response).Return(_httpResponse); Logger = MockRepository.GenerateStub<ILogger>(); WebAuthenticationService = MockRepository.GenerateStub<IWebAuthenticationService>(); MappingEngine = MockRepository.GenerateStub<IMappingEngine>(); AccountCreator = MockRepository.GenerateStub<IAccountCreator>(); AccountController = new AccountController(AccountService, Logger, WebAuthenticationService, MappingEngine, null, AccountCreator); AccountController.ControllerContext = new ControllerContext(HttpContext, new RouteData(), AccountController); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { User user = (User)httpContext.Session[WebConstants.UserSessionKey]; if (user == null) { httpContext.Response.Redirect("~/Account/login"); return false; } else { if (user.Code == "su") { return true; } if (string.IsNullOrWhiteSpace(Permissions)) { return true; } else { string[] permissionArray = Permissions.Split(AuthorizeAttributeSplitSymbol); foreach (string permission in permissionArray) { if (user.UrlPermissions.Contains(permission)) { return true; } } return false; } } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { bool isAdmin = false; var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized) { // the user is either not authenticated or // not in roles => no need to continue any further return false; } // get the currently logged on user var username = httpContext.User.Identity.Name; // get the id of the article that he is trying to manipulate // from the route data (this assumes that the id is passed as a route // data parameter: /foo/edit/123). If this is not the case and you // are using query string parameters you could fetch the id using the Request //var id = httpContext.Request.RequestContext.RouteData.Values["id"] as string; // Now that we have the current user and the id of the article he // is trying to manipualte all that's left is go ahead and look in // our database to see if this user is the owner of the article HLGranite.Mvc.Models.hlgraniteEntities db = new HLGranite.Mvc.Models.hlgraniteEntities(); HLGranite.Mvc.Models.User user = db.Users.Where(u => u.UserName.Equals(username)).FirstOrDefault(); if (user != null) isAdmin = user.IsAdmin; return isAdmin; }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (!base.AuthorizeCore(httpContext)) return false; return Permission.IsEmptyOrNull() || Authorization.HasPermission(Permission); }
public WebWorkContext(HttpContextBase httpContext, ICustomerService customerService, IVendorService vendorService, IStoreContext storeContext, IAuthenticationService authenticationService, ILanguageService languageService, ICurrencyService currencyService, IGenericAttributeService genericAttributeService, TaxSettings taxSettings, CurrencySettings currencySettings, LocalizationSettings localizationSettings, IUserAgentHelper userAgentHelper, IStoreMappingService storeMappingService) { this._httpContext = httpContext; this._customerService = customerService; this._vendorService = vendorService; this._storeContext = storeContext; this._authenticationService = authenticationService; this._languageService = languageService; this._currencyService = currencyService; this._genericAttributeService = genericAttributeService; this._taxSettings = taxSettings; this._currencySettings = currencySettings; this._localizationSettings = localizationSettings; this._userAgentHelper = userAgentHelper; this._storeMappingService = storeMappingService; }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (!httpContext.User.Identity.IsAuthenticated) return false; return httpContext.User.IsInRole(Roles); }
public string GetViewLocation(HttpContextBase httpContext, string key) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } return (string)httpContext.Cache[AlterKey(key)]; }
public override RouteData GetRouteData(HttpContextBase httpContext) { // locate appropriate shell settings for request var settings = _runningShellTable.Match(httpContext); // only proceed if there was a match, and it was for this client if (settings == null || settings.Name != _shellSettings.Name) return null; var effectiveHttpContext = httpContext; if (_urlPrefix != null) effectiveHttpContext = new UrlPrefixAdjustedHttpContext(httpContext, _urlPrefix); var routeData = _route.GetRouteData(effectiveHttpContext); if (routeData == null) return null; // otherwise wrap handler and return it routeData.RouteHandler = new RouteHandler(_workContextAccessor, routeData.RouteHandler, SessionState); routeData.DataTokens["IWorkContextAccessor"] = _workContextAccessor; if (IsHttpRoute) { routeData.Values["IWorkContextAccessor"] = _workContextAccessor; // for WebApi } return routeData; }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { Debug.WriteLine(httpContext.Request.HttpMethod == "GET"); return httpContext.Request.UserAgent != null && httpContext.Request.UserAgent.Contains(requiredUserAgent); }
/// <summary> /// Gets current page. /// </summary> /// <returns>Current page object.</returns> public IPage GetCurrentPage(HttpContextBase httpContext) { // TODO: remove it or optimize it. var http = new HttpContextTool(httpContext); var virtualPath = HttpUtility.UrlDecode(http.GetAbsolutePath()); return GetPageByVirtualPath(virtualPath) ?? new Page(); // TODO: do not return empty page, should implemented another logic. }
public virtual void Handle(HttpContextBase context) { string action = context.Request["action"]; try { if (!Handlers.ContainsKey(action)) throw new InvalidOperationException("Couln't find any handler for the action: " + action); IAjaxService service = Handlers[action]; if (service.RequiresEditAccess && !security.IsEditor(context.User)) throw new PermissionDeniedException(null, context.User); if (!service.IsValidHttpMethod(context.Request.HttpMethod)) throw new HttpException((int)HttpStatusCode.MethodNotAllowed, "This service requires HTTP POST method"); service.Handle(context); } catch (Exception ex) { Logger.ErrorFormat("AJAX {0}: {1}", action, ex.Message); context.Response.Status = ((int)HttpStatusCode.InternalServerError).ToString() + " Internal Server Error"; context.Response.Write(WriteException(ex, context.User)); } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { try { string url = httpContext.Request.Path; url = url.Substring(0, url.IndexOf("?") > 1 ? url.IndexOf("?") : url.Length); HttpCookie authcookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authcookie == null) { string token = httpContext.Request.Form["token"].ToString(); XXF.BasicService.CertCenter.CertCenterProvider ccp = new XXF.BasicService.CertCenter.CertCenterProvider(XXF.BasicService.CertCenter.ServiceCertType.manage); if (ccp.Auth(token)) { return true; } return false; } try { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authcookie.Value); string userid = ticket.Name.Split(' ').FirstOrDefault(); return true; } catch { return false; } } catch { return false; } }
public override ClaimsIdentity ProcessSignInResponse(string realm, string originalUrl, HttpContextBase httpContext) { var client = new FacebookClient(this.applicationId, this.secret); AuthenticationResult result; try { result = client.VerifyAuthentication(httpContext, this.MultiProtocolIssuer.ReplyUrl); } catch (WebException wex) { throw new InvalidOperationException(new StreamReader(wex.Response.GetResponseStream()).ReadToEnd(), wex); } var claims = new List<Claim> { new Claim(System.IdentityModel.Claims.ClaimTypes.NameIdentifier, result.ExtraData["id"]) }; foreach (var claim in result.ExtraData) { claims.Add(new Claim("http://schemas.facebook.com/me/" + claim.Key, claim.Value)); } return new ClaimsIdentity(claims, "Facebook"); }
public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model) { if (model.Exception != null) throw model.Exception; var client = model.AuthenticatedClient; var username = client.UserInformation.UserName; FormsAuthentication.SetAuthCookie(username, false); context.Response.AppendCookie(new HttpCookie("AccessToken", client.AccessToken.SecretToken) { Secure = !context.IsDebuggingEnabled, HttpOnly = true }); var urlHelper = new UrlHelper(((MvcHandler)context.Handler).RequestContext); var redirectUrl = string.Format("/{0}/", username); var cookie = context.Request.Cookies["returnUrl"]; if (cookie != null && urlHelper.IsLocalUrl(cookie.Value)) { redirectUrl = cookie.Value; cookie.Expires = DateTime.Now.AddDays(-1); context.Response.Cookies.Add(cookie); } return new RedirectResult(redirectUrl); }
protected override string RenderJsDependencies(IEnumerable<IClientDependencyFile> jsDependencies, HttpContextBase http, IDictionary<string, string> htmlAttributes) { if (!jsDependencies.Any()) return string.Empty; var sb = new StringBuilder(); if (http.IsDebuggingEnabled || !EnableCompositeFiles) { foreach (var dependency in jsDependencies) { sb.Append(RenderSingleJsFile(dependency.FilePath, htmlAttributes)); } } else { var comp = ClientDependencySettings.Instance.DefaultCompositeFileProcessingProvider.ProcessCompositeList(jsDependencies, ClientDependencyType.Javascript, http); foreach (var s in comp) { sb.Append(RenderSingleJsFile(s, htmlAttributes)); } } return sb.ToString(); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { bool authorized = false; if (httpContext.Session["username"] != null) { if (Roles.ToString() != "") { if (httpContext.Session["Role"].ToString().Equals("Super Admin") || httpContext.Session["Role"].ToString().Equals("Manager")) authorized = true; else { authorized = false; } } else { authorized = true; } } if (!authorized) { // The user is not authorized => no need to go any further return false; } return true; }
private static string GenerateClientUrlInternal(HttpContextBase httpContext, string contentPath) { if (String.IsNullOrEmpty(contentPath)) { return contentPath; } // can't call VirtualPathUtility.IsAppRelative since it throws on some inputs bool isAppRelative = contentPath[0] == '~'; if (isAppRelative) { string absoluteContentPath = VirtualPathUtility.ToAbsolute(contentPath, httpContext.Request.ApplicationPath); string modifiedAbsoluteContentPath = httpContext.Response.ApplyAppPathModifier(absoluteContentPath); return GenerateClientUrlInternal(httpContext, modifiedAbsoluteContentPath); } // we only want to manipulate the path if URL rewriting is active for this request, else we risk breaking the generated URL bool wasRequestRewritten = _urlRewriterHelper.WasRequestRewritten(httpContext); if (!wasRequestRewritten) { return contentPath; } // Since the rawUrl represents what the user sees in his browser, it is what we want to use as the base // of our absolute paths. For example, consider mysite.example.com/foo, which is internally // rewritten to content.example.com/mysite/foo. When we want to generate a link to ~/bar, we want to // base it from / instead of /foo, otherwise the user ends up seeing mysite.example.com/foo/bar, // which is incorrect. string relativeUrlToDestination = MakeRelative(httpContext.Request.Path, contentPath); string absoluteUrlToDestination = MakeAbsolute(httpContext.Request.RawUrl, relativeUrlToDestination); return absoluteUrlToDestination; }
public void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } httpContext.Cache.Insert(AlterKey(key), virtualPath, new CacheDependency(HostingEnvironment.MapPath("~/Themes"))); }
internal static IDictionary<UnityPerWebRequestLifetimeManager, object> GetInstances(HttpContextBase httpContext) { IDictionary<UnityPerWebRequestLifetimeManager, object> instances; if (httpContext.Items.Contains(Key)) { instances = (IDictionary<UnityPerWebRequestLifetimeManager, object>)httpContext.Items[Key]; } else { lock (httpContext.Items) { if (httpContext.Items.Contains(Key)) { instances = (IDictionary<UnityPerWebRequestLifetimeManager, object>)httpContext.Items[Key]; } else { instances = new Dictionary<UnityPerWebRequestLifetimeManager, object>(); httpContext.Items.Add(Key, instances); } } } return instances; }
public async Task<bool> CreateAndSignInExternalUser( HttpContextBase context, string logOnProvider, IUser user, string role, bool persist) { if (user == null) { throw new ArgumentNullException("user"); } var identity = await GetExternalIdentity(context); if (!VerifyExternalIdentity(identity, logOnProvider)) { return false; } var providerKey = identity.FindFirstValue( "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"); if (!(await storeManager.CreateExternalUser( user, logOnProvider, providerKey, role))) { return false; } await SignIn(context, user.Id, identity.Claims, persist); return true; }
public CultureSelectorResult GetCulture(HttpContextBase context) { if (context == null || ContextHelpers.IsRequestAdmin(context)) return null; // Attempt to determine culture by previous route if by POST string path; if (context.Request.HttpMethod.Equals(HttpVerbs.Post.ToString(), StringComparison.OrdinalIgnoreCase)) { if (context.Request.UrlReferrer != null) path = context.Request.UrlReferrer.AbsolutePath; else return null; } else { path = context.Request.Path; } var appPath = context.Request.ApplicationPath ?? "/"; var requestUrl = (path.StartsWith(appPath) ? path.Substring(appPath.Length) : path).TrimStart('/'); var content = GetByPath(requestUrl); if (content != null) { return new CultureSelectorResult { Priority = -2, CultureName = _localizationService.Value.GetContentCulture(content) }; } return null; }
internal UrlBuilder(HttpContextBase httpContext, VirtualPathUtilityBase virtualPathUtility, string path, object parameters) { _virtualPathUtility = virtualPathUtility; Uri uri; if (Uri.TryCreate(path, UriKind.Absolute, out uri)) { _path = uri.GetLeftPart(UriPartial.Path); _params.Append(uri.Query); } else { // If the url is being built as part of a WebPages request, use the template stack to identify the current template's virtual path. _path = GetPageRelativePath(httpContext, path); int queryStringIndex = (_path ?? String.Empty).IndexOf('?'); if (queryStringIndex != -1) { _params.Append(_path.Substring(queryStringIndex)); _path = _path.Substring(0, queryStringIndex); } } if (parameters != null) { AddParam(parameters); } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } else { if (httpContext.User.Identity.IsAuthenticated) { string strOwnerPermission; if (httpContext.Session["Permissons"] == null) { FormsIdentity formId = (FormsIdentity)httpContext.User.Identity; FormsAuthenticationTicket Ticket = formId.Ticket; var userdata = Encoding.Default.GetString(Convert.FromBase64String(Ticket.UserData)); strOwnerPermission = userdata; httpContext.Session["Permissons"] = Ticket.UserData; } else { strOwnerPermission = httpContext.Session["Permissons"].ToString(); } //if (strOwnerPermission == Permissons) return true; } httpContext.Response.StatusCode = 403; return false; } }
public bool AddToBasket(HttpContextBase httpContext, int productId, int quantity) { bool success = true; Basket basket = GetBasket(httpContext); BasketItem item = basket.BasketItems.FirstOrDefault(i => i.ProductId == productId); if (item == null) { item = new BasketItem() { BasketId = basket.BasketId, ProductId = productId, Quantity = quantity }; basket.AddBasketItem(item); } else { item.Quantity = item.Quantity + quantity; } baskets.Commit(); return success; }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (!CheckAuthToken(httpContext.Request.Headers)) return false; return base.AuthorizeCore(httpContext); }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (routeDirection == RouteDirection.UrlGeneration) { return true; } object versionValue; if (!values.TryGetValue(parameterName, out versionValue)) { return true; } if (versionValue == null || versionValue == UrlParameter.Optional) { return true; } string versionText = versionValue.ToString(); if (versionText.Length == 0) { return true; } SemanticVersion ignored; return SemanticVersion.TryParse(versionText, out ignored); }
/// <summary> /// Ensures that the user must be logged in or that the application is not configured just yet. /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } try { //if its not configured then we can continue if (!_applicationContext.IsConfigured) { return true; } //otherwise we need to ensure that a user is logged in var isLoggedIn = BasePage.ValidateUserContextID(BasePage.umbracoUserContextID); if (isLoggedIn) { return true; } return false; } catch (Exception) { return false; } }
public override void ProcessSignInRequest(Scope scope, HttpContextBase httpContext) { httpContext.ApplicationInstance.CompleteRequest(); HttpContext.Current.Response.Redirect(this.GetAuthorizationLink()); HttpContext.Current.ApplicationInstance.CompleteRequest(); }
public Subject GetCurrentSubject(PageItem pageItem, HttpContextBase httpContext) { var subjectId = httpContext.Request.RawUrl; if (httpContext.Items["Comments.SubjectId"] != null) { subjectId = httpContext.Items["Comments.SubjectId"].ToString(); } var subject = new Subject { Id = subjectId }; var page = httpContext.CurrentHandler as Page; if (page != null) { subject.Title = page.Title; } if (httpContext.Items["Comments.SubjectTitle"] != null) { subject.Title = httpContext.Items["Comments.SubjectTitle"].ToString(); } if (httpContext.Items["Comments.SubjectType"] != null) { subject.Type = httpContext.Items["Comments.SubjectType"].ToString(); } return subject; }