public TestableV1Feed(
     IEntityRepository<Package> repo,
     IGalleryConfigurationService configuration,
     ISearchService searchService)
     : base(repo, configuration, searchService)
 {
 }
 public ApiController(
     IEntitiesContext entitiesContext,
     IPackageService packageService,
     IPackageFileService packageFileService,
     IUserService userService,
     INuGetExeDownloaderService nugetExeDownloaderService,
     IContentService contentService,
     IIndexingService indexingService,
     ISearchService searchService,
     IAutomaticallyCuratePackageCommand autoCuratePackage,
     IStatusService statusService,
     IMessageService messageService,
     AuditingService auditingService,
     IGalleryConfigurationService configurationService)
 {
     EntitiesContext = entitiesContext;
     PackageService = packageService;
     PackageFileService = packageFileService;
     UserService = userService;
     NugetExeDownloaderService = nugetExeDownloaderService;
     ContentService = contentService;
     StatisticsService = null;
     IndexingService = indexingService;
     SearchService = searchService;
     AutoCuratePackage = autoCuratePackage;
     StatusService = statusService;
     MessageService = messageService;
     AuditingService = auditingService;
     ConfigurationService = configurationService;
 }
        public ISecretReader CreateSecretReader(IGalleryConfigurationService configurationService)
        {
            if (configurationService == null)
            {
                throw new ArgumentNullException(nameof(configurationService));
            }

            ISecretReader secretReader;

            var vaultName = configurationService.ReadSetting(
                string.Format(CultureInfo.InvariantCulture, "{0}{1}", KeyVaultConfigurationPrefix, VaultNameConfigurationKey)).Result;

            if (!string.IsNullOrEmpty(vaultName))
            {
                var clientId = configurationService.ReadSetting(
                    string.Format(CultureInfo.InvariantCulture, "{0}{1}", KeyVaultConfigurationPrefix, ClientIdConfigurationKey)).Result;
                var certificateThumbprint = configurationService.ReadSetting(
                    string.Format(CultureInfo.InvariantCulture, "{0}{1}", KeyVaultConfigurationPrefix, CertificateThumbprintConfigurationKey)).Result;

                var keyVaultConfiguration = new KeyVaultConfiguration(vaultName, clientId, certificateThumbprint, validateCertificate: true);

                secretReader = new KeyVaultReader(keyVaultConfiguration);
            }
            else
            {
                secretReader = new EmptySecretReader();
            }

            return new CachingSecretReader(secretReader, _diagnosticsService);
        }
        public async Task Startup(IGalleryConfigurationService config, IAppBuilder app)
        {
            await Configure(config);

            if (BaseConfig.Enabled)
            {
                AttachToOwinApp(config, app);
            }
        }
 public ODataV1FeedController(
     IEntityRepository<Package> packagesRepository,
     IGalleryConfigurationService configurationService,
     ISearchService searchService)
     : base(configurationService)
 {
     _packagesRepository = packagesRepository;
     _configurationService = configurationService;
     _searchService = searchService;
 }
 public ODataV2CuratedFeedController(
     IEntitiesContext entities,
     IGalleryConfigurationService configurationService,
     ISearchService searchService,
     ICuratedFeedService curatedFeedService)
     : base(configurationService)
 {
     _entities = entities;
     _configurationService = configurationService;
     _searchService = searchService;
     _curatedFeedService = curatedFeedService;
 }
        protected override void AttachToOwinApp(IGalleryConfigurationService config, IAppBuilder app)
        {
            var cookieSecurity = config.Current.RequireSSL ?
                CookieSecureOption.Always :
                CookieSecureOption.Never;

            var options = new CookieAuthenticationOptions
            {
                AuthenticationType = AuthenticationTypes.LocalUser,
                AuthenticationMode = AuthenticationMode.Active,
                CookieHttpOnly = true,
                CookieSecure = cookieSecurity,
                LoginPath = new PathString("/users/account/LogOn"),
                ExpireTimeSpan = TimeSpan.FromHours(6),
                SlidingExpiration = true
            };

            BaseConfig.ApplyToOwinSecurityOptions(options);
            app.UseCookieAuthentication(options);
            app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.LocalUser);
        }
 // Configuration Logic
 protected virtual async Task Configure(IGalleryConfigurationService config)
 {
     BaseConfig = await config.ResolveConfigObject(BaseConfig, AuthPrefix + Name + ".");
 }
 protected virtual void AttachToOwinApp(IGalleryConfigurationService config, IAppBuilder app)
 {
 }
 public HomeController(IContentService content, IGalleryConfigurationService config)
 {
     _content = content ?? throw new ArgumentNullException(nameof(content));
     _config  = config ?? throw new ArgumentNullException(nameof(config));
 }
