Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NancySentryRequest"/> class.
        /// </summary>
        /// <param name="httpContext">The HTTP context.</param>
        internal NancySentryRequest(NancyContext httpContext)
        {
            this.httpContext = httpContext;

            if (!HasHttpContext || this.httpContext.Request == null)
                return;

            // Url and Method
            Url = this.httpContext.Request.Url.ToString();
            Method = this.httpContext.Request.Method;
            Data = this.httpContext.Request.Form;

            // QueryString
            string qs = string.Empty;
            foreach (var item in this.httpContext.Request.Query)
                qs += item + "=" + this.httpContext.Request.Query[item] + "&";

            QueryString = qs.TrimEnd(new[] { '&' });

            // Cookies
            Cookies = this.httpContext.Request.Cookies;

            // Headers
            Headers = this.httpContext.Request.Headers.Select(s => new
            {
                Key = s.Key,
                Value = s.Value.Aggregate(new StringBuilder(), (stringBuilder, argument) =>
                {
                    stringBuilder.Append(argument);
                    stringBuilder.Append(" ");
                    return stringBuilder;
                }).ToString().TrimEnd(new[] { ' ' })
            }).ToDictionary(k => k.Key, v => v.Value);
        }
Ejemplo n.º 2
0
    public override Response ProcessRequest(NancyContext context)
    {
      if (!context.Request.Url.Path.StartsWith(HandlerRoot, StringComparison.InvariantCultureIgnoreCase))
      {
        return null;
      }

      var path = context.Request.Url.Path.Remove(0, HandlerRoot.Length + 1);
      var match = Regex.Match(path, @"^(?<filename>.*)_[a-z0-9]+_(?<extension>[a-z]+)$", RegexOptions.IgnoreCase);
      if (match.Success == false)
      {
        if (Logger != null) Logger.Error("RawFileRouteHandler.ProcessRequest : Invalid file path in URL '{0}'", path);
        return null;
      }
      var extension = match.Groups["extension"].Value;

      var filePath = Path.Combine(applicationRoot, string.Concat(match.Groups["filename"].Value, ".", extension).Replace('/', '\\'));
      if (!File.Exists(filePath))
      {
        if (Logger != null) Logger.Error("RawFileRouteHandler.ProcessRequest : Raw file does not exist '{0}'", filePath);
        return null;
      }

      var response = new StreamResponse(() => File.OpenRead(filePath), MimeTypes.GetMimeType(filePath));
      if (Logger != null) Logger.Trace("RawFileRouteHandler.ProcessRequest : Returned response for '{0}'", context.Request.Url.Path);
      return response;
    }
        public void Handle_WhenTestContextIsSetOnTheRepository_DoesNotLogTheTextContext()
        {
            const string testContext = "EventsApiConsumerTests.GetAllEvents_WhenCalled_ReturnsAllEvents";
            var headers = new Dictionary<string, IEnumerable<string>>
            {
                { Constants.AdministrativeRequestTestContextHeaderKey, new List<string> { testContext } }
            };

            var context = new NancyContext
            {
                Request = new Request("DELETE", new Url
                {
                    Path = "/interactions",
                    Scheme = "http"
                }, null, headers)
            };

            var handler = GetSubject();

            _mockProviderRepository.TestContext.Returns(testContext);

            handler.Handle(context);

            _mockLog.Received(0).Log(LogLevel.Info, Arg.Any<Func<string>>(), null, Arg.Is<object[]>(x => x.Single() == testContext));
        }
