コード例 #1
0
        /// <summary>
        /// Enables forms authentication for a module
        /// </summary>
        /// <param name="module">Module to add handlers to (usually "this")</param>
        /// <param name="configuration">Forms authentication configuration</param>
        public static void Enable(INancyModule module, FormsAuthenticationConfiguration configuration)
        {
            if (module == null)
            {
                throw new ArgumentNullException("module");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            configuration.EnsureConfigurationIsValid();

            module.RequiresAuthentication();

            currentConfiguration = configuration;

            module.Before.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));

            if (!configuration.DisableRedirect)
            {
                module.After.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration));
            }
        }
コード例 #2
0
        /// <summary>
        /// Get the description for a route.
        /// </summary>
        /// <param name="module">The module that the route is defined in.</param>
        /// <param name="path">The path of the route that the description should be retrieved for.</param>
        /// <returns>A <see cref="string"/> containing the description of the route if it could be found, otherwise <see cref="string.Empty"/>.</returns>
        public string GetDescription(INancyModule module, string path)
        {
            var assembly =
                module.GetType().Assembly;

            if (assembly.IsDynamic)
            {
                return string.Empty;
            }

            var moduleName =
                string.Concat(module.GetType().FullName, ".resources");

            var resourceName = assembly
                .GetManifestResourceNames()
                .FirstOrDefault(x => x.Equals(moduleName, StringComparison.OrdinalIgnoreCase));

            if (resourceName != null)
            {
                var manager =
                    new ResourceManager(resourceName.Replace(".resources", string.Empty), assembly);

                return manager.GetString(path);
            }

            return string.Empty;
        }
コード例 #3
0
 private static void CreateNegotiationContext(INancyModule module, NancyContext context)
 {
     // TODO - not sure if this should be here or not, but it'll do for now :)
     context.NegotiationContext = new NegotiationContext
                                      {
                                          ModuleName = module.GetModuleName(),
                                          ModulePath = module.ModulePath,
                                      };
 }
コード例 #4
0
        /// <summary>
        /// Builds a fully configured <see cref="INancyModule"/> instance, based upon the provided <paramref name="module"/>.
        /// </summary>
        /// <param name="module">The <see cref="INancyModule"/> that should be configured.</param>
        /// <param name="context">The current request context.</param>
        /// <returns>A fully configured <see cref="INancyModule"/> instance.</returns>
        public INancyModule BuildModule(INancyModule module, NancyContext context)
        {
            module.Context = context;
            module.Response = this.responseFormatterFactory.Create(context);
            module.ViewFactory = this.viewFactory;
            module.ModelBinderLocator = this.modelBinderLocator;
            module.ValidatorLocator = this.validatorLocator;

            return module;
        }
コード例 #5
0
        public MetadataModuleRouteMetadataProviderFixture()
        {
            this.resolver = A.Fake<IMetadataModuleResolver>();
            this.module = A.Fake<INancyModule>();
            this.route = new RouteDescription("NamedDescription", "GET", "/things", ctx => true);
            this.metadataModule = new FakeNancyMetadataModule();
            this.metadataModule.Describe[this.route.Name] = desc => { return Metadata; };

            this.provider = new MetadataModuleRouteMetadataProvider(this.resolver);
        }
コード例 #6
0
        public static void Enable(INancyModule module)
        {
            if (module == null)
            {
                throw new ArgumentNullException("module");
            }

            module.RequiresAuthentication();
            module.Before.AddItemToStartOfPipeline(GetCredentialRetrievalHook());
        }
コード例 #7
0
 private IMetadataModule SafeInvokeConvention(Func<INancyModule, IEnumerable<IMetadataModule>, IMetadataModule> convention, INancyModule module)
 {
     try
     {
         return convention.Invoke(module, this.metadataModules);
     }
     catch
     {
         return null;
     }
 }
コード例 #8
0
        /// <summary>
        /// Get the currently logged in user
        /// </summary>
        private User GetLoggedInUser(INancyModule nancyModule)
        {
            var currentUser = nancyModule.GetPrincipal();
            if (!currentUser.IsAuthenticated())
                return null;

            if (string.IsNullOrWhiteSpace(currentUser.Email))
                return null;

            User loggedInUser = null;//ReadStore.Users.Get(currentUser.Email).FirstOrDefault();
            return loggedInUser;
        }
コード例 #9
0
        /// <summary>
        /// Builds a fully configured <see cref="INancyModule"/> instance, based upon the provided <paramref name="module"/>.
        /// </summary>
        /// <param name="module">The <see cref="INancyModule"/> that should be configured.</param>
        /// <param name="context">The current request context.</param>
        /// <returns>A fully configured <see cref="INancyModule"/> instance.</returns>
        public INancyModule BuildModule(INancyModule module, NancyContext context)
        {
            module.Context = context;
            module.Response = new DefaultResponseFormatter(rootPathProvider, context, this.serializerFactory);
            module.ModelBinderLocator = this.modelBinderLocator;

            module.After = new AfterPipeline();
            module.Before = new BeforePipeline();
            module.OnError = new ErrorPipeline();

            return module;
        }
コード例 #10
0
        /// <summary>
        /// Builds a fully configured <see cref="INancyModule"/> instance, based upon the provided <paramref name="module"/>.
        /// </summary>
        /// <param name="module">The <see cref="INancyModule"/> that shoule be configured.</param>
        /// <param name="context">The current request context.</param>
        /// <returns>A fully configured <see cref="INancyModule"/> instance.</returns>
        public INancyModule BuildModule(INancyModule module, NancyContext context)
        {
            CreateNegotiationContext(module, context);

            module.Context = context;
            module.Response = this.responseFormatterFactory.Create(context);
            module.ViewFactory = this.viewFactory;
            module.ModelBinderLocator = this.modelBinderLocator;
            module.ValidatorLocator = this.validatorLocator;
            module.Text = new TextResourceFinder(this.textResource, context);

            return module;
        }