Beispiel #11
0
 public SecretReaderFactory(IGalleryConfigurationService configurationService)
 {
     _configurationService = configurationService ?? throw new ArgumentNullException(nameof(configurationService));
 }
 public ConfigController(IGalleryConfigurationService config, AuthenticationService auth)
 {
     _config = config;
     _auth = auth;
 }
 private static void ConfigureSearch(ContainerBuilder builder, IGalleryConfigurationService configuration)
 {
     if (configuration.Current.ServiceDiscoveryUri == null)
     {
         builder.RegisterType<LuceneSearchService>()
             .AsSelf()
             .As<ISearchService>()
             .InstancePerLifetimeScope();
         builder.RegisterType<LuceneIndexingService>()
             .AsSelf()
             .As<IIndexingService>()
             .InstancePerLifetimeScope();
     }
     else
     {
         builder.RegisterType<ExternalSearchService>()
             .AsSelf()
             .As<ISearchService>()
             .As<IIndexingService>()
             .InstancePerLifetimeScope();
     }
 }
        private static IAuditingService GetAuditingServiceForAzureStorage(ContainerBuilder builder, IGalleryConfigurationService configuration)
        {
            string instanceId;

            try
            {
                instanceId = RoleEnvironment.CurrentRoleInstance.Id;
            }
            catch
            {
                instanceId = Environment.MachineName;
            }

            var localIp = AuditActor.GetLocalIpAddressAsync().Result;

            var service = new CloudAuditingService(instanceId, localIp, configuration.Current.AzureStorage_Auditing_ConnectionString, AuditActor.GetAspNetOnBehalfOfAsync);

            builder.RegisterInstance(service)
            .As <ICloudStorageStatusDependency>()
            .SingleInstance();

            return(service);
        }
        private static void ConfigureForLocalFileSystem(ContainerBuilder builder, IGalleryConfigurationService configuration)
        {
            builder.RegisterType<FileSystemFileStorageService>()
                .AsSelf()
                .As<IFileStorageService>()
                .SingleInstance();

            builder.RegisterInstance(NullReportService.Instance)
                .AsSelf()
                .As<IReportService>()
                .SingleInstance();

            builder.RegisterInstance(NullStatisticsService.Instance)
                .AsSelf()
                .As<IStatisticsService>()
                .SingleInstance();

            // Setup auditing
            var auditingPath = Path.Combine(
                FileSystemFileStorageService.ResolvePath(configuration.Current.FileStorageDirectory),
                FileSystemAuditingService.DefaultContainerName);

            builder.RegisterInstance(new FileSystemAuditingService(auditingPath, FileSystemAuditingService.GetAspNetOnBehalfOf))
                .AsSelf()
                .As<AuditingService>()
                .SingleInstance();

            // If we're not using azure storage, then aggregate stats comes from SQL
            builder.RegisterType<SqlAggregateStatsService>()
                .AsSelf()
                .As<IAggregateStatsService>()
                .InstancePerLifetimeScope();
        }
 protected override void AttachToOwinApp(IGalleryConfigurationService config, IAppBuilder app)
 {
     AttachedTo = app;
     base.AttachToOwinApp(config, app);
 }