Ejemplo n.º 4
0
        private void CompressResponse(NancyContext context)
        {
            var request = context.Request;
            var response = context.Response;

            try
            {
                if (
                   !response.ContentType.Contains("image")
                && !response.ContentType.Contains("font")
                && request.Headers.AcceptEncoding.Any(x => x.Contains("gzip"))
                && !AlreadyGzipEncoded(response)
                && !ContentLengthIsTooSmall(response))
                {
                    var contents = response.Contents;

                    response.Headers["Content-Encoding"] = "gzip";
                    response.Contents = responseStream =>
                    {
                        using (var gzip = new GZipStream(responseStream, CompressionMode.Compress, true))
                        using (var buffered = new BufferedStream(gzip, 8192))
                        {
                            contents.Invoke(buffered);
                        }
                    };
                }
            }

            catch (Exception ex)
            {
                _logger.Error(ex, "Unable to gzip response");
                throw;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Perform any initialisation tasks
        /// </summary>
        /// <param name="pipelines">Application pipelines</param>
        /// <param name="context">The current context</param>
        public void Initialize(IPipelines pipelines, NancyContext context)
        {
            // On each request, store the NancyContext in the LogicalCallContext
            CallContext.LogicalSetData(NancyConfiguration.NancyContextDataSlot, context);

            var nancyConfiguration = NancyConfiguration.Settings;
            if (nancyConfiguration == null)
                return;

            var name = nancyConfiguration.PipelineName.Value;
            var sharpRaven = new PipelineItem(name, (nancyContext, exception) =>
            {
                if (nancyConfiguration.CaptureExceptionOnError.Value)
                {
                    var guid = this.ravenClient.CaptureException(exception);

                    if (guid != null)
                    {
                        context.Items.Add(NancyConfiguration.SentryEventGuidKey, guid);
                        exception.Data.Add(NancyConfiguration.SentryEventGuidKey, guid);
                    }
                }

                return null;
            });

            pipelines.OnError.AddItemToStartOfPipeline(sharpRaven);
        }
        public void Handle(Nancy.HttpStatusCode statusCode, Nancy.NancyContext context)
        {
            if (context.Request.Headers.Accept.Count() == 0)
            {
                return;
            }

            if (context.Request.Headers.Accept.First().Item1.Contains("/json") ||
                context.Request.Headers.Accept.First().Item1.Contains("/xml"))
            {
                return;
            }

            // this is most probably XmlHttpRequest
            if (context.Request.Method == "PATCH" ||
                context.Request.Method == "DELETE")
            {
                return;
            }

            if (context.Request.Method == "GET" ||
                context.Request.Method == "POST" ||
                context.Request.Headers.UserAgent.Contains("Mozilla") ||
                context.Request.Headers.UserAgent.Contains("WebKit") ||
                context.Request.Headers.UserAgent.Contains("Trident"))
            {
                var response = _renderer.RenderView(context, "Codes/" + (int)statusCode);
                response.StatusCode  = statusCode;
                response.ContentType = "text/html; charset=utf-8";
                context.Response     = response;
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Transmogrify original response and apply JSONP Padding
        /// </summary>
        /// <param name="context">Current Nancy Context</param>
        private static void PrepareJsonp(NancyContext context)
        {
            var isJson = Json.Json.IsJsonContentType(context.Response.ContentType);
            bool hasCallback = context.Request.Query["callback"].HasValue;

            if (!isJson || !hasCallback)
            {
                return;
            }

            // grab original contents for running later
            var original = context.Response.Contents;
            string callback = context.Request.Query["callback"].Value;

            // set content type to application/javascript so browsers can handle it by default
            // http://stackoverflow.com/questions/111302/best-content-type-to-serve-jsonp
            context.Response.ContentType = string.Concat("application/javascript", Encoding);

            context.Response.Contents = stream =>
            {
                // disposing of stream is handled elsewhere
                var writer = new StreamWriter(stream)
                {
                    AutoFlush = true
                };

                writer.Write("{0}(", callback);
                original(stream);
                writer.Write(");");
            };
        }
Ejemplo n.º 8
0
 public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)
 {
     if (!cachedUsers.ContainsKey(identifier))
         return null;
     User info = cachedUsers[identifier];
     return new UserIndentity {UserName = info.Login, Claims = new List<string> {info.Role.ToString()}, AuthId = identifier};
 }
Ejemplo n.º 9
0
        static object DeleteMember(
            NancyContext context,
            IDocumentSession documentSession,
            string alias)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (documentSession == null) throw new ArgumentNullException("documentSession");

            if (String.IsNullOrEmpty(alias))
                return 404;

            if (!context.IsSignedUp())
                return 403;

            var memberToDelete = documentSession.GetMemberByAlias(alias);
            if (memberToDelete == null)
                return 404;

            var currentMember = context.GetCurrentMember(documentSession);
            Debug.Assert(currentMember != null, "`requireSignedUp()` should ensure the current member is not null.");

            if (!memberToDelete.Alias.Equals(currentMember.Alias, StringComparison.OrdinalIgnoreCase))
                return 403;

            documentSession.DeleteMember(memberToDelete.Id);

            context.SetAlert("Your membership was deleted.", type: AlertType.Success);

            context.SignOutOfTwitter();

            return context.Redirect(Paths.Home());
        }
Ejemplo n.º 10
0
        public bool IsCacheable(NancyContext context)
        {
            if (!RuntimeInfoBase.IsProduction)
            {
                return false;
            }

            if (((DynamicDictionary)context.Request.Query).ContainsKey("h")) return true;

            if (context.Request.Path.StartsWith("/api", StringComparison.CurrentCultureIgnoreCase))
            {
                if (context.Request.Path.ContainsIgnoreCase("/MediaCover")) return true;

                return false;
            }

            if (context.Request.Path.StartsWith("/signalr", StringComparison.CurrentCultureIgnoreCase)) return false;
            if (context.Request.Path.EndsWith("main.js")) return false;
            if (context.Request.Path.StartsWith("/feed", StringComparison.CurrentCultureIgnoreCase)) return false;

            if (context.Request.Path.StartsWith("/log", StringComparison.CurrentCultureIgnoreCase) &&
                context.Request.Path.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase))
            {
                return false;
            }

            if (context.Response != null)
            {
                if (context.Response.ContentType.Contains("text/html")) return false;
            }

            return true;
        }
Ejemplo n.º 11
0
        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(requestContainer, pipelines, context);

            // At request startup we modify the request pipelines to
            // include forms authentication - passing in our now request
            // scoped user name mapper.
            //
            // The pipelines passed in here are specific to this request,
            // so we can add/remove/update items in them as we please.
            var loginService = requestContainer.Resolve<LoginService>();
            var authConfiguration =
                new StatelessAuthenticationConfiguration(c =>
                {
                    var apiKeyFromRequest = ((DynamicDictionaryValue)c.Request.Query.ApiKey).Value as ApiKey
                        ?? ((DynamicDictionaryValue)c.Request.Form.ApiKey).Value as ApiKey;

                    if (apiKeyFromRequest == null) return null;

                    if (loginService.IsApiKeyValid(apiKeyFromRequest))
                    {
                        return new UserIdentity(apiKeyFromRequest.Username, new List<string>());
                    }
                    return null;
                });

            StatelessAuthentication.Enable(pipelines, authConfiguration);
        }