コード例 #11
0
        /// <summary>
        /// Builds a fully configured <see cref="INancyModule"/> instance, based upon the provided <paramref name="module"/>.
        /// </summary>
        /// <param name="module">The <see cref="INancyModule"/> that should be configured.</param>
        /// <param name="context">The current request context.</param>
        /// <returns>A fully configured <see cref="INancyModule"/> instance.</returns>
        public INancyModule BuildModule(INancyModule module, NancyContext context)
        {
            // Currently we don't connect view location, binders etc.
            module.Context = context;
            module.Response = new DefaultResponseFormatter(rootPathProvider, context, serializers);
            module.ModelBinderLocator = this.modelBinderLocator;

            module.After = new AfterPipeline();
            module.Before = new BeforePipeline();
            module.OnError = new ErrorPipeline();

            return module;
        }
コード例 #12
0
ファイル: RouteId.cs プロジェクト: khellang/Nancy.Swagger
        public static RouteId Create(INancyModule module, Route route)
        {
            var routeId = new RouteId { Module = module };

            if (!string.IsNullOrEmpty(route.Description.Name))
            {
                routeId.Name = route.Description.Name;
            }
            else
            {
                routeId.Method = route.Description.Method.ToHttpMethod();
                routeId.Path = route.Description.Path.EnsureForwardSlash();
            }

            return routeId;
        }
コード例 #13
0
ファイル: RouteId.cs プロジェクト: khellang/Nancy.Swagger
        public static RouteId Create(INancyModule module, RouteAttribute swaggerRouteAttribute)
        {
            var routeId = new RouteId { Module = module };

            if (!string.IsNullOrEmpty(swaggerRouteAttribute.Name))
            {
                routeId.Name = swaggerRouteAttribute.Name;
            }
            else if (swaggerRouteAttribute.Path != null)
            {
                routeId.Method = swaggerRouteAttribute.Method;
                routeId.Path = module.ModulePath.EnsureForwardSlash() + swaggerRouteAttribute.Path;
            }

            return routeId;
        }
コード例 #14
0
ファイル: BasicAuthentication.cs プロジェクト: kppullin/Nancy
        /// <summary>
        /// Enables basic authentication for a module
        /// </summary>
        /// <param name="module">Module to add handlers to (usually "this")</param>
        /// <param name="configuration">Forms authentication configuration</param>
        public static void Enable(INancyModule module, BasicAuthenticationConfiguration configuration)
        {
            if (module == null)
            {
                throw new ArgumentNullException("module");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            module.RequiresAuthentication();
            module.Before.AddItemToStartOfPipeline(GetCredentialRetrievalHook(configuration));
            module.After.AddItemToEndOfPipeline(GetAuthenticationPromptHook(configuration));
        }
コード例 #15
0
        /// <summary>
        /// Gets the <see cref="T:System.Type" /> of the metadata that is created by the provider.
        /// </summary>
        /// <param name="module">The <see cref="T:Nancy.INancyModule" /> instance that the route is declared in.</param>
        /// <param name="routeDescription">A <see cref="T:Nancy.Routing.RouteDescription" /> for the route.</param>
        /// <returns>
        /// A <see cref="T:System.Type" /> instance, or <see langword="null" /> if nothing is found.
        /// </returns>
        public Type GetMetadataType(INancyModule module, RouteDescription routeDescription)
        {
            if (String.IsNullOrWhiteSpace(routeDescription.Name))
                return null;

            // TODO: Yikes, what an ugly hack. We need to figure out a better way to identify routes than their name. [asbjornu]
            switch (routeDescription.Name)
            {
                case JsonSchema:
                case ClientAssembly:
                case ClientNugetPackage:
                case ClientNugetPackageVersioned:
                    return typeof(PomonaRouteMetadata);
            }

            return null;
        }
コード例 #16
0
        /// <summary>
        /// Enables stateless authentication for a module
        /// </summary>
        /// <param name="module">Module to add handlers to (usually "this")</param>
        /// <param name="configuration">Stateless authentication configuration</param>
        public static void Enable(INancyModule module, StatelessAuthenticationConfiguration configuration)
        {
            if (module == null)
            {
                throw new ArgumentNullException("module");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (!configuration.IsValid)
            {
                throw new ArgumentException("Configuration is invalid", "configuration");
            }

            module.Before.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));
        }
コード例 #17
0
        private SwaggerRouteData CreateSwaggerRouteData(INancyModule module, Route route, Dictionary<RouteId, MethodInfo> routeHandlers)
        {
            var data = new SwaggerRouteData(route.Description.Path, new PathItem());

            var routeId = RouteId.Create(module, route);
            var handler = routeHandlers.ContainsKey(routeId) ? routeHandlers[routeId] : null;
            var operation = new AnnotatedOperation(route.Description.Name, handler, _modelCatalog);

            var method = route.Description.Method.ToHttpMethod();
            switch (route.Description.Method.ToLowerInvariant())
            {
                case "get":
                    data.PathItem.Get = operation;
                    break;
                case "post":
                    data.PathItem.Post = operation;
                    break;
                case "patch":
                    data.PathItem.Patch = operation;
                    break;
                case "delete":
                    data.PathItem.Delete = operation;
                    break;
                case "put":
                    data.PathItem.Put = operation;
                    break;
                case "head":
                    data.PathItem.Head = operation;
                    break;
                case "options":
                    data.PathItem.Options = operation;
                    break;
            }

            if (operation.ResponseType != null)
            {
                data.Types.Add(method, operation.ResponseType);
            }

            return data;
        }