Beispiel #17
0
        private static List <(string name, Uri searchUri)> GetPreviewSearchClientsFromConfiguration(IGalleryConfigurationService configuration)
        {
            var searchClients = new List <(string name, Uri searchUri)>();

            if (configuration.Current.PreviewSearchServiceUriPrimary != null)
            {
                searchClients.Add((SearchClientConfiguration.PreviewSearchPrimaryInstance, configuration.Current.PreviewSearchServiceUriPrimary));
            }
            if (configuration.Current.PreviewSearchServiceUriSecondary != null)
            {
                searchClients.Add((SearchClientConfiguration.PreviewSearchSecondaryInstance, configuration.Current.PreviewSearchServiceUriSecondary));
            }

            return(searchClients);
        }
 // Configuration Logic
 protected virtual async Task Configure(IGalleryConfigurationService config)
 {
     BaseConfig = await config.ResolveConfigObject(BaseConfig, AuthPrefix + Name + ".");
 }
 protected virtual void AttachToOwinApp(IGalleryConfigurationService config, IAppBuilder app) { }
 protected override ODataV1FeedController CreateController(IEntityRepository <Package> packagesRepository,
                                                           IGalleryConfigurationService configurationService, ISearchService searchService)
 {
     return(new ODataV1FeedController(packagesRepository, configurationService, searchService));
 }
 public ApiController(
     IEntitiesContext entitiesContext,
     IPackageService packageService,
     IPackageFileService packageFileService,
     IUserService userService,
     INuGetExeDownloaderService nugetExeDownloaderService,
     IContentService contentService,
     IIndexingService indexingService,
     ISearchService searchService,
     IAutomaticallyCuratePackageCommand autoCuratePackage,
     IStatusService statusService,
     IStatisticsService statisticsService,
     IMessageService messageService,
     AuditingService auditingService,
     IGalleryConfigurationService configurationService)
     : this(entitiesContext, packageService, packageFileService, userService, nugetExeDownloaderService, contentService, indexingService, searchService, autoCuratePackage, statusService, messageService, auditingService, configurationService)
 {
     StatisticsService = statisticsService;
 }
        private static void ConfigureForAzureStorage(ContainerBuilder builder, IGalleryConfigurationService configuration)
        {
            /// The goal here is to initialize a <see cref="ICloudBlobClient"/> and <see cref="IFileStorageService"/>
            /// instance for each unique connection string. Each dependent of <see cref="IFileStorageService"/> (that
            /// is, each service that has a <see cref="IFileStorageService"/> constructor parameter) is registered in
            /// <see cref="StorageDependent.GetAll(IAppConfiguration)"/> and is grouped by the respective storage
            /// connection string. Each group is given a binding key which refers to the appropriate instance of the
            /// <see cref="IFileStorageService"/>.
            var completedBindingKeys = new HashSet <string>();

            foreach (var dependent in StorageDependent.GetAll(configuration.Current))
            {
                if (completedBindingKeys.Add(dependent.BindingKey))
                {
                    builder.RegisterInstance(new CloudBlobClientWrapper(dependent.AzureStorageConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant))
                    .AsSelf()
                    .As <ICloudBlobClient>()
                    .SingleInstance()
                    .Keyed <ICloudBlobClient>(dependent.BindingKey);

                    builder.RegisterType <CloudBlobFileStorageService>()
                    .WithParameter(new ResolvedParameter(
                                       (pi, ctx) => pi.ParameterType == typeof(ICloudBlobClient),
                                       (pi, ctx) => ctx.ResolveKeyed <ICloudBlobClient>(dependent.BindingKey)))
                    .AsSelf()
                    .As <IFileStorageService>()
                    .As <ICloudStorageStatusDependency>()
                    .SingleInstance()
                    .Keyed <IFileStorageService>(dependent.BindingKey);
                }

                var registration = builder.RegisterType(dependent.ImplementationType)
                                   .WithParameter(new ResolvedParameter(
                                                      (pi, ctx) => pi.ParameterType == typeof(IFileStorageService),
                                                      (pi, ctx) => ctx.ResolveKeyed <IFileStorageService>(dependent.BindingKey)))
                                   .AsSelf()
                                   .As(dependent.InterfaceType);

                if (dependent.IsSingleInstance)
                {
                    registration.SingleInstance();
                }
                else
                {
                    registration.InstancePerLifetimeScope();
                }
            }

            // when running on Windows Azure, we use a back-end job to calculate stats totals and store in the blobs
            builder.RegisterInstance(new JsonAggregateStatsService(configuration.Current.AzureStorage_Statistics_ConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant))
            .AsSelf()
            .As <IAggregateStatsService>()
            .SingleInstance();

            // when running on Windows Azure, pull the statistics from the warehouse via storage
            builder.RegisterInstance(new CloudReportService(configuration.Current.AzureStorage_Statistics_ConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant))
            .AsSelf()
            .As <IReportService>()
            .As <ICloudStorageStatusDependency>()
            .SingleInstance();

            // when running on Windows Azure, download counts come from the downloads.v1.json blob
            var downloadCountService = new CloudDownloadCountService(configuration.Current.AzureStorage_Statistics_ConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant);

            builder.RegisterInstance(downloadCountService)
            .AsSelf()
            .As <IDownloadCountService>()
            .SingleInstance();
            ObjectMaterializedInterception.AddInterceptor(new DownloadCountObjectMaterializedInterceptor(downloadCountService));

            builder.RegisterType <JsonStatisticsService>()
            .AsSelf()
            .As <IStatisticsService>()
            .SingleInstance();

            builder.RegisterInstance(new TableErrorLog(configuration.Current.AzureStorage_Errors_ConnectionString))
            .As <ErrorLog>()
            .SingleInstance();
        }
        public static IHtmlString PreFormattedText(this HtmlHelper self, string text, IGalleryConfigurationService configurationService)
        {
            // Encode HTML entities. Important! Security!
            var encodedText = HttpUtility.HtmlEncode(text);

            // Turn HTTP and HTTPS URLs into links.
            // Source: https://stackoverflow.com/a/4750468
            string anchorEvaluator(Match match)
            {
                string trimmedEntityValue = string.Empty;
                string trimmedAnchorValue = match.Value;

                foreach (var trimmedEntity in _trimmedHtmlEntities)
                {
                    if (match.Value.EndsWith(trimmedEntity))
                    {
                        // Remove trailing html entity from anchor URL
                        trimmedAnchorValue = match.Value.Substring(0, match.Value.Length - trimmedEntity.Length);
                        trimmedEntityValue = trimmedEntity;

                        break;
                    }
                }

                if (PackageHelper.TryPrepareUrlForRendering(trimmedAnchorValue, out string formattedUri))
                {
                    string anchorText = formattedUri;
                    string siteRoot   = configurationService.GetSiteRoot(useHttps: true);
                    // Format links to NuGet packages
                    Match packageMatch = RegexEx.MatchWithTimeout(formattedUri, $@"({Regex.Escape(siteRoot)}\/packages\/(?<name>\w+([_.-]\w+)*(\/[0-9a-zA-Z-.]+)?)\/?$)", RegexOptions.IgnoreCase);
                    if (packageMatch != null && packageMatch.Groups["name"].Success)
                    {
                        anchorText = packageMatch.Groups["name"].Value;
                    }

                    return($"<a href=\"{formattedUri}\" rel=\"nofollow\">{anchorText}</a>" + trimmedEntityValue);
                }

                return(match.Value);
            }

            encodedText = RegexEx.TryReplaceWithTimeout(
                encodedText,
                @"((http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)",
                anchorEvaluator,
                RegexOptions.IgnoreCase);

            // Replace new lines with the <br /> tag.
            encodedText = encodedText.Replace("\n", "<br />");

            // Replace more than one space in a row with a space then &nbsp;.
            encodedText = RegexEx.TryReplaceWithTimeout(
                encodedText,
                "  +",
                match => " " + string.Join(string.Empty, Enumerable.Repeat("&nbsp;", match.Value.Length - 1)),
                RegexOptions.None);

            return(self.Raw(encodedText));
        }
 public ISecretReader CreateSecretReader(IGalleryConfigurationService configurationService)
 {
     return new EmptySecretReader();
 }
