Ejemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <TaskMaintenanceServiceHealthCheck>();
            services.AddSingleton <StartupHealthCheck>();
            services.AddHealthChecks()
            .AddCheck <TaskMaintenanceServiceHealthCheck>(
                "task_service_responsive",
                failureStatus: HealthStatus.Unhealthy,
                tags: new[] { "live" })
            .AddCheck <StartupHealthCheck>(
                "startup",
                failureStatus: HealthStatus.Degraded,
                tags: new[] { "ready" });

            var provider = Configuration["Database:Provider"];

            switch (provider)
            {
            case "InMemory":
                services.AddDbContextPool <SteamfitterContext>((serviceProvider, optionsBuilder) => optionsBuilder
                                                               .AddInterceptors(serviceProvider.GetRequiredService <EventTransactionInterceptor>())
                                                               .UseInMemoryDatabase("api"));
                break;

            case "Sqlite":
            case "SqlServer":
            case "PostgreSQL":
                services.AddDbContextPool <SteamfitterContext>((serviceProvider, optionsBuilder) => optionsBuilder
                                                               .AddInterceptors(serviceProvider.GetRequiredService <EventTransactionInterceptor>())
                                                               .UseConfiguredDatabase(Configuration));
                break;
            }

            var connectionString = Configuration.GetConnectionString(DatabaseExtensions.DbProvider(Configuration));

            switch (provider)
            {
            case "Sqlite":
                services.AddHealthChecks().AddSqlite(connectionString, tags: new[] { "ready", "live" });
                break;

            case "SqlServer":
                services.AddHealthChecks().AddSqlServer(connectionString, tags: new[] { "ready", "live" });
                break;

            case "PostgreSQL":
                services.AddHealthChecks().AddNpgSql(connectionString, tags: new[] { "ready", "live" });
                break;
            }

            services.AddOptions()
            .Configure <DatabaseOptions>(Configuration.GetSection("Database"))
            .AddScoped(config => config.GetService <IOptionsMonitor <DatabaseOptions> >().CurrentValue)

            .Configure <ClaimsTransformationOptions>(Configuration.GetSection("ClaimsTransformation"))
            .AddScoped(config => config.GetService <IOptionsMonitor <ClaimsTransformationOptions> >().CurrentValue)

            .Configure <SeedDataOptions>(Configuration.GetSection("SeedData"))
            .AddScoped(config => config.GetService <IOptionsMonitor <SeedDataOptions> >().CurrentValue);

            services
            .Configure <ClientOptions>(Configuration.GetSection("ClientSettings"))
            .AddScoped(config => config.GetService <IOptionsMonitor <ClientOptions> >().CurrentValue);

            services
            .Configure <FilesOptions>(Configuration.GetSection("Files"))
            .AddScoped(config => config.GetService <IOptionsMonitor <FilesOptions> >().CurrentValue);

            services.AddScoped <IPlayerVmService, PlayerVmService>();
            services.AddScoped <IPlayerService, PlayerService>();
            services.AddScoped <IClaimsTransformation, AuthorizationClaimsTransformer>();
            services.AddScoped <IUserClaimsService, UserClaimsService>();

            services.AddCors(options => options.UseConfiguredCors(Configuration.GetSection("CorsPolicy")));

            services.AddSignalR()
            .AddJsonProtocol(options =>
            {
                options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ValidateModelStateFilter));
                options.Filters.Add(typeof(JsonExceptionFilter));

                // Require all scopes in authOptions
                var policyBuilder = new AuthorizationPolicyBuilder().RequireAuthenticatedUser();
                Array.ForEach(_authOptions.AuthorizationScope.Split(' '), x => policyBuilder.RequireScope(x));

                var policy = policyBuilder.Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonNullableGuidConverter());
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });

            services.AddSwagger(_authOptions);
            services.AddPlayerApiClient();
            services.AddPlayerVmApiClient();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority                 = _authOptions.Authority;
                options.RequireHttpsMetadata      = _authOptions.RequireHttpsMetadata;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidAudiences = _authOptions.AuthorizationScope.Split(' ')
                };
            });

            services.AddRouting(options =>
            {
                options.LowercaseUrls = true;
            });

            services.AddMemoryCache();

            services.AddScoped <IScenarioService, ScenarioService>();
            services.AddScoped <ITaskService, TaskService>();
            services.AddScoped <IResultService, ResultService>();
            services.AddScoped <IScenarioTemplateService, ScenarioTemplateService>();
            services.AddScoped <IPermissionService, PermissionService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IUserPermissionService, UserPermissionService>();
            services.AddScoped <IFilesService, FilesService>();
            services.AddScoped <IBondAgentService, BondAgentService>();
            services.AddScoped <IVmCredentialService, VmCredentialService>();
            services.AddSingleton <StackStormService>();
            services.AddSingleton <IHostedService>(x => x.GetService <StackStormService>());
            services.AddSingleton <IStackStormService>(x => x.GetService <StackStormService>());
            services.AddSingleton <BondAgentStore>();
            services.AddSingleton <ITaskExecutionQueue, TaskExecutionQueue>();
            services.AddHostedService <TaskExecutionService>();
            services.AddHostedService <TaskMaintenanceService>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <IPrincipal>(p => p.GetService <IHttpContextAccessor>().HttpContext.User);
            services.AddHttpClient();
            services.AddScoped <IScoringService, ScoringService>();

            ApplyPolicies(services);

            services.AddAutoMapper(cfg =>
            {
                cfg.ForAllPropertyMaps(
                    pm => pm.SourceType != null && Nullable.GetUnderlyingType(pm.SourceType) == pm.DestinationType,
                    (pm, c) => c.MapFrom <object, object, object, object>(new IgnoreNullSourceValues(), pm.SourceMember.Name));
            }, typeof(Startup));

            services.Configure <VmTaskProcessingOptions>(Configuration.GetSection("VmTaskProcessing"));
            services
            .Configure <ResourceOwnerAuthorizationOptions>(Configuration.GetSection("ResourceOwnerAuthorization"))
            .AddScoped(config => config.GetService <IOptionsMonitor <ResourceOwnerAuthorizationOptions> >().CurrentValue);

            services.AddTransient <EventTransactionInterceptor>();
            services.AddMediatR(typeof(Startup));
        }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var provider = Configuration["Database:Provider"];

            switch (provider)
            {
            case "InMemory":
                services.AddDbContextPool <AlloyContext>((ServiceProvider, builder) => builder
                                                         .AddInterceptors(ServiceProvider.GetRequiredService <EventTransactionInterceptor>())
                                                         .UseInMemoryDatabase("api"));
                break;

            case "Sqlite":
            case "SqlServer":
            case "PostgreSQL":
                services.AddDbContextPool <AlloyContext>((serviceProvider, builder) => builder
                                                         .AddInterceptors(serviceProvider.GetRequiredService <EventTransactionInterceptor>())
                                                         .UseConfiguredDatabase(Configuration));
                break;
            }

            services.AddSingleton <StartupHealthCheck>();
            services.AddSingleton <HostedServiceHealthCheck>();
            services.AddHealthChecks()
            .AddCheck <StartupHealthCheck>(
                "startup",
                failureStatus: HealthStatus.Degraded,
                tags: new[] { "ready" })
            .AddCheck <HostedServiceHealthCheck>(
                "service_responsive",
                failureStatus: HealthStatus.Unhealthy,
                tags: new[] { "live" });

            var connectionString = Configuration.GetConnectionString(DatabaseExtensions.DbProvider(Configuration));

            switch (provider)
            {
            case "Sqlite":
                services.AddHealthChecks().AddSqlite(connectionString, tags: new[] { "ready", "live" });
                break;

            case "SqlServer":
                services.AddHealthChecks().AddSqlServer(connectionString, tags: new[] { "ready", "live" });
                break;

            case "PostgreSQL":
                services.AddHealthChecks().AddNpgSql(connectionString, tags: new[] { "ready", "live" });
                break;
            }

            services.AddOptions()
            .Configure <DatabaseOptions>(Configuration.GetSection("Database"))
            .AddScoped(config => config.GetService <IOptionsMonitor <DatabaseOptions> >().CurrentValue)

            .Configure <ClaimsTransformationOptions>(Configuration.GetSection("ClaimsTransformation"))
            .AddScoped(config => config.GetService <IOptionsMonitor <ClaimsTransformationOptions> >().CurrentValue);

            services
            .Configure <ClientOptions>(Configuration.GetSection("ClientSettings"))
            .AddScoped(config => config.GetService <IOptionsMonitor <ClientOptions> >().CurrentValue);

            services
            .Configure <FilesOptions>(Configuration.GetSection("Files"))
            .AddScoped(config => config.GetService <IOptionsMonitor <FilesOptions> >().CurrentValue);

            services
            .Configure <ResourceOwnerAuthorizationOptions>(Configuration.GetSection("ResourceOwnerAuthorization"))
            .AddScoped(config => config.GetService <IOptionsMonitor <ResourceOwnerAuthorizationOptions> >().CurrentValue);

            services
            .Configure <ResourceOptions>(Configuration.GetSection("Resource"))
            .AddScoped(config => config.GetService <IOptionsMonitor <ResourceOptions> >().CurrentValue);

            services.AddCors(options => options.UseConfiguredCors(Configuration.GetSection("CorsPolicy")));

            services.AddSignalR()
            .AddJsonProtocol(options =>
            {
                options.PayloadSerializerOptions.PropertyNameCaseInsensitive = true;
                options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                options.PayloadSerializerOptions.Converters.Add(new JsonDateTimeConverter());
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ValidateModelStateFilter));
                options.Filters.Add(typeof(JsonExceptionFilter));

                // Require all scopes in authOptions
                var policyBuilder = new AuthorizationPolicyBuilder().RequireAuthenticatedUser();
                Array.ForEach(_authOptions.AuthorizationScope.Split(' '), x => policyBuilder.RequireScope(x));

                var policy = policyBuilder.Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonNullableGuidConverter());
                // options.JsonSerializerOptions.Converters.Add(new JsonIntegerConverter());
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                options.JsonSerializerOptions.Converters.Add(new JsonDateTimeConverter());
            });

            services.AddSwagger(_authOptions);

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority                 = _authOptions.Authority;
                options.RequireHttpsMetadata      = _authOptions.RequireHttpsMetadata;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidAudiences = _authOptions.AuthorizationScope.Split(' ')
                };

                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        // If the request is for our hub...
                        var path        = context.HttpContext.Request.Path;
                        var accessToken = context.Request.Query["access_token"];

                        if (!string.IsNullOrEmpty(accessToken) &&
                            (path.StartsWithSegments("/hubs")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddRouting(options =>
            {
                options.LowercaseUrls = true;
            });

            services.AddMemoryCache();

            services.AddScoped <IEventTemplateService, EventTemplateService>();
            services.AddScoped <IEventService, EventService>();
            services.AddScoped <ICasterService, CasterService>();
            services.AddScoped <IPlayerService, PlayerService>();
            services.AddScoped <ISteamfitterService, SteamfitterService>();
            services.AddScoped <IUserClaimsService, UserClaimsService>();
            services.AddTransient <EventTransactionInterceptor>();

            // add the other API clients
            services.AddPlayerApiClient();
            services.AddCasterApiClient();
            services.AddSteamfitterApiClient();

            // add the background IHostedServices
            services.AddAlloyBackgroundService();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <IPrincipal>(p => p.GetService <IHttpContextAccessor>().HttpContext.User);

            services.AddHttpClient();

            ApplyPolicies(services);

            services.AddAutoMapper(cfg =>
            {
                cfg.ForAllPropertyMaps(
                    pm => pm.SourceType != null && Nullable.GetUnderlyingType(pm.SourceType) == pm.DestinationType,
                    (pm, c) => c.MapFrom <object, object, object, object>(new IgnoreNullSourceValues(), pm.SourceMember.Name));
            }, typeof(Startup));

            services.AddMediatR(typeof(Startup).GetTypeInfo().Assembly);
            services.AddScoped <IClaimsTransformation, AuthorizationClaimsTransformer>();
        }
Ejemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var provider = Configuration["Database:Provider"];

            switch (provider)
            {
            case "InMemory":
                services.AddDbContextPool <PlayerContext>((serviceProvider, opt) => opt
                                                          .AddInterceptors(serviceProvider.GetRequiredService <EventTransactionInterceptor>())
                                                          .UseInMemoryDatabase("api"));
                break;

            case "Sqlite":
            case "SqlServer":
            case "PostgreSQL":
                services.AddDbContextPool <PlayerContext>((serviceProvider, builder) => builder
                                                          .AddInterceptors(serviceProvider.GetRequiredService <EventTransactionInterceptor>())
                                                          .UseConfiguredDatabase(Configuration));
                break;
            }
            var connectionString = Configuration.GetConnectionString(DatabaseExtensions.DbProvider(Configuration));

            switch (provider)
            {
            case "Sqlite":
                services.AddHealthChecks().AddSqlite(connectionString, tags: new[] { "ready", "live" });
                break;

            case "SqlServer":
                services.AddHealthChecks().AddSqlServer(connectionString, tags: new[] { "ready", "live" });
                break;

            case "PostgreSQL":
                services.AddHealthChecks().AddNpgSql(connectionString, tags: new[] { "ready", "live" });
                break;
            }


            services.AddOptions()
            .Configure <DatabaseOptions>(Configuration.GetSection("Database"))
            .AddScoped(config => config.GetService <IOptionsMonitor <DatabaseOptions> >().CurrentValue)

            .Configure <ClaimsTransformationOptions>(Configuration.GetSection("ClaimsTransformation"))
            .AddScoped(config => config.GetService <IOptionsMonitor <ClaimsTransformationOptions> >().CurrentValue)

            .Configure <SeedDataOptions>(Configuration.GetSection("SeedData"))
            .AddScoped(config => config.GetService <IOptionsMonitor <SeedDataOptions> >().CurrentValue)

            .Configure <FileUploadOptions>(Configuration.GetSection("FileUpload"))
            .AddScoped(config => config.GetService <IOptionsMonitor <FileUploadOptions> >().CurrentValue)

            .Configure <Player.Api.Options.AuthorizationOptions>(Configuration.GetSection("Authorization"))
            .AddSingleton(config => config.GetService <IOptionsMonitor <Player.Api.Options.AuthorizationOptions> >().CurrentValue);

            services.AddCors(options => options.UseConfiguredCors(Configuration.GetSection("CorsPolicy")));

            services.AddSignalR()
            .AddJsonProtocol(options =>
            {
                options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ValidateModelStateFilter));
                options.Filters.Add(typeof(JsonExceptionFilter));
            })
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });

            services.AddSwagger(_authOptions);

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority            = _authOptions.Authority;
                options.RequireHttpsMetadata = _authOptions.RequireHttpsMetadata;
                options.Audience             = _authOptions.AuthorizationScope;
                options.SaveToken            = true;
            });

            services.AddRouting(options =>
            {
                options.LowercaseUrls = true;
            });

            services.AddMemoryCache();
            services.AddMediatR(typeof(Startup));
            services.AddTransient <EventTransactionInterceptor>();

            services.AddScoped <IViewService, ViewService>();
            services.AddScoped <IApplicationService, ApplicationService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ITeamService, TeamService>();
            services.AddScoped <INotificationService, NotificationService>();
            services.AddScoped <IPermissionService, PermissionService>();
            services.AddScoped <IRoleService, RoleService>();
            services.AddScoped <IViewMembershipService, ViewMembershipService>();
            services.AddScoped <ITeamMembershipService, TeamMembershipService>();
            services.AddScoped <IFileService, FileService>();
            services.AddScoped <IPresenceService, PresenceService>();
            services.AddScoped <IWebhookService, WebhookService>();

            services.AddScoped <IClaimsTransformation, AuthorizationClaimsTransformer>();
            services.AddScoped <IUserClaimsService, UserClaimsService>();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <IPrincipal>(p => p.GetService <IHttpContextAccessor>().HttpContext.User);

            services.AddSingleton <ConnectionCacheService>();
            services.AddSingleton <BackgroundWebhookService>();
            services.AddSingleton <IHostedService>(x => x.GetService <BackgroundWebhookService>());
            services.AddSingleton <IBackgroundWebhookService>(x => x.GetService <BackgroundWebhookService>());
            services.AddHttpClient();

            ApplyPolicies(services);

            services.AddAutoMapper(cfg =>
            {
                cfg.ForAllPropertyMaps(
                    pm => pm.SourceType != null && Nullable.GetUnderlyingType(pm.SourceType) == pm.DestinationType,
                    (pm, c) => c.MapFrom <object, object, object, object>(new IgnoreNullSourceValues(), pm.SourceMember.Name));
            }, typeof(Startup));
        }