コード例 #18
0
        public object GetMetadata(INancyModule module, RouteDescription routeDescription)
        {
            var type = GetModuleMetadataType(module);

            if (type == null)
            {
                return(null);
            }

            ModuleMetadata metadata;

            if (MetadataItems.TryGetValue(type, out metadata))
            {
                return(metadata[routeDescription.Method, routeDescription.Path]);
            }

            metadata = (ModuleMetadata)(_container.Resolve(type));
            MetadataItems.Add(type, metadata);

            return(metadata?[routeDescription.Method, routeDescription.Path]);
        }
コード例 #19
0
        public static Response AddUser(this INancyModule module, UserIdentity userIdentity, IUserRepository userRepository, IViewRenderer viewRenderer)
        {
            try
            {
                var allUsers = userRepository.GetAllUsers();
                if (allUsers.Any(user => string.Equals(user.UserName, userIdentity.UserName, StringComparison.OrdinalIgnoreCase)))
                {
                    module.Context.ViewBag.AuthenticationError = Constants.AdminUserAlreadyExistsError;
                    return(viewRenderer.RenderView(module.Context, AdminModule.AdminUserAddRoute));
                }

                userRepository.AddUser(userIdentity);
                module.Context.ViewBag.AuthenticationError = Constants.AdminUserAdded;
                return(module.Response.AsRedirect($"~/{AdminModule.AdminDashboardRoute}"));
            }
            catch (Exception e)
            {
                module.Context.ViewBag.AuthenticationError = e.Message;
                return(viewRenderer.RenderView(module.Context, AdminModule.AdminUserAddRoute));
            }
        }
コード例 #20
0
ファイル: ModuleExtensions.cs プロジェクト: zippy1981/Nancy
        /// <summary>
        /// Performs validation on the specified <paramref name="instance"/>.
        /// </summary>
        /// <typeparam name="T">The type of the <paramref name="instance"/> that is being validated.</typeparam>
        /// <param name="module">The module that the validation is performed from.</param>
        /// <param name="instance">The instance that is being validated.</param>
        /// <returns>A <see cref="ModelValidationResult"/> instance.</returns>
        public static ModelValidationResult Validate <T>(this INancyModule module, T instance)
        {
            var validator =
                module.ValidatorLocator.GetValidatorForType(typeof(T));

            var result = (validator == null) ?
                         ModelValidationResult.Valid :
                         validator.Validate(instance, module.Context);

            if (module.ModelValidationResult.Errors.Any())
            {
                module.ModelValidationResult.Errors =
                    module.ModelValidationResult.Errors.Concat(result.Errors).ToDictionary(key => key.Key, val => val.Value);
            }

            module.ModelValidationResult = module.ModelValidationResult.Errors.Any()
                                               ? module.ModelValidationResult
                                               : result;

            return(module.ModelValidationResult);
        }
コード例 #21
0
        public dynamic Execute(dynamic parameters, INancyModule module)
        {
            string feedName = parameters.feed;
            var    feed     = GetFeedModel(feedName);

            if (feed == null)
            {
                var response = module.Response.AsText("Feed does not exist.");
                response.StatusCode = HttpStatusCode.BadRequest;
                return(response);
            }

            using (var dbContext = new DatabaseContext(Store))
            {
                IQueryable <IInternalPackage> ds = dbContext.Packages.AsNoTracking().AsQueryable();

                ds = ds.Where(pk => pk.FeedId == feed.Id);
                ds = ds.Where(pk => pk.Listed);

                string packageId      = parameters.PackageId;
                string packageVersion = parameters.PackageVersion;

                if (!string.IsNullOrWhiteSpace(packageId) && !string.IsNullOrWhiteSpace(packageVersion))
                {
                    ds = ds.Where(pk => pk.PackageId == packageId && pk.Version == packageVersion);
                }

                var package = ds.FirstOrDefault();

                if (package == null)
                {
                    return(new Response()
                    {
                        StatusCode = HttpStatusCode.NotFound
                    });
                }

                return(ProcessResponse(module, feed, package));
            }
        }
コード例 #22
0
        public UserIdentity CurrentUser(INancyModule module)
        {
            try
            {
                var user = this.GetCurrentUser(module);

                if (user == null)
                {
                    Logging.Log().Error("Unknown user. Throwing AuthenticationException...");

                    throw new AuthenticationException("Cannot authenticate user.");
                }

                Logging.Log().Information("User claims he is {0}", user.Id);

                if (module != null &&
                    ForwardedFor.Exist(module.Request.Headers))
                {
                    ForwardedFor header = ForwardedFor.Create(module.Request.Headers);
                    if (this.UserIsTrustedServiceAccount(user))
                    {
                        Logging.Log().Information("User {0} is on the list of trusted service accounts. User {0} acts on behalf of the following user: id={1}, pid={2}, name={3}.", user.Id, header.User.Id, header.User.Pid, header.User.Name);

                        return(header.User);
                    }
                    else
                    {
                        Logging.Log().Warning("User {0} is NOT on the list of trusted service accounts, but sent Forwarded header.", user.Id);
                    }
                }

                return(user);
            }
            catch (Exception exception)
            {
                Logging.Log().Error("Unknown user. Throwing AuthenticationException...");

                throw new AuthenticationException("Cannot authenticate user.", exception);
            }
        }