Beispiel #25
0
 internal static void SetConfigurationService(IGalleryConfigurationService configurationService)
 {
     _configuration = configurationService;
 }
        private static void ConfigureAutocomplete(ContainerBuilder builder, IGalleryConfigurationService configuration)
        {
            if (configuration.Current.ServiceDiscoveryUri != null &&
                !string.IsNullOrEmpty(configuration.Current.AutocompleteServiceResourceType))
            {
                builder.RegisterType<AutocompleteServicePackageIdsQuery>()
                    .AsSelf()
                    .As<IPackageIdsQuery>()
                    .SingleInstance();

                builder.RegisterType<AutocompleteServicePackageVersionsQuery>()
                    .AsSelf()
                    .As<IPackageVersionsQuery>()
                    .InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType<PackageIdsQuery>()
                    .AsSelf()
                    .As<IPackageIdsQuery>()
                    .InstancePerLifetimeScope();

                builder.RegisterType<PackageVersionsQuery>()
                    .AsSelf()
                    .As<IPackageVersionsQuery>()
                    .InstancePerLifetimeScope();
            }
        }
Beispiel #27
0
 public static TestableMessageService Create(
     AuthenticationService authenticationService,
     IGalleryConfigurationService configurationService)
 {
     return(new TestableMessageService(authenticationService, configurationService));
 }
        private static void ConfigureForAzureStorage(ContainerBuilder builder, IGalleryConfigurationService configuration)
        {
            builder.RegisterInstance(new CloudBlobClientWrapper(configuration.Current.AzureStorageConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant))
                .AsSelf()
                .As<ICloudBlobClient>()
                .SingleInstance();

            builder.RegisterType<CloudBlobFileStorageService>()
                .AsSelf()
                .As<IFileStorageService>()
                .SingleInstance();

            // when running on Windows Azure, we use a back-end job to calculate stats totals and store in the blobs
            builder.RegisterInstance(new JsonAggregateStatsService(configuration.Current.AzureStorageConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant))
                .AsSelf()
                .As<IAggregateStatsService>()
                .SingleInstance();

            // when running on Windows Azure, pull the statistics from the warehouse via storage
            builder.RegisterInstance(new CloudReportService(configuration.Current.AzureStorageConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant))
                .AsSelf()
                .As<IReportService>()
                .SingleInstance();

            // when running on Windows Azure, download counts come from the downloads.v1.json blob
            var downloadCountService = new CloudDownloadCountService(configuration.Current.AzureStorageConnectionString, configuration.Current.AzureStorageReadAccessGeoRedundant);
            builder.RegisterInstance(downloadCountService)
                .AsSelf()
                .As<IDownloadCountService>()
                .SingleInstance();
            ObjectMaterializedInterception.AddInterceptor(new DownloadCountObjectMaterializedInterceptor(downloadCountService));

            builder.RegisterType<JsonStatisticsService>()
                .AsSelf()
                .As<IStatisticsService>()
                .SingleInstance();

            string instanceId;
            try
            {
                instanceId = RoleEnvironment.CurrentRoleInstance.Id;
            }
            catch
            {
                instanceId = Environment.MachineName;
            }

            var localIp = AuditActor.GetLocalIP().Result;

            builder.RegisterInstance(new CloudAuditingService(instanceId, localIp, configuration.Current.AzureStorageConnectionString, CloudAuditingService.GetAspNetOnBehalfOf))
                .AsSelf()
                .As<AuditingService>()
                .SingleInstance();
        }