Ejemplo n.º 12
0
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            var formsAuthConfig = new FormsAuthenticationConfiguration
            {
                RedirectUrl = "~/login",
                UserMapper = container.Resolve<IUserMapper>()
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfig);

            pipelines.AfterRequest += ctx =>
            {
                var dbContext = container.Resolve<SmartFlowContext>();
                dbContext.SaveChanges();
            };

            pipelines.OnError += (ctx, ex) =>
            {
                var logger = container.Resolve<TextFileLogger>();
                logger.Write("Error", Enums.LogLevel.ApplicationError, ex);
                return ErrorResponse.FromException(ex);
            };

            base.RequestStartup(container, pipelines, context);
        }
        public static RequestInfo Collect(NancyContext context, ExceptionlessClient client) {
            if (context == null)
                return null;

            var info = new RequestInfo {
                ClientIpAddress = context.Request.UserHostAddress,
                HttpMethod = context.Request.Method
            };

            if (context.Request.Headers.UserAgent != null)
                info.UserAgent = context.Request.Headers.UserAgent;

            if (context.Request.Url != null) {
                info.Host = context.Request.Url.HostName;
                info.IsSecure = context.Request.Url.IsSecure;
                info.Path = context.Request.Url.BasePath + context.Request.Url.Path;
                info.Port = context.Request.Url.Port ?? 80;
            }

            if (context.Request.Headers.Referrer != null)
                info.Referrer = context.Request.Headers.Referrer;

            info.Cookies = context.Request.Cookies.ToDictionary(client);

            if (context.Request.Url != null && !String.IsNullOrWhiteSpace(context.Request.Url.Query))
                info.QueryString = HttpUtility.ParseQueryString(context.Request.Url.Query).ToDictionary(client);

            return info;
        }
Ejemplo n.º 14
0
 // The bootstrapper enables you to reconfigure the composition of the framework,
 // by overriding the various methods and properties.
 // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper
 //protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
 //{
 //    // No registrations should be performed in here, however you may
 //    // resolve things that are needed during application startup.
 //}
 //protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer)
 //{
 //    // Perform registration that should have an application lifetime
 //}
 protected override void ConfigureRequestContainer(ILifetimeScope container, NancyContext context)
 {
     // Perform registrations that should have a request lifetime
     var builder = new ContainerBuilder();
     builder.RegisterModule(new ServicesModule());
     builder.Update(container.ComponentRegistry);
 }
Ejemplo n.º 15
0
    public Response RunCassetteRequestHandler(NancyContext context)
    {
      try
      {

        logger.Info("RunCassetteRequestHandler : {0}", context.Request.Path);

        if (!context.Request.Path.StartsWith(string.Concat("/", UrlModifier.CassettePrefix)))
          return null;

        var requestPath = context.Request.Path.Substring(UrlModifier.CassettePrefix.Length);

        if (String.IsNullOrWhiteSpace(requestPath) || requestPath == "/")
        {
          var diagnosticsHandler = Container.Resolve<ICassetteRequestHandler>(DiagnosticRequestHandler.PathPrefix);
          return diagnosticsHandler.ProcessRequest(context, requestPath);
        }

        return CallPathHandler(context, requestPath);


      }
      catch (Exception ex)
      {
        logger.FatalException(string.Format("RunCassetteRequestHandler : {0} : {1}", ex.GetType(), ex.Message), ex);
        return null;
      }
    }
        public void Handle_WhenExpectedResponseHasNotBeenSet_ResponseMapperIsCalledAndReturns500Response()
        {
            var nancyContext = new NancyContext
            {
                Request = new Request("GET", "/", "HTTP")
            };

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction { Request = new ProviderServiceRequest(), Response = null }
            };

            nancyContext.SetMockInteraction(interactions);

            var mockRequestMapper = Substitute.For<IProviderServiceRequestMapper>();
            var mockResponseMapper = Substitute.For<INancyResponseMapper>();
            var mockProviderRepository = Substitute.For<IMockProviderRepository>();

            mockResponseMapper.Convert(Arg.Any<ProviderServiceResponse>())
                .Returns(new Response
                {
                    StatusCode = HttpStatusCode.InternalServerError
                });

            IMockProviderRequestHandler handler = new MockProviderRequestHandler(mockRequestMapper, mockResponseMapper, mockProviderRepository);

            var result = handler.Handle(nancyContext);

            mockResponseMapper.Received(1).Convert(Arg.Is<ProviderServiceResponse>(x => x.Status == 500));
            Assert.Equal(HttpStatusCode.InternalServerError, result.StatusCode);
        }
