private static void AddRouting(OrchardCoreBuilder builder)
 {
     stackVariable0 = builder;
     stackVariable1 = Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__6_0;
     if (stackVariable1 == null)
     {
         dummyVar0      = stackVariable1;
         stackVariable1 = new Action <IServiceCollection>(Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9.u003cAddRoutingu003eb__6_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__6_0 = stackVariable1;
     }
     dummyVar1 = stackVariable0.ConfigureServices(stackVariable1, -2147483548);
     return;
 }
        private static void AddExtensionServices(OrchardCoreBuilder builder)
        {
            builder.ApplicationServices.AddSingleton <IModuleNamesProvider, AssemblyAttributeModuleNamesProvider>();
            builder.ApplicationServices.AddSingleton <IApplicationContext, ModularApplicationContext>();

            builder.ApplicationServices.AddExtensionManagerHost();

            builder.ConfigureServices(services =>
            {
                services.AddExtensionManager();
                services.AddScoped <IShellFeaturesManager, ShellFeaturesManager>();
                services.AddScoped <IShellDescriptorFeaturesManager, ShellDescriptorFeaturesManager>();
            });
        }
 private static void AddAntiForgery(OrchardCoreBuilder builder)
 {
     dummyVar0      = AntiforgeryServiceCollectionExtensions.AddAntiforgery(builder.get_ApplicationServices());
     stackVariable3 = builder;
     stackVariable4 = Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__7_0;
     if (stackVariable4 == null)
     {
         dummyVar1      = stackVariable4;
         stackVariable4 = new Action <IServiceCollection, IServiceProvider>(Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9.u003cAddAntiForgeryu003eb__7_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__7_0 = stackVariable4;
     }
     dummyVar2 = stackVariable3.ConfigureServices(stackVariable4, 0);
     return;
 }
 public static OrchardCoreBuilder WithFeatures(this OrchardCoreBuilder builder, params string[] featureIds)
 {
     V_0 = featureIds;
     V_1 = 0;
     while (V_1 < (int)V_0.Length)
     {
         V_2           = new OrchardCoreBuilderExtensions.u003cu003ec__DisplayClass4_0();
         V_2.featureId = V_0[V_1];
         dummyVar0     = ServiceCollectionServiceExtensions.AddTransient <ShellFeature>(builder.get_ApplicationServices(), new Func <IServiceProvider, ShellFeature>(V_2.u003cWithFeaturesu003eb__0));
         V_1           = V_1 + 1;
     }
     dummyVar1 = builder.get_ApplicationServices().AddSetFeaturesDescriptor();
     return(builder);
 }
        /// <summary>
        /// Registers tenants defined in configuration.
        /// </summary>
        public static OrchardCoreBuilder WithTenants(this OrchardCoreBuilder builder)
        {
            var services = builder.ApplicationServices;

            services.AddSingleton <IShellsSettingsSources, ShellsSettingsSources>();
            services.AddSingleton <IShellsConfigurationSources, ShellsConfigurationSources>();
            services.AddSingleton <IShellConfigurationSources, ShellConfigurationSources>();
            services.AddTransient <IConfigureOptions <ShellOptions>, ShellOptionsSetup>();
            services.AddSingleton <IShellSettingsManager, ShellSettingsManager>();

            return(builder.ConfigureServices(s =>
            {
                s.AddScoped <IShellDescriptorManager, ConfiguredFeaturesShellDescriptorManager>();
            }));
        }
        /// <summary>
        /// Adds tenant level services to keep in sync any single <see cref="IDocument"/> between an <see cref="IDocumentStore"/> and a multi level cache.
        /// </summary>
        public static OrchardCoreBuilder AddDocumentManagement(this OrchardCoreBuilder builder)
        {
            return(builder.ConfigureServices(services =>
            {
                services.AddScoped(typeof(IDocumentManager <>), typeof(DocumentManager <>));
                services.AddScoped(typeof(IVolatileDocumentManager <>), typeof(VolatileDocumentManager <>));
                services.AddScoped(typeof(IDocumentManager <,>), typeof(DocumentManager <,>));

                services.TryAddEnumerable(ServiceDescriptor.Singleton <IConfigureOptions <DocumentOptions>, DocumentOptionsSetup>());

                services.AddScoped(typeof(IDocumentEntityManager <>), typeof(DocumentEntityManager <>));
                services.AddScoped(typeof(IVolatileDocumentEntityManager <>), typeof(VolatileDocumentEntityManager <>));
                services.AddScoped(typeof(IDocumentEntityManager <,>), typeof(DocumentEntityManager <,>));
            }));
        }
Esempio n. 7
0
        /// <summary>
        /// Adds host and tenant level antiforgery services.
        /// </summary>
        private static void AddAntiForgery(OrchardCoreBuilder builder)
        {
            builder.ApplicationServices.AddAntiforgery();

            builder.ConfigureServices((services, serviceProvider) =>
            {
                var settings    = serviceProvider.GetRequiredService <ShellSettings>();
                var environment = serviceProvider.GetRequiredService <IHostEnvironment>();

                var cookieName = "orchantiforgery_" + HttpUtility.UrlEncode(settings.Name + environment.ContentRootPath);

                // If uninitialized, we use the host services.
                if (settings.State == TenantState.Uninitialized)
                {
                    // And delete a cookie that may have been created by another instance.
                    var httpContextAccessor = serviceProvider.GetRequiredService <IHttpContextAccessor>();

                    // Use case when creating a container without ambient context.
                    if (httpContextAccessor.HttpContext == null)
                    {
                        return;
                    }

                    // Use case when creating a container in a deferred task.
                    if (httpContextAccessor.HttpContext.Response.HasStarted)
                    {
                        return;
                    }

                    httpContextAccessor.HttpContext.Response.Cookies.Delete(cookieName);

                    return;
                }

                // Re-register the antiforgery  services to be tenant-aware.
                var collection = new ServiceCollection()
                                 .AddAntiforgery(options =>
                {
                    options.Cookie.Name = cookieName;

                    // Don't set the cookie builder 'Path' so that it uses the 'IAuthenticationFeature' value
                    // set by the pipeline and comming from the request 'PathBase' which already ends with the
                    // tenant prefix but may also start by a path related e.g to a virtual folder.
                });

                services.Add(collection);
            });
        }
Esempio n. 8
0
 /// <summary>
 /// Adds backwards compatibility to the handling of SameSite cookies.
 /// </summary>
 private static void AddSameSiteCookieBackwardsCompatibility(OrchardCoreBuilder builder)
 {
     builder.ConfigureServices(services =>
     {
         services.Configure <CookiePolicyOptions>(options =>
         {
             options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
             options.OnAppendCookie        = cookieContext => CheckSameSiteBackwardsCompatiblity(cookieContext.Context, cookieContext.CookieOptions);
             options.OnDeleteCookie        = cookieContext => CheckSameSiteBackwardsCompatiblity(cookieContext.Context, cookieContext.CookieOptions);
         });
     })
     .Configure(app =>
     {
         app.UseCookiePolicy();
     });
 }
 private static void AddExtensionServices(OrchardCoreBuilder builder)
 {
     dummyVar0       = ServiceCollectionServiceExtensions.AddSingleton <IModuleNamesProvider, AssemblyAttributeModuleNamesProvider>(builder.get_ApplicationServices());
     dummyVar1       = ServiceCollectionServiceExtensions.AddSingleton <IApplicationContext, ModularApplicationContext>(builder.get_ApplicationServices());
     dummyVar2       = builder.get_ApplicationServices().AddExtensionManagerHost();
     stackVariable9  = builder;
     stackVariable10 = Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__4_0;
     if (stackVariable10 == null)
     {
         dummyVar3       = stackVariable10;
         stackVariable10 = new Action <IServiceCollection>(Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9.u003cAddExtensionServicesu003eb__4_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__4_0 = stackVariable10;
     }
     dummyVar4 = stackVariable9.ConfigureServices(stackVariable10, 0);
     return;
 }
Esempio n. 10
0
        /// <summary>
        /// Adds html script sanitization services.
        /// </summary>
        /// <param name="builder">The <see cref="OrchardCoreBuilder"/>.</param>
        public static OrchardCoreBuilder AddHtmlSanitizer(this OrchardCoreBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.AddOptions <HtmlSanitizerOptions>();

                services.ConfigureHtmlSanitizer((sanitizer) =>
                {
                    sanitizer.AllowedAttributes.Add("class");
                });

                services.AddSingleton <IHtmlSanitizerService, HtmlSanitizerService>();
            });

            return(builder);
        }
Esempio n. 11
0
        /// <summary>
        /// Adds tenant level data protection services.
        /// </summary>
        private static void AddDataProtection(OrchardCoreBuilder builder)
        {
            builder.ConfigureServices((services, serviceProvider) =>
            {
                var settings = serviceProvider.GetRequiredService <ShellSettings>();
                var options  = serviceProvider.GetRequiredService <IOptions <ShellOptions> >();

                var directory = Directory.CreateDirectory(Path.Combine(
                                                              options.Value.ShellsApplicationDataPath,
                                                              options.Value.ShellsContainerName,
                                                              settings.Name, "DataProtection-Keys"));

                // Re-register the data protection services to be tenant-aware so that modules that internally
                // rely on IDataProtector/IDataProtectionProvider automatically get an isolated instance that
                // manages its own key ring and doesn't allow decrypting payloads encrypted by another tenant.
                // By default, the key ring is stored in the tenant directory of the configured App_Data path.
                var collection = new ServiceCollection()
                                 .AddDataProtection()
                                 .PersistKeysToFileSystem(directory)
                                 .SetApplicationName(settings.Name)
                                 .Services;

                // Retrieve the implementation type of the newly startup filter registered as a singleton
                var startupFilterType = collection.FirstOrDefault(s => s.ServiceType == typeof(IStartupFilter))?.ImplementationType;

                if (startupFilterType != null)
                {
                    // Remove any previously registered data protection startup filters.
                    var descriptors = services.Where(s => s.ServiceType == typeof(IStartupFilter) &&
                                                     (s.ImplementationInstance?.GetType() == startupFilterType ||
                                                      s.ImplementationType == startupFilterType)).ToArray();

                    foreach (var descriptor in descriptors)
                    {
                        services.Remove(descriptor);
                    }
                }

                // Remove any previously registered options setups.
                services.RemoveAll <IConfigureOptions <KeyManagementOptions> >();
                services.RemoveAll <IConfigureOptions <DataProtectionOptions> >();

                services.Add(collection);
            });
        }
 public static OrchardCoreBuilder WithTenants(this OrchardCoreBuilder builder)
 {
     stackVariable1 = builder.get_ApplicationServices();
     dummyVar0      = ServiceCollectionServiceExtensions.AddSingleton <IShellsSettingsSources, ShellsSettingsSources>(stackVariable1);
     dummyVar1      = ServiceCollectionServiceExtensions.AddSingleton <IShellsConfigurationSources, ShellsConfigurationSources>(stackVariable1);
     dummyVar2      = ServiceCollectionServiceExtensions.AddSingleton <IShellConfigurationSources, ShellConfigurationSources>(stackVariable1);
     dummyVar3      = ServiceCollectionServiceExtensions.AddTransient <IConfigureOptions <ShellOptions>, ShellOptionsSetup>(stackVariable1);
     dummyVar4      = ServiceCollectionServiceExtensions.AddSingleton <IShellSettingsManager, ShellSettingsManager>(stackVariable1);
     stackVariable7 = builder;
     stackVariable8 = OrchardCoreBuilderExtensions.u003cu003ec.u003cu003e9__3_0;
     if (stackVariable8 == null)
     {
         dummyVar5      = stackVariable8;
         stackVariable8 = new Action <IServiceCollection>(OrchardCoreBuilderExtensions.u003cu003ec.u003cu003e9.u003cWithTenantsu003eb__3_0);
         OrchardCoreBuilderExtensions.u003cu003ec.u003cu003e9__3_0 = stackVariable8;
     }
     return(stackVariable7.ConfigureServices(stackVariable8, 0));
 }
Esempio n. 13
0
        /// <summary>
        /// Adds host and tenant level antiforgery services.
        /// </summary>
        private static void AddAntiForgery(OrchardCoreBuilder builder)
        {
            builder.ApplicationServices.AddAntiforgery();

            builder.ConfigureServices((services, serviceProvider) =>
            {
                var settings = serviceProvider.GetRequiredService <ShellSettings>();

                var tenantName   = settings.Name;
                var tenantPrefix = "/" + settings.RequestUrlPrefix;

                services.AddAntiforgery(options =>
                {
                    options.Cookie.Name = "orchantiforgery_" + tenantName;
                    options.Cookie.Path = tenantPrefix;
                });
            });
        }
Esempio n. 14
0
        /// <summary>
        /// Adds host and tenant level authentication services and configuration.
        /// </summary>
        private static void AddAuthentication(OrchardCoreBuilder builder)
        {
            builder.ApplicationServices.AddAuthentication();

            builder.ConfigureServices(services =>
            {
                services.AddAuthentication();

                // IAuthenticationSchemeProvider is already registered at the host level.
                // We need to register it again so it is taken into account at the tenant level
                // because it holds a reference to an underlying dictionary, responsible of storing
                // the registered schemes which need to be distinct for each tenant.
                services.AddSingleton <IAuthenticationSchemeProvider, AuthenticationSchemeProvider>();
            })
            .Configure(app =>
            {
                app.UseAuthentication();
            });
        }
        public static OrchardCoreBuilder ConfigureSecuritySettings(this OrchardCoreBuilder builder)
        {
            builder.ConfigureServices((tenantServices, serviceProvider) =>
            {
                var configurationSection = serviceProvider.GetRequiredService <IShellConfiguration>().GetSection("OrchardCore_Security");

                tenantServices.PostConfigure <SecuritySettings>(settings =>
                {
                    settings.ContentSecurityPolicy.Clear();
                    settings.PermissionsPolicy.Clear();

                    configurationSection.Bind(settings);

                    settings.FromConfiguration = true;
                });
            });

            return(builder);
        }
Esempio n. 16
0
        /// <summary>
        /// Adds tenant level caching services.
        /// </summary>
        public static OrchardCoreBuilder AddCaching(this OrchardCoreBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.AddSingleton <ISignal>(sp =>
                {
                    var messageBus = sp.GetService <IMessageBus>();

                    if (messageBus == null)
                    {
                        return(new Signal());
                    }
                    else
                    {
                        return(new DistributedSignal(messageBus));
                    }
                });

                services.AddSingleton <IModularTenantEvents>(sp => sp.GetRequiredService <ISignal>());

                services.AddScoped <ITagCache, DefaultTagCache>();
                services.AddScoped <ICacheContextManager, CacheContextManager>();
                services.AddScoped <ICacheScopeManager, CacheScopeManager>();

                services.AddScoped <ICacheContextProvider, FeaturesCacheContextProvider>();
                services.AddScoped <ICacheContextProvider, QueryCacheContextProvider>();
                services.AddScoped <ICacheContextProvider, RolesCacheContextProvider>();
                services.AddScoped <ICacheContextProvider, RouteCacheContextProvider>();
                services.AddScoped <ICacheContextProvider, UserCacheContextProvider>();
                services.AddScoped <ICacheContextProvider, KnownValueCacheContextProvider>();

                // IMemoryCache is registered at the tenant level so that there is one instance for each tenant.
                services.AddSingleton <IMemoryCache, MemoryCache>();

                // MemoryDistributedCache needs to be registered as a singleton as it owns a MemoryCache instance.
                services.AddSingleton <IDistributedCache, MemoryDistributedCache>();

                // Provides a distributed cache service that can return existing references in the current scope.
                services.AddScoped <IScopedDistributedCache, ScopedDistributedCache>();
            });

            return(builder);
        }
 public static OrchardCoreBuilder AddOrchardCore(this IServiceCollection services)
 {
     if (services == null)
     {
         throw new ArgumentNullException("services");
     }
     stackVariable1 = services;
     stackVariable2 = Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__0_0;
     if (stackVariable2 == null)
     {
         dummyVar0      = stackVariable2;
         stackVariable2 = new Func <ServiceDescriptor, bool>(Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9.u003cAddOrchardCoreu003eb__0_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__0_0 = stackVariable2;
     }
     stackVariable3 = stackVariable1.LastOrDefault <ServiceDescriptor>(stackVariable2);
     if (stackVariable3 != null)
     {
         stackVariable4 = stackVariable3.get_ImplementationInstance();
     }
     else
     {
         dummyVar1      = stackVariable3;
         stackVariable4 = null;
     }
     V_0 = stackVariable4 as OrchardCoreBuilder;
     if (V_0 == null)
     {
         V_0       = new OrchardCoreBuilder(services);
         dummyVar2 = ServiceCollectionServiceExtensions.AddSingleton <OrchardCoreBuilder>(services, V_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddDefaultServices(services);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddShellServices(services);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddExtensionServices(V_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddStaticFiles(V_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddRouting(V_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddAntiForgery(V_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddSameSiteCookieBackwardsCompatibility(V_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddAuthentication(V_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddDataProtection(V_0);
         dummyVar3 = ServiceCollectionServiceExtensions.AddSingleton <IServiceCollection>(services, services);
     }
     return(V_0);
 }
Esempio n. 18
0
        /// <summary>
        /// Adds tenant level services.
        /// </summary>
        public static OrchardCoreBuilder AddSecurity(this OrchardCoreBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.AddAuthorization();

                services.Configure <AuthenticationOptions>((options) =>
                {
                    if (!options.Schemes.Any(x => x.Name == "Api"))
                    {
                        options.AddScheme <ApiAuthenticationHandler>("Api", null);
                    }
                });

                services.AddScoped <IPermissionGrantingService, DefaultPermissionGrantingService>();
                services.AddScoped <IAuthorizationHandler, PermissionHandler>();
            });

            return(builder);
        }
        /// <summary>
        /// Adds tenant level caching services.
        /// </summary>
        public static OrchardCoreBuilder AddCaching(this OrchardCoreBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.AddSingleton <ISignal>(sp =>
                {
                    var messageBus = sp.GetService <IMessageBus>();

                    if (messageBus == null)
                    {
                        return(new Signal());
                    }
                    else
                    {
                        return(new DistributedSignal(messageBus));
                    }
                });

                services.AddSingleton <IModularTenantEvents>(sp => sp.GetRequiredService <ISignal>());

                services.AddScoped <ITagCache, DefaultTagCache>();
                services.AddScoped <ICacheContextManager, CacheContextManager>();
                services.AddScoped <ICacheScopeManager, CacheScopeManager>();

                services.AddScoped <ICacheContextProvider, FeaturesCacheContextProvider>();
                services.AddScoped <ICacheContextProvider, QueryCacheContextProvider>();
                services.AddScoped <ICacheContextProvider, RolesCacheContextProvider>();
                services.AddScoped <ICacheContextProvider, RouteCacheContextProvider>();
                services.AddScoped <ICacheContextProvider, UserCacheContextProvider>();
                services.AddScoped <ICacheContextProvider, KnownValueCacheContextProvider>();

                // IMemoryCache is registered at the tenant level so that there is one instance for each tenant.
                services.AddSingleton <IMemoryCache, MemoryCache>();

                // MemoryDistributedCache needs to be registered as a singleton as it owns a MemoryCache instance.
                services.AddSingleton <IDistributedCache, MemoryDistributedCache>();
            });

            // Adds services to keep in sync any document type between a document store and a multi level cache.
            return(builder.AddDocumentManagement());
        }
 private static void AddSameSiteCookieBackwardsCompatibility(OrchardCoreBuilder builder)
 {
     stackVariable0 = builder;
     stackVariable1 = Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__8_0;
     if (stackVariable1 == null)
     {
         dummyVar0      = stackVariable1;
         stackVariable1 = new Action <IServiceCollection>(Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9.u003cAddSameSiteCookieBackwardsCompatibilityu003eb__8_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__8_0 = stackVariable1;
     }
     stackVariable3 = stackVariable0.ConfigureServices(stackVariable1, 0);
     stackVariable4 = Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__8_1;
     if (stackVariable4 == null)
     {
         dummyVar1      = stackVariable4;
         stackVariable4 = new Action <IApplicationBuilder>(Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9.u003cAddSameSiteCookieBackwardsCompatibilityu003eb__8_1);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__8_1 = stackVariable4;
     }
     dummyVar2 = stackVariable3.Configure(stackVariable4, 0);
     return;
 }
 private static void AddStaticFiles(OrchardCoreBuilder builder)
 {
     stackVariable0 = builder;
     stackVariable1 = Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__5_0;
     if (stackVariable1 == null)
     {
         dummyVar0      = stackVariable1;
         stackVariable1 = new Action <IServiceCollection>(Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9.u003cAddStaticFilesu003eb__5_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__5_0 = stackVariable1;
     }
     dummyVar1      = stackVariable0.ConfigureServices(stackVariable1, 0);
     stackVariable4 = builder;
     stackVariable5 = Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__5_1;
     if (stackVariable5 == null)
     {
         dummyVar2      = stackVariable5;
         stackVariable5 = new Action <IApplicationBuilder, IEndpointRouteBuilder, IServiceProvider>(Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9.u003cAddStaticFilesu003eb__5_1);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__5_1 = stackVariable5;
     }
     dummyVar3 = stackVariable4.Configure(stackVariable5, 0);
     return;
 }
 private static void AddAuthentication(OrchardCoreBuilder builder)
 {
     dummyVar0      = AuthenticationServiceCollectionExtensions.AddAuthentication(builder.get_ApplicationServices());
     stackVariable3 = builder;
     stackVariable4 = Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__10_0;
     if (stackVariable4 == null)
     {
         dummyVar1      = stackVariable4;
         stackVariable4 = new Action <IServiceCollection>(Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9.u003cAddAuthenticationu003eb__10_0);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__10_0 = stackVariable4;
     }
     stackVariable6 = stackVariable3.ConfigureServices(stackVariable4, 0);
     stackVariable7 = Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__10_1;
     if (stackVariable7 == null)
     {
         dummyVar2      = stackVariable7;
         stackVariable7 = new Action <IApplicationBuilder>(Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9.u003cAddAuthenticationu003eb__10_1);
         Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.u003cu003ec.u003cu003e9__10_1 = stackVariable7;
     }
     dummyVar3 = stackVariable6.Configure(stackVariable7, 0);
     return;
 }
        /// <summary>
        /// Adds tenant level services for managing liquid view template files.
        /// </summary>
        public static OrchardCoreBuilder AddLiquidViews(this OrchardCoreBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.TryAddEnumerable(
                    ServiceDescriptor.Transient <IConfigureOptions <LiquidViewOptions>,
                                                 LiquidViewOptionsSetup>());

                services.TryAddEnumerable(
                    ServiceDescriptor.Transient <IConfigureOptions <ShapeTemplateOptions>,
                                                 LiquidShapeTemplateOptionsSetup>());

                services.TryAddSingleton <ILiquidViewFileProviderAccessor, LiquidViewFileProviderAccessor>();
                services.AddSingleton <IApplicationFeatureProvider <ViewsFeature>, LiquidViewsFeatureProvider>();
                services.AddScoped <IRazorViewExtensionProvider, LiquidViewExtensionProvider>();
                services.AddSingleton <LiquidTagHelperFactory>();

                services.AddScoped <ILiquidTemplateEventHandler, RequestLiquidTemplateEventHandler>();
            });

            return(builder);
        }
Esempio n. 24
0
        /// <summary>
        /// Adds tenant level configuration to serve static files from modules
        /// </summary>
        private static void AddStaticFiles(OrchardCoreBuilder builder)
        {
            builder.Configure((app, routes, serviceProvider) =>
            {
                var env        = serviceProvider.GetRequiredService <IHostingEnvironment>();
                var appContext = serviceProvider.GetRequiredService <IApplicationContext>();

                IFileProvider fileProvider;
                if (env.IsDevelopment())
                {
                    var fileProviders = new List <IFileProvider>();
                    fileProviders.Add(new ModuleProjectStaticFileProvider(appContext));
                    fileProviders.Add(new ModuleEmbeddedStaticFileProvider(appContext));
                    fileProvider = new CompositeFileProvider(fileProviders);
                }
                else
                {
                    fileProvider = new ModuleEmbeddedStaticFileProvider(appContext);
                }

                var options = serviceProvider.GetRequiredService <IOptions <StaticFileOptions> >().Value;

                options.RequestPath  = "";
                options.FileProvider = fileProvider;

                var shellConfiguration = serviceProvider.GetRequiredService <IShellConfiguration>();

                var cacheControl = shellConfiguration.GetValue("StaticFileOptions:CacheControl", "public, max-age=2592000, s-max-age=31557600");

                // Cache static files for a year as they are coming from embedded resources and should not vary
                options.OnPrepareResponse = ctx =>
                {
                    ctx.Context.Response.Headers[HeaderNames.CacheControl] = cacheControl;
                };

                app.UseStaticFiles(options);
            });
        }
        /// <summary>
        /// Adds host and tenant level antiforgery services.
        /// </summary>
        private static void AddAntiForgery(OrchardCoreBuilder builder)
        {
            builder.ApplicationServices.AddAntiforgery();

            builder.ConfigureServices((services, serviceProvider) =>
            {
                var settings   = serviceProvider.GetRequiredService <ShellSettings>();
                var cookieName = "__orchantiforgery_" + settings.VersionId;

                // Re-register the antiforgery services to be tenant-aware.
                var collection = new ServiceCollection()
                                 .AddAntiforgery(options =>
                {
                    options.Cookie.Name = cookieName;

                    // Don't set the cookie builder 'Path' so that it uses the 'IAuthenticationFeature' value
                    // set by the pipeline and comming from the request 'PathBase' which already ends with the
                    // tenant prefix but may also start by a path related e.g to a virtual folder.
                });

                services.Add(collection);
            });
        }
        /// <summary>
        /// Adds tenant level data protection services.
        /// </summary>
        private static void AddDataProtection(OrchardCoreBuilder builder)
        {
            builder.ConfigureServices((services, serviceProvider) =>
            {
                var settings = serviceProvider.GetRequiredService <ShellSettings>();
                var options  = serviceProvider.GetRequiredService <IOptions <ShellOptions> >();

                var directory = Directory.CreateDirectory(Path.Combine(
                                                              options.Value.ShellsApplicationDataPath,
                                                              options.Value.ShellsContainerName,
                                                              settings.Name, "DataProtection-Keys"));

                // Re-register the data protection services to be tenant-aware so that modules that internally
                // rely on IDataProtector/IDataProtectionProvider automatically get an isolated instance that
                // manages its own key ring and doesn't allow decrypting payloads encrypted by another tenant.
                // By default, the key ring is stored in the tenant directory of the configured App_Data path.
                services.Add(new ServiceCollection()
                             .AddDataProtection()
                             .PersistKeysToFileSystem(directory)
                             .SetApplicationName(settings.Name)
                             .Services);
            });
        }
Esempio n. 27
0
        private static void AddDefaultServices(OrchardCoreBuilder builder)
        {
            var services = builder.ApplicationServices;

            services.AddLogging();
            services.AddOptions();

            // These services might be moved at a higher level if no components from OrchardCore needs them.
            services.AddLocalization();

            // For performance, prevents the 'ResourceManagerStringLocalizer' from being used.
            // Also support pluralization.
            services.AddSingleton <IStringLocalizerFactory, NullStringLocalizerFactory>();
            services.AddSingleton <IHtmlLocalizerFactory, NullHtmlLocalizerFactory>();

            services.AddWebEncoders();

            services.AddHttpContextAccessor();
            services.AddSingleton <IClock, Clock>();
            services.AddScoped <ILocalClock, LocalClock>();

            services.AddScoped <ILocalizationService, DefaultLocalizationService>();
            services.AddScoped <ICalendarManager, DefaultCalendarManager>();
            services.AddScoped <ICalendarSelector, DefaultCalendarSelector>();

            services.AddSingleton <IPoweredByMiddlewareOptions, PoweredByMiddlewareOptions>();

            services.AddScoped <IOrchardHelper, DefaultOrchardHelper>();

            builder.ConfigureServices(s =>
            {
                s.AddSingleton <LocalLock>();
                s.AddSingleton <ILock>(sp => sp.GetRequiredService <LocalLock>());
                s.AddSingleton <IDistributedLock>(sp => sp.GetRequiredService <LocalLock>());
            });
        }
        /// <summary>
        /// Adds OrchardCore services to the host service collection.
        /// </summary>
        public static OrchardCoreBuilder AddOrchardCore(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            // If an instance of OrchardCoreBuilder exists reuse it,
            // so we can call AddOrchardCore several times.
            var builder = services
                          .LastOrDefault(d => d.ServiceType == typeof(OrchardCoreBuilder))?
                          .ImplementationInstance as OrchardCoreBuilder;

            if (builder == null)
            {
                builder = new OrchardCoreBuilder(services);
                services.AddSingleton(builder);

                AddDefaultServices(builder);
                AddShellServices(builder);
                AddExtensionServices(builder);
                AddStaticFiles(builder);

                AddRouting(builder);
                AddEndpointsApiExplorer(builder);
                AddAntiForgery(builder);
                AddSameSiteCookieBackwardsCompatibility(builder);
                AddAuthentication(builder);
                AddDataProtection(builder);

                // Register the list of services to be resolved later on
                services.AddSingleton(services);
            }

            return(builder);
        }
Esempio n. 29
0
 /// <summary>
 /// Allow Mini Profiler on the admin too when the feature is enabled, not just on the frontend.
 /// </summary>
 public static OrchardCoreBuilder AllowMiniProfilerOnAdmin(this OrchardCoreBuilder builder)
 {
     return(builder.ConfigureServices(services =>
                                      services.Configure <MiniProfilerOptions>(settings => settings.AllowOnAdmin = true)));
 }
Esempio n. 30
0
        /// <summary>
        /// Adds tenant level data access services.
        /// </summary>
        /// <param name="builder">The <see cref="OrchardCoreBuilder"/>.</param>
        public static OrchardCoreBuilder AddDataAccess(this OrchardCoreBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.AddScoped <IDataMigrationManager, DataMigrationManager>();
                services.AddScoped <IModularTenantEvents, AutomaticDataMigrations>();

                services.AddOptions <StoreCollectionOptions>();
                services.AddTransient <IConfigureOptions <SqliteOptions>, SqliteOptionsConfiguration>();

                // Adding supported databases
                services.TryAddDataProvider(name: "Sql Server", value: "SqlConnection", hasConnectionString: true, sampleConnectionString: "Server=localhost;Database=Orchard;User Id=username;Password=password", hasTablePrefix: true, isDefault: false);
                services.TryAddDataProvider(name: "Sqlite", value: "Sqlite", hasConnectionString: false, hasTablePrefix: false, isDefault: true);
                services.TryAddDataProvider(name: "MySql", value: "MySql", hasConnectionString: true, sampleConnectionString: "Server=localhost;Database=Orchard;Uid=username;Pwd=password", hasTablePrefix: true, isDefault: false);
                services.TryAddDataProvider(name: "Postgres", value: "Postgres", hasConnectionString: true, sampleConnectionString: "Server=localhost;Port=5432;Database=Orchard;User Id=username;Password=password", hasTablePrefix: true, isDefault: false);

                // Configuring data access

                services.AddSingleton(sp =>
                {
                    var shellSettings = sp.GetService <ShellSettings>();

                    // Before the setup a 'DatabaseProvider' may be configured without a required 'ConnectionString'.
                    if (shellSettings.State == TenantState.Uninitialized || shellSettings["DatabaseProvider"] == null)
                    {
                        return(null);
                    }

                    IConfiguration storeConfiguration = new YesSql.Configuration
                    {
                        ContentSerializer = new PoolingJsonContentSerializer(sp.GetService <ArrayPool <char> >()),
                    };

                    switch (shellSettings["DatabaseProvider"])
                    {
                    case "SqlConnection":
                        storeConfiguration
                        .UseSqlServer(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted)
                        .UseBlockIdGenerator();
                        break;

                    case "Sqlite":
                        var shellOptions            = sp.GetService <IOptions <ShellOptions> >();
                        var sqliteOptions           = sp.GetService <IOptions <SqliteOptions> >()?.Value ?? new SqliteOptions();
                        var option                  = shellOptions.Value;
                        var databaseFolder          = Path.Combine(option.ShellsApplicationDataPath, option.ShellsContainerName, shellSettings.Name);
                        var databaseFile            = Path.Combine(databaseFolder, "yessql.db");
                        var connectionStringBuilder = new SqliteConnectionStringBuilder
                        {
                            DataSource = databaseFile,
                            Cache      = SqliteCacheMode.Shared,
                            Pooling    = sqliteOptions.UseConnectionPooling
                        };

                        Directory.CreateDirectory(databaseFolder);
                        storeConfiguration
                        .UseSqLite(connectionStringBuilder.ToString(), IsolationLevel.ReadUncommitted)
                        .UseDefaultIdGenerator();
                        break;

                    case "MySql":
                        storeConfiguration
                        .UseMySql(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted)
                        .UseBlockIdGenerator();
                        break;

                    case "Postgres":
                        storeConfiguration
                        .UsePostgreSql(shellSettings["ConnectionString"], IsolationLevel.ReadUncommitted)
                        .UseBlockIdGenerator();
                        break;

                    default:
                        throw new ArgumentException("Unknown database provider: " + shellSettings["DatabaseProvider"]);
                    }

                    if (!string.IsNullOrWhiteSpace(shellSettings["TablePrefix"]))
                    {
                        storeConfiguration = storeConfiguration.SetTablePrefix(shellSettings["TablePrefix"] + "_");
                    }

                    var store   = StoreFactory.CreateAndInitializeAsync(storeConfiguration).GetAwaiter().GetResult();
                    var options = sp.GetService <IOptions <StoreCollectionOptions> >().Value;
                    foreach (var collection in options.Collections)
                    {
                        store.InitializeCollectionAsync(collection).GetAwaiter().GetResult();
                    }

                    var indexes = sp.GetServices <IIndexProvider>();

                    store.RegisterIndexes(indexes);

                    return(store);
                });

                services.AddScoped(sp =>
                {
                    var store = sp.GetService <IStore>();

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

                    var session = store.CreateSession();

                    var scopedServices = sp.GetServices <IScopedIndexProvider>();

                    session.RegisterIndexes(scopedServices.ToArray());

                    ShellScope.Current
                    .RegisterBeforeDispose(scope =>
                    {
                        return(scope.ServiceProvider
                               .GetRequiredService <IDocumentStore>()
                               .CommitAsync());
                    })
                    .AddExceptionHandler((scope, e) =>
                    {
                        return(scope.ServiceProvider
                               .GetRequiredService <IDocumentStore>()
                               .CancelAsync());
                    });

                    return(session);
                });

                services.AddScoped <IDocumentStore, DocumentStore>();
                services.AddSingleton <IFileDocumentStore, FileDocumentStore>();

                services.AddTransient <IDbConnectionAccessor, DbConnectionAccessor>();
            });

            return(builder);
        }