コード例 #23
0
        public static void RequiresAnyRole(this INancyModule module, Role[] requiredRoles, string[] except = null)
        {
            module.AddBeforeHookOrExecute((ctx =>
            {
                if (except != null && except.Contains(ctx.ResolvedRoute.Description.Name))
                {
                    return(null);
                }

                return(SecurityHooks.RequiresAuthentication(ctx));
            }), "Requires Authentication");

            module.AddBeforeHookOrExecute((ctx =>
            {
                if (except != null && except.Contains(ctx.ResolvedRoute.Description.Name))
                {
                    return(null);
                }

                return(SecurityHooks.RequiresAnyRole(ctx, requiredRoles));
            }), "Requires Claims");
        }
コード例 #24
0
        /// <summary>
        /// Deal with an unknown social identity
        /// </summary>
        private dynamic HandleUnknownIdentity(INancyModule nancyModule)
        {
            // Get the currently logged in user
            var loggedInUser = GetLoggedInUser(nancyModule);

            // If we come in with an unknown identity, but are logged in, it means we want to link it
            if (loggedInUser != null)
            {
                // Link to the logged in user
                // TODO: Implement
                //LinkIdentity(userInfo, providerName, loggedInUser);

                // If a user is already logged in, then we know they could only have gotten here via the account page,
                // so we will redirect them there
                //nancyModule.AddAlertMessage("success", string.Format("Successfully linked {0} account.", providerName));
                return nancyModule.Response.AsRedirect("~/account/identity");
            }

            // User is unknown, nobody is logged in, send to register/link page
            // TODO: Prefill model with email if we have it, and a flag saying it comes from a social identity
            return nancyModule.Response.AsRedirect("~/account/register");
        }
コード例 #25
0
        /// <summary>
        /// Deal with an unknown social identity
        /// </summary>
        private dynamic HandleUnknownIdentity(INancyModule nancyModule)
        {
            // Get the currently logged in user
            var loggedInUser = GetLoggedInUser(nancyModule);

            // If we come in with an unknown identity, but are logged in, it means we want to link it
            if (loggedInUser != null)
            {
                // Link to the logged in user
                // TODO: Implement
                //LinkIdentity(userInfo, providerName, loggedInUser);

                // If a user is already logged in, then we know they could only have gotten here via the account page,
                // so we will redirect them there
                //nancyModule.AddAlertMessage("success", string.Format("Successfully linked {0} account.", providerName));
                return(nancyModule.Response.AsRedirect("~/account/identity"));
            }

            // User is unknown, nobody is logged in, send to register/link page
            // TODO: Prefill model with email if we have it, and a flag saying it comes from a social identity
            return(nancyModule.Response.AsRedirect("~/account/register"));
        }
コード例 #26
0
        /// <summary>
        /// Get the description for a route.
        /// </summary>
        /// <param name="module">The module that the route is defined in.</param>
        /// <param name="path">The path of the route that the description should be retrieved for.</param>
        /// <returns>A <see cref="string"/> containing the description of the route if it could be found, otherwise <see cref="string.Empty"/>.</returns>
        public string GetDescription(INancyModule module, string path)
        {
            var assembly =
                module.GetType().Assembly;

            var moduleName =
                string.Concat(module.GetType().FullName, ".resources");

            var resourceName = assembly
                               .GetManifestResourceNames()
                               .FirstOrDefault(x => x.Equals(moduleName, StringComparison.OrdinalIgnoreCase));

            if (resourceName != null)
            {
                var manager =
                    new ResourceManager(resourceName.Replace(".resources", string.Empty), assembly);

                return(manager.GetString(path));
            }

            return(string.Empty);
        }
コード例 #27
0
        public static void RequiresAuthentication(this INancyModule module, string[] excludes)
        {
            module.AddBeforeHookOrExecute(p =>
            {
                Response response = null;
                if (excludes.Contains(p.ResolvedRoute.Description.Name))
                {
                    return(response);
                }

                if (p.CurrentUser == null ||
                    string.IsNullOrWhiteSpace(p.CurrentUser.UserName))
                {
                    response = new Response
                    {
                        StatusCode = HttpStatusCode.Unauthorized
                    };
                }

                return(response);
            }, "Requires Authentication");
        }
コード例 #28
0
        /// <summary>
        /// Gets the metadata for the provided route.
        /// </summary>
        /// <param name="module">The <see cref="T:Nancy.INancyModule" /> instance that the route is declared in.</param>
        /// <param name="routeDescription">A <see cref="T:Nancy.Routing.RouteDescription" /> for the route.</param>
        /// <returns>
        /// An object representing the metadata for the given route, or <see langword="null" /> if nothing is found.
        /// </returns>
        public object GetMetadata(INancyModule module, RouteDescription routeDescription)
        {
            if (String.IsNullOrWhiteSpace(routeDescription.Name))
            {
                return(null);
            }

            // TODO: Yikes, what an ugly hack. We need to figure out a better way to identify routes than their name. [asbjornu]
            switch (routeDescription.Name)
            {
            case JsonSchema:
                return(new PomonaRouteMetadata
                {
                    ContentType = "application/json",
                    Method = HttpMethod.Get,
                    Relation = "json-schema",
                });

            case ClientAssembly:
                return(new PomonaRouteMetadata
                {
                    ContentType = "binary/octet-stream",
                    Method = HttpMethod.Get,
                    Relation = "client-assembly",
                });

            case ClientNugetPackage:
            case ClientNugetPackageVersioned:
                return(new PomonaRouteMetadata
                {
                    ContentType = "application/zip",
                    Method = HttpMethod.Get,
                    Relation = "nuget-package",
                });
            }

            return(null);
        }