Ejemplo n.º 17
0
        private NancyModule GetInitializedModuleForMatch(NancyContext context, RouteCandidate routeMatchToReturn)
        {
            var module =
                this.nancyModuleCatalog.GetModuleByKey(routeMatchToReturn.Item1, context);

            return(this.moduleBuilder.BuildModule(module, context));
        }
        protected override void RequestStartup(IWindsorContainer container, IPipelines pipelines, NancyContext context)
        {
            //var formsAuthConfiguration = new FormsAuthenticationConfiguration
            //{
            //    RedirectUrl = "/login",
            //    UserMapper = container.Resolve<IUserMapper>(),
            //};
            //FormsAuthentication.Enable(pipelines, formsAuthConfiguration);

            pipelines.BeforeRequest.AddItemToEndOfPipeline(ctx =>
            {
                if (ctx.CurrentUser != null) ctx.ViewBag.UserName = ctx.CurrentUser.UserName;
                return null;
            });

            pipelines.BeforeRequest.AddItemToStartOfPipeline(nancyContext =>
            {
                //nancyContext.Request.Headers.UserAgent = "Lightstone";
                var token = "";
                var cookie = nancyContext.Request.Headers.Cookie.FirstOrDefault(x => (x.Name + "").ToLower() == "token");
                if (cookie != null)
                    token = HttpUtility.UrlDecode(cookie.Value);
                    //nancyContext.Request.Headers.Authorization = "Token {0}".FormatWith(HttpUtility.UrlDecode(token.Value));

                var user = container.Resolve<ITokenizer>().Detokenize(token, nancyContext, new DefaultUserIdentityResolver());
                if (user != null)
                    nancyContext.CurrentUser = user;
                return null;
            });
            TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration(container.Resolve<ITokenizer>()));
        }
        private static Response OnError(NancyContext context, Exception exception) {
            var contextData = new Dictionary<string, object> { { NANCY_CONTEXT, context } };

            ExceptionlessClient.Current.ProcessUnhandledException(exception, "NancyPipelineException", true, contextData);

            return context.Response;
        }
 private void AttachErrorResponse(NancyContext ctx)
 {
     if (ctx.ModelValidationResult.Errors.Count > 0)
     {
         ctx.Response.StatusCode = HttpStatusCode.BadRequest;
     }
 }
Ejemplo n.º 21
0
        private string GetHtmlLinks(NancyContext context)
        {
            var routeCache = this.routeCacheProvider.GetCache();
            if (routeCache == null)
                return String.Empty;

            StringBuilder linkBuilder = new StringBuilder();

            var routesWithMetadata = routeCache
                .Select(r => r.Value)
                .SelectMany(r => r.Select(t => t.Item2))
                .Where(r => r.Metadata != null && r.Metadata.Has<PomonaRouteMetadata>());

            foreach (var route in routesWithMetadata)
            {
                var metadata = route.Metadata.Retrieve<PomonaRouteMetadata>();
                var rel = String.Concat("http://pomona.io/rel/", metadata.Relation);
                var contentType = metadata.ContentType;
                var methods = metadata.Method.ToString().ToUpperInvariant();
                var href = context.Request.Url.BasePath + route.Path;

                linkBuilder.AppendFormat("<link rel=\"{0}\" type=\"{1}\" methods=\"{2}\" href=\"{3}\">{4}",
                                         rel,
                                         contentType,
                                         methods,
                                         href,
                                         Environment.NewLine);
            }

            return linkBuilder.ToString();
        }
Ejemplo n.º 22
0
 protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
 {
     base.ConfigureRequestContainer(container, context);
     var ctx = new SmartFlowContext();
     container.Register(ctx);
     container.Register<IUserMapper, SmartFlowAuthService>();
 }
        public Response Handle(NancyContext context)
        {
            try
            {
                var response = HandlePactRequest(context);

                return response;
            }
            catch (Exception ex)
            {
                var exceptionMessage = ex.Message
                    .Replace("\r", " ")
                    .Replace("\n", "")
                    .Replace("\t", " ")
                    .Replace(@"\", "");

                var errorResponse = new ProviderServiceResponse
                {
                    Status = 500,
                    Body = exceptionMessage
                };
                var response = _responseMapper.Convert(errorResponse);
                response.ReasonPhrase = exceptionMessage;

                return response;
            }
        }
Ejemplo n.º 24
0
    public void RewriteResponseContents(NancyContext context)
    {
      if (!context.Response.ContentType.Equals("text/html"))
      {
        // Only html needs to be (possibly) rewritten
        return;
      }
      var currentContents = context.Response.Contents;
      context.Response.Contents =
        stream =>
        { 
          var placeholderTracker = Container.Resolve<IPlaceholderTracker>();

          var currentContentsStream = new MemoryStream();
          currentContents(currentContentsStream);
          var reader = new StreamReader(currentContentsStream);

          reader.BaseStream.Seek(0, SeekOrigin.Begin);
          var writer = new StreamWriter(stream);
          
          writer.Write(placeholderTracker.ReplacePlaceholders(reader.ReadToEnd()));
          
          writer.Flush();
        };
    }
        protected override void RequestStartup(IWindsorContainer container, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(container, pipelines, context);

            pipelines.BeforeRequest.AddItemToEndOfPipeline(nancyContext =>
            {
                this.Info(() => "Monitoring API invoked at {0}[{1}]".FormatWith(nancyContext.Request.Method, nancyContext.Request.Url));
                var token = "";
                var cookie = nancyContext.Request.Headers.Cookie.FirstOrDefault(x => (x.Name + "").ToLower() == "token");
                if (cookie != null)
                    token = HttpUtility.UrlDecode(cookie.Value);

                nancyContext.Request.Headers.Authorization = "Token {0}".FormatWith(token);

                var user = container.Resolve<ITokenizer>().Detokenize(token, nancyContext, new DefaultUserIdentityResolver());
                if (user != null)
                {
                    nancyContext.CurrentUser = user;
                }
                return null;
            });

            pipelines.OnError.AddItemToEndOfPipeline((nancyContext, exception) =>
            {
                this.Error(() => "Error on Monitoring request {0}[{1}] => {2}".FormatWith(nancyContext.Request.Method, nancyContext.Request.Url, exception));
                return ErrorResponse.FromException(exception);
            });
            TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration(container.Resolve<ITokenizer>()));

            pipelines.OnError.AddItemToEndOfPipeline((nancyContext, exception) =>
            {
                this.Error(() => "Error on Monitoring request {0}[{1}] => {2}".FormatWith(nancyContext.Request.Method, nancyContext.Request.Url, exception));
                return ErrorResponse.FromException(exception);
            });
        }