Beispiel #29
0
 public ConfigController(IGalleryConfigurationService config, AuthenticationService auth)
 {
     _config = config;
     _auth   = auth;
 }
 public static TestableMarkdownMessageService Create(IGalleryConfigurationService configurationService)
 {
     configurationService.Current.SmtpUri = new Uri("smtp://fake.mail.server");
     return(new TestableMarkdownMessageService(configurationService));
 }
        private static void ConfigureSearch(
            ILoggerFactory loggerFactory,
            IGalleryConfigurationService configuration,
            ITelemetryService telemetryService,
            ServiceCollection services,
            ContainerBuilder builder)
        {
            var searchClients = GetSearchClientsFromConfiguration(configuration);

            if (searchClients.Count >= 1)
            {
                services.AddTransient <CorrelatingHttpClientHandler>();
                services.AddTransient((s) => new TracingHttpHandler(DependencyResolver.Current.GetService <IDiagnosticsService>().SafeGetSource("ExternalSearchService")));

                // Register the default search service implementation and its dependencies.
                RegisterSearchService(
                    loggerFactory,
                    configuration,
                    telemetryService,
                    services,
                    builder,
                    searchClients);

                // Register the preview search service and its dependencies with a binding key.
                var previewSearchClients = GetPreviewSearchClientsFromConfiguration(configuration);
                RegisterSearchService(
                    loggerFactory,
                    configuration,
                    telemetryService,
                    services,
                    builder,
                    previewSearchClients,
                    BindingKeys.PreviewSearchClient);
            }
            else
            {
                builder.RegisterType <LuceneSearchService>()
                .AsSelf()
                .As <ISearchService>()
                .Keyed <ISearchService>(BindingKeys.PreviewSearchClient)
                .InstancePerLifetimeScope();
                builder.RegisterType <LuceneIndexingService>()
                .AsSelf()
                .As <IIndexingService>()
                .As <IIndexingJobFactory>()
                .InstancePerLifetimeScope();
            }

            builder
            .Register(c => new SearchSideBySideService(
                          c.Resolve <ISearchService>(),
                          c.ResolveKeyed <ISearchService>(BindingKeys.PreviewSearchClient),
                          c.Resolve <ITelemetryService>(),
                          c.Resolve <IMessageService>(),
                          c.Resolve <IMessageServiceConfiguration>()))
            .As <ISearchSideBySideService>()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <PackagesController>()
            .WithParameter(new ResolvedParameter(
                               (pi, ctx) => pi.ParameterType == typeof(ISearchService) && pi.Name == ParameterNames.PackagesController_PreviewSearchService,
                               (pi, ctx) => ctx.ResolveKeyed <ISearchService>(BindingKeys.PreviewSearchClient)))
            .As <PackagesController>()
            .InstancePerLifetimeScope();
        }