コード例 #29
0
        public dynamic Execute(dynamic parameters, INancyModule module)
        {
            module.RequiresAuthentication();

            IFeedConfiguration feedConfig;

            try
            {
                int feedId = int.Parse(parameters.id);

                feedConfig = module.Bind <FeedConfiguration>();

                if (feedId != feedConfig.FeedId)
                {
                    return(HttpStatusCode.BadRequest);
                }

                ITransaction transaction = _store.BeginTransaction();

                var existingFeedExists = transaction.Query <IFeedConfiguration>().Where("FeedId = @feedId").Parameter("feedId", feedId).Count() > 0;

                if (!existingFeedExists)
                {
                    return(HttpStatusCode.NotFound);
                }

                transaction.Update(feedConfig);
                transaction.Commit();
                transaction.Dispose();
            }
            catch (Exception ex)
            {
                return(HttpStatusCode.InternalServerError);
            }


            return(feedConfig);
        }
コード例 #30
0
 /// <summary>Enables forms authentication for a module</summary>
 /// <param name="module">Module to add handlers to (usually "this")</param>
 /// <param name="configuration">Forms authentication configuration</param>
 public static void Enable(INancyModule module, CustomAuthenticationConfiguration configuration)
 {
     if (module == null)
     {
         throw new ArgumentNullException("module");
     }
     if (configuration == null)
     {
         throw new ArgumentNullException("configuration");
     }
     if (!configuration.IsValid)
     {
         throw new ArgumentException("Configuration is invalid", "configuration");
     }
     module.RequiresAuthentication();
     CustomAuthenticationProvider.currentConfiguration = configuration;
     module.Before.AddItemToStartOfPipeline(CustomAuthenticationProvider.GetLoadAuthenticationHook(configuration));
     if (configuration.DisableRedirect)
     {
         return;
     }
     module.After.AddItemToEndOfPipeline(CustomAuthenticationProvider.GetRedirectToLoginHook(configuration));
 }
コード例 #31
0
        public dynamic Execute(dynamic parameters, INancyModule module)
        {
            module.RequiresAuthentication();

            using (ITransaction transaction = _store.BeginTransaction())
            {
                int feedId = int.Parse(parameters.id);

                var feed = transaction.Query <IFeed>().Where("Id = @feedId").Parameter("feedId", feedId).First();
                if (feed != null)
                {
                    //Temporary until the API Key table is used
                    if (!string.IsNullOrWhiteSpace(feed.ApiKeyHashed))
                    {
                        feed.HasApiKey = true;
                    }
                    feed.ApiKeyHashed = null;   //We don't want to expose this to the front end
                    feed.ApiKeySalt   = null;   //We don't want to expose this to the front end
                }

                return(feed);
            }
        }
コード例 #32
0
        public static void MetricForRequestTime(this INancyModule module, string metricName, Predicate <RouteDescription> routePredicate)
        {
            var timer = NancyGlobalMetrics.NancyGlobalMetricsContext.Timer(metricName, Unit.Requests, SamplingType.FavourRecent, TimeUnit.Seconds, TimeUnit.Milliseconds);
            var key   = "Metrics.Nancy.Request.Timer." + metricName;

            module.Before.AddItemToStartOfPipeline(ctx =>
            {
                if (routePredicate(ctx.ResolvedRoute.Description))
                {
                    ctx.Items[key] = timer.NewContext();
                }
                return(null);
            });

            module.After.AddItemToEndOfPipeline(ctx =>
            {
                if (routePredicate(ctx.ResolvedRoute.Description))
                {
                    using (ctx.Items[key] as IDisposable) { }
                    ctx.Items.Remove(key);
                }
            });
        }
コード例 #33
0
        public override Response Authenticate(
            INancyModule nancyModule,
            IUserMapper userMapper,
            IConfiguration configuration,
            IUserRepository userRepository,
            UserCredentials userCredentials,
            IViewRenderer viewRenderer,
            IModuleStaticWrappers moduleStaticWrappers)
        {
            var validUser = userRepository.Authenticate(userCredentials.User, userCredentials.Password);

            if (validUser == null)
            {
                nancyModule.Context.ViewBag.AuthenticationError = Constants.AuthenticationError;
                return(viewRenderer.RenderView(nancyModule.Context, AuthenticationRedirectUrl.Url));
            }

            var guid = userMapper.AddUser(userCredentials.User, validUser.FirstName, validUser.LastName, validUser.Claims);

            validUser.LastLogin = DateTime.UtcNow;
            userRepository.UpdateUser(validUser);
            return(moduleStaticWrappers.LoginAndRedirect(nancyModule, guid, null, ModuleStaticWrappers.DefaultFallbackRedirectUrl));
        }
コード例 #34
0
        protected override UserIdentity GetCurrentUser(INancyModule module)
        {
            var env = module.Context.GetOwinEnvironment();

            // server.User will be set only if certificate validation will succeed
            if (!env.ContainsKey("server.User") || env["server.User"] == null || !env.ContainsKey("ssl.ClientCertificate") || env["ssl.ClientCertificate"] == null)
            {
                return(null);
            }

            var clientCertificate = env["ssl.ClientCertificate"] as X509Certificate2;
            var identity          = (ClaimsPrincipal)env["server.User"];

            Logging.Log().Information("Using the following client certificate to authenticate: {0}", clientCertificate);

            var disinguishedNameClaim =
                identity.Claims.First(
                    claim => claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname");

            var subjectName = disinguishedNameClaim.Value;
            var subject     = subjectName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim());
            var cn          = subject.Where(i => i.StartsWith("CN=", StringComparison.InvariantCultureIgnoreCase)).Select(i => i.Remove(0, 3)).First();

            string pattern = @"^(.*)\s\((.*)\)$";

            var result = Regex.Match(cn, pattern);

            var userIdentity = new UserIdentity
            {
                Id   = cn,
                Name = result.Groups[1].Value,
                Pid  = result.Groups[2].Value
            };

            return(userIdentity);
        }