Ejemplo n.º 26
0
        static object GetMember(
            NancyContext context,
            IDocumentSession documentSession,
            string alias)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (documentSession == null) throw new ArgumentNullException("documentSession");

            if (String.IsNullOrEmpty(alias))
                return 404;

            if (!context.IsSignedUp())
                return 403;

            var member = documentSession.GetMemberByAlias(alias);
            if (member == null)
                return 404;

            var currentMember = context.GetCurrentMember(documentSession);
            Debug.Assert(currentMember != null, "`requireSignedUp()` should ensure the current member is not null.");
            if (!member.Alias.Equals(currentMember.Alias, StringComparison.OrdinalIgnoreCase))
                return 403;

            var rooms = documentSession.GetRoomsByOwner(member.Id);

            return new MemberResponse(member, rooms);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Adds the current response to the cache if required
        /// Only stores by Path and stores the response in a dictionary.
        /// Do not use this as an actual cache :-)
        /// </summary>
        /// <param name="context">Current context</param>
        public void SetCache(NancyContext context)
        {
            if (context.Response.StatusCode != HttpStatusCode.OK)
            {
                return;
            }

            object cacheSecondsObject;
            if (!context.Items.TryGetValue(ContextExtensions.OUTPUT_CACHE_TIME_KEY, out cacheSecondsObject))
            {
                return;
            }

            int cacheSeconds;
            if (!int.TryParse(cacheSecondsObject.ToString(), out cacheSeconds))
            {
                return;
            }

            var cachedResponse = new CachedResponse(context.Response);

            this.cachedResponses[context.Request.Path] = new Tuple<DateTime, Response, int>(DateTime.Now, cachedResponse, cacheSeconds);

            context.Response = cachedResponse;
        }
Ejemplo n.º 28
0
        protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
        {
            base.ConfigureRequestContainer(container, context);

            container.Register<IUserMapper, FakeRepository>();
            container.Register<IRepository, FakeRepository>();
        }
Ejemplo n.º 29
0
        public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)
        {
            string userGuid = identifier.ToString();
            var user = this.Repository.Find<User>(x => x.Guid == userGuid).SingleOrDefault();

            return user == null ? null : new PlayerIdentity() { UserName = user.Id.ToString() };
        }
Ejemplo n.º 30
0
    public void CacheCheck(NancyContext context)
    {

      var responseHeaders = context.Response.Headers;
      var requestHeaders = context.Request.Headers;

      string currentFileEtag;
      if (responseHeaders.TryGetValue("ETag", out currentFileEtag))
      {
        if (requestHeaders.IfNoneMatch.Contains(currentFileEtag))
        {
          context.Response = HttpStatusCode.NotModified;
          return;
        }
      }

      string responseLastModifiedString;
      if (responseHeaders.TryGetValue("Last-Modified", out responseLastModifiedString))
      {
        var responseLastModified = DateTime.ParseExact(responseLastModifiedString, "R", CultureInfo.InvariantCulture, DateTimeStyles.None);
        if (responseLastModified <= requestHeaders.IfModifiedSince)
        {
          context.Response = HttpStatusCode.NotModified;
        }
      }
    }
Ejemplo n.º 31
0
        public ResolveResult Resolve(NancyContext context)
        {
            var results = this.trie.GetMatches(GetMethod(context), context.Request.Path, context);

            if (!results.Any())
            {
                if (this.IsOptionsRequest(context))
                {
                    return this.BuildOptionsResult(context);
                }
                return this.GetNotFoundResult(context);
            }

            // Sort in descending order
            Array.Sort(results, (m1, m2) => -m1.CompareTo(m2));

            for (var index = 0; index < results.Length; index++)
            {
                var matchResult = results[index];
                if (matchResult.Condition == null || matchResult.Condition.Invoke(context))
                {
                    return this.BuildResult(context, matchResult);
                }
            }

            return this.GetNotFoundResult(context);
        }
Ejemplo n.º 32
0
 public bool HandlesStatusCode(Nancy.HttpStatusCode statusCode, Nancy.NancyContext context)
 {
     return
         ((statusCode == HttpStatusCode.Forbidden) ||
          (statusCode == HttpStatusCode.NotFound) ||
          (statusCode == HttpStatusCode.InternalServerError) ||
          (statusCode == HttpStatusCode.Locked));
 }
Ejemplo n.º 33
0
        public void Handle(Nancy.HttpStatusCode statusCode, Nancy.NancyContext context)
        {
            var response = viewRenderer.RenderView(context, "Error", new ErrorViewModel {
                Code = (int)statusCode
            });

            response.StatusCode = statusCode;
            context.Response    = response;
        }
Ejemplo n.º 34
0
        private ResolveResult CreateRouteAndParametersFromMatch(NancyContext context, RouteCandidate routeMatchToReturn)
        {
            var associatedModule =
                this.GetInitializedModuleForMatch(context, routeMatchToReturn);

            var route = associatedModule.Routes.ElementAt(routeMatchToReturn.Item2);

            return(new ResolveResult(route, routeMatchToReturn.Item4.Parameters, associatedModule.Before, associatedModule.After, associatedModule.OnError));
        }
        private void ModifyResult(Nancy.NancyContext ctx)
        {
            var myIndexWatch = Int32.Parse(ctx.Items["X-watch"].ToString());

            lock (_lock)
            {
                var myWatch = _watch[myIndexWatch];
                myWatch.Stop();
                var elapsedMs = myWatch.ElapsedMilliseconds;
                _watch.RemoveAt(myIndexWatch);
                Console.WriteLine(ctx.Request.Method + " " + ctx.Request.Path + ": " + elapsedMs + " miliseconds");
            }
        }
Ejemplo n.º 36
0
        private void SetCookieDomain(Nancy.NancyContext ctx)
        {
            string domainName = System.Configuration.ConfigurationManager.AppSettings["Domain"];

            if (domainName == null || domainName.Trim() == string.Empty)
            {
                return;
            }

            foreach (Nancy.Cookies.INancyCookie cookie in ctx.Response.Cookies)
            {
                cookie.Domain = domainName;
            }
        }
        private Nancy.Response CheckSomething(Nancy.NancyContext ctx)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();

            lock (_lock)
            {
                _watch.Add(watch);
                _watch.Insert(nextId, watch);
                ctx.Items.Add("X-watch", nextId);
                nextId++;
            }

            // if you return null, nancy will proceed to module
            return(null);
        }