コード例 #35
0
        /// <summary>
        /// Gets the metadata for the provided route.
        /// </summary>
        /// <param name="module">The <see cref="T:Nancy.INancyModule" /> instance that the route is declared in.</param>
        /// <param name="routeDescription">A <see cref="T:Nancy.Routing.RouteDescription" /> for the route.</param>
        /// <returns>
        /// An object representing the metadata for the given route, or <see langword="null" /> if nothing is found.
        /// </returns>
        public object GetMetadata(INancyModule module, RouteDescription routeDescription)
        {
            if (String.IsNullOrWhiteSpace(routeDescription.Name))
                return null;

            // TODO: Yikes, what an ugly hack. We need to figure out a better way to identify routes than their name. [asbjornu]
            switch (routeDescription.Name)
            {
                case JsonSchema:
                    return new PomonaRouteMetadata
                    {
                        ContentType = "application/json",
                        Method = HttpMethod.Get,
                        Relation = "json-schema",
                    };

                case ClientAssembly:
                    return new PomonaRouteMetadata
                    {
                        ContentType = "binary/octet-stream",
                        Method = HttpMethod.Get,
                        Relation = "client-assembly",
                    };

                case ClientNugetPackage:
                case ClientNugetPackageVersioned:
                    return new PomonaRouteMetadata
                    {
                        ContentType = "application/zip",
                        Method = HttpMethod.Get,
                        Relation = "nuget-package",
                    };
            }

            return null;
        }
コード例 #36
0
 /// <summary>
 /// This module requires authentication and any one of certain claims to be present.
 /// </summary>
 /// <param name="module">Module to enable</param>
 /// <param name="requiredClaims">Claim(s) required</param>
 public static void RequiresAnyClaim(this INancyModule module, params Predicate <Claim>[] requiredClaims)
 {
     module.AddBeforeHookOrExecute(SecurityHooks.RequiresAuthentication(), "Requires Authentication");
     module.AddBeforeHookOrExecute(SecurityHooks.RequiresAnyClaim(requiredClaims), "Requires Any Claim");
 }
コード例 #37
0
        private SwaggerRouteData CreateSwaggerRouteData(INancyModule module, Route route, Dictionary<RouteId, MethodInfo> routeHandlers)
        {
            var data = new SwaggerRouteData
            {
                ApiPath = route.Description.Path,
                ResourcePath = module.ModulePath.EnsureForwardSlash(),
                OperationMethod = route.Description.Method.ToHttpMethod(),
                OperationNickname = route.Description.Name
            };

            var routeId = RouteId.Create(module, route);
            var handler = routeHandlers.ContainsKey(routeId) ? routeHandlers[routeId] : null;
            if (handler == null)
            {
                data.OperationNotes = "[example]"; // TODO: Insert example how to annotate a route
                data.OperationSummary = "Warning: no annotated method found for this route";

                return data;
            }

            foreach (var attr in handler.GetCustomAttributes<RouteAttribute>())
            {
                data.OperationSummary = attr.Summary ?? data.OperationSummary;
                data.OperationNotes = attr.Notes ?? data.OperationNotes;
                data.OperationModel = attr.Response ?? data.OperationModel;
                data.OperationConsumes = attr.Consumes ?? data.OperationConsumes;
                data.OperationProduces = attr.Produces ?? data.OperationProduces;
            }

            data.OperationResponseMessages = handler.GetCustomAttributes<SwaggerResponseAttribute>()
                .Select(attr => {
                    var msg = new ResponseMessage
                    {
                        Code = (int)attr.Code,
                        Message = attr.Message                    
                    };
                    
                    if (attr.Model != null) 
                    {
                        msg.ResponseModel = Primitive.IsPrimitive(attr.Model) 
                                                ? Primitive.FromType(attr.Model).Type
                                                : SwaggerConfig.ModelIdConvention(attr.Model);
                    }

                    return msg;
                })
                .ToList();


            data.OperationParameters = handler.GetParameters()
                .Select(CreateSwaggerParameterData)
                .ToList();

            return data;
        }
コード例 #38
0
ファイル: ModuleSecurity.cs プロジェクト: yannisgu/Nancy
 /// <summary>
 /// This module requires https.
 /// </summary>
 /// <param name="module">The <see cref="INancyModule"/> that requires HTTPS.</param>
 public static void RequiresHttps(this INancyModule module)
 {
     module.RequiresHttps(true);
 }
コード例 #39
0
ファイル: ModuleSecurity.cs プロジェクト: yannisgu/Nancy
 /// <summary>
 /// This module requires authentication and any one of certain claims to be present.
 /// </summary>
 /// <param name="module">Module to enable</param>
 /// <param name="requiredClaims">Claim(s) required</param>
 public static void RequiresAnyClaim(this INancyModule module, IEnumerable <string> requiredClaims)
 {
     module.AddBeforeHookOrExecute(SecurityHooks.RequiresAuthentication(), "Requires Authentication");
     module.AddBeforeHookOrExecute(SecurityHooks.RequiresAnyClaim(requiredClaims), "Requires Any Claim");
 }