Ejemplo n.º 38
0
        HttpClient CreateProxyClient(Nancy.NancyContext context)
        {
            var handler = new HttpClientHandler();

            handler.AllowAutoRedirect = false;
            var client = new HttpClient(handler);

            foreach (var header in Context.Request.Headers)
            {
                //Log.Debug("{key}: {value}", header.Key, header.Value);
                if (_skipHeaders.Contains(header.Key)) // host header causes 400 invalid host error
                {
                    continue;
                }
                client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            // client.DefaultRequestHeaders.Add("X-Forwarded-For", <UserHostAddress>); // TODO: see RequestLogEnricher.GetUserIPAddress()
            client.DefaultRequestHeaders.Add("X-Compute-Id", Context.Items["RequestId"] as string);
            client.DefaultRequestHeaders.Add("X-Compute-Host", Context.Items["Hostname"] as string);
            return(client);
        }
Ejemplo n.º 39
0
        Nancy.Response CreateProxyResponse(HttpResponseMessage backendResponse, Nancy.NancyContext context)
        {
            string responseBody = backendResponse.Content.ReadAsStringAsync().Result;
            var    response     = (Nancy.Response)responseBody;

            response.StatusCode = (Nancy.HttpStatusCode)backendResponse.StatusCode;
            foreach (var header in backendResponse.Headers)
            {
                foreach (var value in header.Value)
                {
                    response.Headers.Add(header.Key, value);
                }
            }
            foreach (var header in backendResponse.Content.Headers)
            {
                foreach (var value in header.Value)
                {
                    response.Headers.Add(header.Key, value);
                }
            }
            return(response);
        }
Ejemplo n.º 40
0
 private bool EnableTracing(NancyContext ctx)
 {
     return(StaticConfiguration.EnableRequestTracing &&
            !ctx.Items.ContainsKey(DiagnosticsHook.ItemsKey));
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Check if the error handler can handle errors of the provided status code.
 /// </summary>
 /// <param name="statusCode">The HTTP status code.</param>
 /// <param name="context">The <see cref="NancyContext" /> instance of the current request.</param>
 /// <returns>
 /// <c>true</c> if if the instance handles the specified HTTP status code.
 /// </returns>
 public bool HandlesStatusCode(HttpStatusCode statusCode, Nancy.NancyContext context)
 {
     return(statusCode == HttpStatusCode.NotFound || statusCode == HttpStatusCode.InternalServerError);
 }
Ejemplo n.º 42
0
 protected override void ConfigureRequestContainer(TinyIoCContainer _container, Nancy.NancyContext _context)
 {
     base.ConfigureRequestContainer(_container, _context);
     _container.Register <IUserMapper, UserMapper>();
 }
 protected override void ConfigureRequestContainer(
     Nancy.TinyIoc.TinyIoCContainer container, Nancy.NancyContext context)
 {
     base.ConfigureRequestContainer(container, context);
 }
Ejemplo n.º 44
0
 public static string GetLastName(this Nancy.NancyContext context) => context.CurrentUser?.FindFirst(_ => _.Type == "family_name")?.Value;
Ejemplo n.º 45
0
        public ResolveResult Resolve(NancyContext context)
        {
            AreaConfigs areaConfigs;

            // We are leveraging sort of a hack of Nancy's routing system. Protect from direct access to internal paths.
            if (context.Request.Path.StartsWith(Constants.ResolverAreaPrefix) || context.Request.Path.StartsWith(Constants.ResolverAdminAreaPrefix))
            {
                return(new ResolveResult(new NotFoundRoute(context.Request.Method, context.Request.Path), DynamicDictionary.Empty, null, null, null));
            }

            // First, try resolving the admin area. By convention, it is always "admin/areaName/path", where "admin" is configurable
            if (context.Request.Path.StartsWith(AreasResolver.Instance.AdminAreaPrefix))
            {
                String areaName;
                var    path = context.Request.Path.Substring(AreasResolver.Instance.AdminAreaPrefix.Length);
                int    pos  = path.IndexOf('/', 1);
                if (pos > 1)
                {
                    areaName = path.Substring(1, pos - 1);
                    path     = path.Substring(pos);
                }
                else
                {
                    areaName = path.Substring(1);
                    path     = "/";
                }

                // Core admin modules take precedence over user modules
                if (!NSembleCoreAdminModule.AvailableModules.TryGetValue(areaName, out areaConfigs))
                {
                    areaConfigs = AreasResolver.Instance.GetAreaConfigsByName(areaName);
                }

                if (areaConfigs == null)
                {
                    return(new ResolveResult(new NotFoundRoute(context.Request.Method, context.Request.Path), DynamicDictionary.Empty, null, null, null));
                }

                context.Items.Add("AreaConfigs", areaConfigs);

                var ret = Resolve(string.Concat(Constants.ResolverAdminAreaPrefix, "/", areaConfigs.ModuleName, path), context, this.cache);
                return(ret.Selected);
            }

            var remainingPath = AreasResolver.Instance.ParseArea(context.Request.Path, out areaConfigs);

            if (areaConfigs == null)
            {
                // basically, a 404
                return(new ResolveResult(new NotFoundRoute(context.Request.Method, context.Request.Path), DynamicDictionary.Empty, null, null, null));
            }

            context.Items.Add("AreaConfigs", areaConfigs);

            var newPath = string.Concat(Constants.ResolverAreaPrefix, "/", areaConfigs.ModuleName, remainingPath);

            var result =
                this.Resolve(newPath, context, this.cache);

            return(result.Selected);
        }
Ejemplo n.º 46
0
        private ResolveResults Resolve(string path, NancyContext context, IRouteCache routeCache)
        {
            if (routeCache.IsEmpty())
            {
                context.Trace.TraceLog.WriteLog(s => s.AppendLine("[DefaultRouteResolver] No routes available"));
                return(new ResolveResults
                {
                    Selected = new ResolveResult(new NotFoundRoute(context.Request.Method, path), DynamicDictionary.Empty, null, null, null)
                });
            }

            var routes =
                routeCache.GetRouteCandidates();

            // Condition
            routes =
                routes.Filter(context, "Invalid condition", (ctx, route) =>
            {
                var validCondition =
                    ((route.Item3.Condition == null) || (route.Item3.Condition(ctx)));

                return(new Tuple <bool, RouteCandidate>(
                           validCondition,
                           route
                           ));
            });

            if (!routes.Item1.Any())
            {
                context.Trace.TraceLog.WriteLog(s => s.AppendLine("[DefaultRouteResolver] No route had a valid condition"));
                return(new ResolveResults
                {
                    Selected = new ResolveResult(new NotFoundRoute(context.Request.Method, path), DynamicDictionary.Empty, null, null, null),
                    Rejected = routes.Item2
                });
            }

            // Path
            routes =
                routes.Filter(context, "Path did not match", (ctx, route) =>
            {
                var validationResult =
                    this.routePatternMatcher.Match(path, route.Item3.Path, route.Item3.Segments, context);

                var routeToReturn =
                    (validationResult.IsMatch) ? new RouteCandidate(route.Item1, route.Item2, route.Item3, validationResult) : route;

                return(new Tuple <bool, RouteCandidate>(
                           validationResult.IsMatch,
                           routeToReturn
                           ));
            });

            if (!routes.Item1.Any())
            {
                context.Trace.TraceLog.WriteLog(s => s.AppendLine("[DefaultRouteResolver] No route matched the requested path"));
                return(new ResolveResults
                {
                    Selected = new ResolveResult(new NotFoundRoute(context.Request.Method, path), DynamicDictionary.Empty, null, null, null),
                    Rejected = routes.Item2
                });
            }

            // Method
            routes =
                routes.Filter(context, "Request method did not match", (ctx, route) =>
            {
                var routeMethod =
                    route.Item3.Method.ToUpperInvariant();

                var requestMethod =
                    ctx.Request.Method.ToUpperInvariant();

                var methodIsValid =
                    routeMethod.Equals(requestMethod) || (routeMethod.Equals("GET") && requestMethod.Equals("HEAD"));

                return(new Tuple <bool, RouteCandidate>(
                           methodIsValid,
                           route
                           ));
            });

            if (!routes.Item1.Any())
            {
                var allowedMethods = routes.Item2.Values.SelectMany(x => x.Select(y => y.Item3.Method)).Distinct();
                if (context.Request.Method.Equals("OPTIONS"))
                {
                    return(new ResolveResults
                    {
                        Selected = new ResolveResult(new OptionsRoute(context.Request.Path, allowedMethods), DynamicDictionary.Empty, null, null, null),
                        Rejected = routes.Item2
                    });
                }
                context.Trace.TraceLog.WriteLog(s => s.AppendLine("[DefaultRouteResolver] Route Matched But Method Not Allowed"));
                return(new ResolveResults
                {
                    Selected = new ResolveResult(new MethodNotAllowedRoute(path, context.Request.Method, allowedMethods), DynamicDictionary.Empty, null, null, null),
                    Rejected = routes.Item2
                });
            }

            // Exact match
            var exactMatchResults =
                routes.Filter(context, "No exact match", (ctx, route) =>
            {
                var routeIsExactMatch =
                    !route.Item4.Parameters.GetDynamicMemberNames().Any();

                return(new Tuple <bool, RouteCandidate>(
                           routeIsExactMatch,
                           route
                           ));
            });

            if (exactMatchResults.Item1.Any())
            {
                context.Trace.TraceLog.WriteLog(s => s.AppendLine("[DefaultRouteResolver] Found exact match route"));
                return(new ResolveResults
                {
                    Selected = this.CreateRouteAndParametersFromMatch(context, exactMatchResults.Item1.First()),
                    Rejected = exactMatchResults.Item2
                });
            }

            // First match out of multiple candidates
            var selected =
                GetTopRouteMatchesNew(routes).First();

            context.Trace.TraceLog.WriteLog(s => s.AppendLine("[DefaultRouteResolver] Selected best match"));
            return(new ResolveResults
            {
                Selected = this.CreateRouteAndParametersFromMatch(context, selected),
                Rejected = exactMatchResults.Item2
            });
        }
Ejemplo n.º 47
0
 public bool HandlesStatusCode(Nancy.HttpStatusCode statusCode, Nancy.NancyContext context)
 {
     return((int)statusCode >= 400);
 }
Ejemplo n.º 48
0
 /// <summary>
 /// Executes at the end of the nancy execution pipeline and before control is passed back to the hosting.
 /// Can be used to pre-render/validate views while still inside the main pipeline/error handling.
 /// </summary>
 /// <param name="context">Nancy context</param>
 /// <returns>Task for completion/erroring</returns>
 public virtual Task PreExecute(NancyContext context)
 {
     return(TaskHelpers.GetCompletedTask());
 }
Ejemplo n.º 49
0
 private void UpdateTraceCookie(NancyContext ctx, Guid sessionGuid)
 {
     var cookie = new NancyCookie("__NCTRACE", sessionGuid.ToString(), true) { Expires = DateTime.Now.AddMinutes(30) };
     ctx.Response.AddCookie(cookie);
 }
Ejemplo n.º 50
0
 private Task InvokePostRequestHook(NancyContext context, CancellationToken cancellationToken, AfterPipeline pipeline)
 {
     return(pipeline == null?TaskHelpers.GetCompletedTask() : pipeline.Invoke(context, cancellationToken));
 }
Ejemplo n.º 51
0
 private bool EnableTracing(NancyContext ctx)
 {
     return StaticConfiguration.EnableRequestTracing &&
            !ctx.Request.Path.StartsWith(DiagnosticsHook.ControlPanelPrefix);
 }
Ejemplo n.º 52
0
 private static Action <Task <Response> > ExecuteTasksWithSingleResultContinuation(NancyContext context, CancellationToken cancellationToken, IEnumerator <Func <NancyContext, CancellationToken, Task <Response> > > enumerator, TaskCompletionSource <Response> tcs)
 {
     return(t =>
     {
         if (ContinueExecution(t.IsFaulted, t.Result, t.Exception))
         {
             if (enumerator.MoveNext())
             {
                 ExecuteTasksWithSingleResultInternal(context, cancellationToken, enumerator, tcs);
             }
             else
             {
                 ExecuteTasksSingleResultFinished(null, tcs);
             }
         }
         else
         {
             ExecuteTasksSingleResultFinished(t, tcs);
         }
     });
 }
Ejemplo n.º 53
-1
        private Response LogRequest(NancyContext ctx)
        {
            _logger.Debug("************ Request ************");
            _logger.Debug("{0} - {1}", ctx.Request.Method, ctx.Request.Path);
            _logger.Debug("************ Headers ************");

            foreach(var headerGroup in ctx.Request.Headers)
            {
                foreach(var header in headerGroup.Value)
                {
                    _logger.Debug("{0} - {1}", headerGroup.Key, header);
                }
            }

            _logger.Debug("************  Body ************");
            using (var reader = new StreamReader(ctx.Request.Body))
            {
                var content = reader.ReadToEnd();
                _logger.Debug(HttpUtility.UrlDecode(content));
            }

            ctx.Request.Body.Position = 0;

            return null;
        }