コード例 #40
0
 /// <summary>Logs the user out and redirects</summary>
 /// <param name="module">Nancy module</param>
 /// <param name="redirectUrl">URL to redirect to</param>
 /// <returns>Nancy response instance</returns>
 public static Response LogoutAndRedirect(this INancyModule module, string redirectUrl)
 {
     return(CustomAuthenticationProvider.LogOutAndRedirectResponse(module.Context, redirectUrl));
 }
コード例 #41
0
 /// <summary>
 /// Logs the user in with the given user guid and redirects.
 /// </summary>
 /// <param name="module">Nancy module</param>
 /// <param name="userIdentifier">User identifier guid</param>
 /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
 /// <param name="fallbackRedirectUrl">Url to redirect to if none in the querystring</param>
 /// <returns>Nancy response instance</returns>
 public static Response LoginAndRedirect(this INancyModule module, Guid userIdentifier, DateTime?cookieExpiry = null, string fallbackRedirectUrl = "/")
 {
     return(CustomAuthenticationProvider.UserLoggedInRedirectResponse(module.Context, userIdentifier, cookieExpiry, fallbackRedirectUrl));
 }
コード例 #42
0
 public string GetDescription(INancyModule module, string path)
 {
     return string.Empty;
 }
コード例 #43
0
 /// <summary>
 /// This module requires https.
 /// </summary>
 /// <param name="module">The <see cref="INancyModule"/> that requires HTTPS.</param>
 /// <param name="redirect"><see langword="true"/> if the user should be redirected to HTTPS (no port number) if the incoming request was made using HTTP, otherwise <see langword="false"/> if <see cref="HttpStatusCode.Forbidden"/> should be returned.</param>
 public static void RequiresHttps(this INancyModule module, bool redirect)
 {
     module.Before.AddItemToEndOfPipeline(SecurityHooks.RequiresHttps(redirect, null));
 }
コード例 #44
0
 public string GetDescription(INancyModule module, string path)
 {
     var moduleMethod = _moduleDescriptions.FirstOrDefault(x => x.Item1 == module.ToString() && x.Item2 == path);
     return moduleMethod != null ? moduleMethod.Item3 : "";
 }
コード例 #45
0
        /// <summary>
        /// Gets the <see cref="Type"/> of the metadata that is created by the provider.
        /// </summary>
        /// <param name="module">The <see cref="INancyModule"/> instance that the route is declared in.</param>
        /// <param name="routeDescription">A <see cref="RouteDescription"/> for the route.</param>
        /// <returns>A <see cref="Type"/> instance, or null if none are found.</returns>
        public Type GetMetadataType(INancyModule module, RouteDescription routeDescription)
        {
            var metadataModule = this.resolver.GetMetadataModule(module);

            return metadataModule != null ? metadataModule.MetadataType : null;
        }
コード例 #46
0
        /// <summary>
        /// Gets the metadata for the provided route by obtaining it from an associated <see cref="IMetadataModule"/>.
        /// </summary>
        /// <param name="module">The <see cref="INancyModule"/> instance that the route is declared in.</param>
        /// <param name="routeDescription">A <see cref="RouteDescription"/> for the route.</param>
        /// <returns>An object representing the metadata for the given route, or null if none are found.</returns>
        public object GetMetadata(INancyModule module, RouteDescription routeDescription)
        {
            var metadataModule = this.resolver.GetMetadataModule(module);

            return metadataModule != null ? metadataModule.GetMetadata(routeDescription) : null;
        }
コード例 #47
0
 public object GetMetadata(INancyModule module, RouteDescription routeDescription)
 {
     var description = _routeDescriptionProvider.GetDescription(module, routeDescription.Path);
     return new DefaultRouteMetadata(routeDescription.Method, routeDescription.Path, description);
 }
コード例 #48
0
        public void SetModule(INancyModule module)
        {
            if (module == null)
            {
                throw new ArgumentNullException("module");
            }

            this.ModuleName = module.GetModuleName();
            this.ModulePath = module.ModulePath;
        }
コード例 #49
0
 /// <summary>Logs the user out without a redirect</summary>
 /// <param name="module">Nancy module</param>
 /// <returns>Nancy response instance</returns>
 public static Response LogoutWithoutRedirect(this INancyModule module)
 {
     return(CustomAuthenticationProvider.LogOutResponse());
 }
コード例 #50
0
 public Response LogoutAndRedirect(INancyModule module, string redirectUrl)
 {
     return(module.LogoutAndRedirect(redirectUrl));
 }
コード例 #51
0
 /// <summary>
 /// Logs the user in with the given user guid and returns ok response.
 /// </summary>
 /// <param name="module">Nancy module</param>
 /// <param name="userIdentifier">User identifier guid</param>
 /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
 /// <returns>Nancy response instance</returns>
 public static Response LoginWithoutRedirect(this INancyModule module, Guid userIdentifier, DateTime?cookieExpiry = null)
 {
     return(CustomAuthenticationProvider.UserLoggedInResponse(userIdentifier, cookieExpiry));
 }
コード例 #52
0
        /// <summary>
        /// Creates a new csrf token for this response with an optional salt.
        /// Only necessary if a particular route requires a new token for each request.
        /// </summary>
        /// <param name="module">Nancy module</param>
        /// <returns></returns>
        public static void CreateNewCsrfToken(this INancyModule module, CryptographyConfiguration cryptographyConfiguration = null)
        {
            var tokenString = GenerateTokenString(cryptographyConfiguration);

            module.Context.Items[CsrfToken.DEFAULT_CSRF_KEY] = tokenString;
        }
コード例 #53
0
ファイル: ModuleSecurity.cs プロジェクト: yannisgu/Nancy
 /// <summary>
 /// This module requires authentication
 /// </summary>
 /// <param name="module">Module to enable</param>
 public static void RequiresAuthentication(this INancyModule module)
 {
     module.AddBeforeHookOrExecute(SecurityHooks.RequiresAuthentication(), "Requires Authentication");
 }
コード例 #54
0
ファイル: NancyModule.cs プロジェクト: adglopez/Nancy
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewRenderer"/> class.
 /// </summary>
 /// <param name="module">The <see cref="INancyModule"/> instance that is rendering the view.</param>
 public ViewRenderer(INancyModule module)
 {
     this.module = module;
 }
コード例 #55
0
ファイル: ModuleSecurity.cs プロジェクト: yannisgu/Nancy
 /// <summary>
 /// This module requires claims to be validated
 /// </summary>
 /// <param name="module">Module to enable</param>
 /// <param name="isValid">Claims validator</param>
 public static void RequiresValidatedClaims(this INancyModule module, Func <IEnumerable <string>, bool> isValid)
 {
     module.AddBeforeHookOrExecute(SecurityHooks.RequiresAuthentication(), "Requires Authentication");
     module.AddBeforeHookOrExecute(SecurityHooks.RequiresValidatedClaims(isValid), "Requires Validated Claim");
 }
コード例 #56
0
ファイル: OmletSchemaBuilder.cs プロジェクト: amacal/omlet
 public OmletSchemaBuilder(INancyModule module, Func<dynamic, dynamic> callback)
 {
     this.module = module;
     this.callback = callback;
     this.onResponse = new Dictionary<HttpStatusCode, JsonSchema>();
 }
コード例 #57
0
ファイル: ModuleSecurity.cs プロジェクト: yannisgu/Nancy
 /// <summary>
 /// This module requires https.
 /// </summary>
 /// <param name="module">The <see cref="INancyModule"/> that requires HTTPS.</param>
 /// <param name="redirect"><see langword="true"/> if the user should be redirected to HTTPS if the incoming request was made using HTTP, otherwise <see langword="false"/> if <see cref="HttpStatusCode.Forbidden"/> should be returned.</param>
 /// <param name="httpsPort">The HTTPS port number to use</param>
 public static void RequiresHttps(this INancyModule module, bool redirect, int httpsPort)
 {
     module.Before.AddItemToEndOfPipeline(RequiresHttps(redirect, httpsPort));
 }
コード例 #58
0
        /// <summary>
        /// Deal with an already known social identity
        /// </summary>
        private dynamic HandleKnownIdentity(UserIdentity userIdentity, INancyModule nancyModule, string returnUrl)
        {
            // Get the currently logged in user
            var loggedInUser = GetLoggedInUser(nancyModule);

            // If we aren't logged in, log ourselves in
            if (loggedInUser == null)
            {
                User user = null;//ReadStore.Users.FindAllByUserId(userIdentity.UserId).FirstOrDefault();
                if (user == null)
                {
                    // Something went wrong
                    //nancyModule.AddAlertMessage();
                    return nancyModule.AsRedirectQueryStringOrDefault("~/dashboard");
                }

                nancyModule.SignIn(user);

                return string.IsNullOrWhiteSpace(returnUrl)
                    ? nancyModule.AsRedirectQueryStringOrDefault("~/dashboard")
                    : nancyModule.Response.AsRedirect(returnUrl);
            }

            // If we are logged in, we are trying to link ourselves, check if we are allowed
            //if (loggedInUser.UserId != userIdentity.UserId)
            //{
            //    // You can't link an account that's already attached to another user
            //    // TODO: Implement
            //    //nancyModule.AddAlertMessage("error", string.Format("This {0} account has already been linked to another user.", providerName));
            //}

            // We are logged in, and are trying to link ourselves to something that has already been linked, just redirect
            // TODO: Perhaps we should update the returned data at this time
            return nancyModule.Response.AsRedirect("~/account/identity");
        }
コード例 #59
0
 /// <summary>
 /// Module requires JwtBearer authentication
 /// </summary>
 /// <param name="module">Module to enable</param>
 /// <param name="configuration">JwtBearer authentication configuration</param>
 public static void EnableJwtBearerAuthentication(this INancyModule module, JwtBearerAuthenticationConfiguration configuration)
 {
     JwtBearerAuthentication.Enable(module, configuration);
 }
コード例 #60
0
        private IEnumerable<SwaggerRouteData> ToSwaggerRouteData(INancyModule module)
        {
            Func<IEnumerable<RouteAttribute>, RouteId> getRouteId = (attrs) =>
            {
                return attrs.Select(attr => RouteId.Create(module, attr))
                            .FirstOrDefault(routeId => routeId.IsValid);
            };

            // Discover route handlers and put them in a Dictionary<RouteId, MethodInfo>
            var routeHandlers =
                module.GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
                    .Select(methodInfo => new
                    {
                        RouteId = getRouteId(methodInfo.GetCustomAttributes<RouteAttribute>()),
                        MethodInfo = methodInfo
                    })
                    .Where(x => x.RouteId.IsValid)
                    .ToDictionary(
                        x => x.RouteId,
                        x => x.MethodInfo
                    );

            return module.Routes
                .Select(route => CreateSwaggerRouteData(module, route, routeHandlers));
        }