Beispiel #1
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, SetupNotRunAuthorizationRequirement requirement)
        {
            if (context.Resource is Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext mvcContext)
            {
                HttpContext httpContext = mvcContext.HttpContext;

                RequestAppSetupState appSetupState = httpContext.RequestServices.GetRequiredService <RequestAppSetupState>();

                if (!await appSetupState.HasBeenSetup())
                {
                    context.Succeed(requirement);
                    return;
                }
            }

            context.Fail();
        }
Beispiel #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            if (!String.Equals(this.Configuration["DISABLE_TELEMETRY"], "True", StringComparison.OrdinalIgnoreCase))
            {
                services.AddApplicationInsightsTelemetry(this.Configuration);
            }

            services.Configure <DatabaseOptions>(this.Configuration.GetSection("database"));
            services.Configure <ServerOptions>(this.Configuration.GetSection("server"));
            services.Configure <HttpsServerOptions>(this.Configuration.GetSection("server").GetSection("https"));
            services.Configure <MailSettings>(this.Configuration.GetSection("mail"));
            services.Configure <DiagnosticsOptions>(this.Configuration.GetSection("diagnostics"));

            services.AddResponseCompression(opts =>
            {
                // Note the possible dangers for HTTPS: https://docs.microsoft.com/en-us/aspnet/core/performance/response-compression?tabs=aspnetcore2x#compression-with-secure-protocol
                opts.EnableForHttps = true;
            });

            services.AddConfiguredDataProtection(this.Configuration);

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(HttpStatusExceptionFilterAttribute));
                options.Filters.Add(typeof(ModelStateCamelCaseFilter));
                options.Filters.Add(typeof(ApiCachePreventionFilterAttribute));
                options.Filters.Add(typeof(SetupRequiredFilterAttribute));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddIdentity <AppUser, AppRole>(
                options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;

                options.Lockout.AllowedForNewUsers      = true;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(15);
                options.Lockout.MaxFailedAccessAttempts = 5;
            })
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders()
            .AddUserValidator <AppUserValidator>()
            .AddRoleValidator <AppRoleValidator>()
            .AddPasswordValidator <AppPasswordValidator>()
            .AddUserManager <AppUserManager>()
            .AddRoleManager <AppRoleManager>()
            .AddUserStore <AppUserStore>()
            .AddRoleStore <AppRoleStore>();

            services.ConfigureApplicationCookie(
                opt =>
            {
                opt.LoginPath         = new PathString("/Account/Login");
                opt.ExpireTimeSpan    = TimeSpan.FromDays(365 / 2d);
                opt.SlidingExpiration = true;

                // Override cookie validator until setup has been completed
                Func <CookieValidatePrincipalContext, Task> existingHandler = opt.Events.OnValidatePrincipal;
                opt.Events.OnValidatePrincipal = async(ctx) =>
                {
                    RequestAppSetupState setupState = ctx.HttpContext.RequestServices.GetRequiredService <RequestAppSetupState>();

                    if (await setupState.HasBeenSetup())
                    {
                        await existingHandler(ctx);
                    }
                    else
                    {
                        ctx.RejectPrincipal();
                    }
                };
            }
                );

            services.AddAuthorization(opt =>
            {
                opt.AddPolicy("AppSetup", policy => policy.AddRequirements(new SetupNotRunAuthorizationRequirement()));
            });

            services.AddSignalR()
            .AddJsonProtocol(options => options.PayloadSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());

            services.AddDbContext <AppDbContext>();

            services.AddHangfire(c =>
            {
#if DEBUG
                c.UseMemoryStorage();
#else
                DatabaseOptions dbOptions = this.Configuration.GetSection("database").Get <DatabaseOptions>();
                c.UseSqlServerStorage(dbOptions.CreateConnectionString());
#endif
            });

            // DI
            services.AddScoped <AppDbContext>();
            services.AddScoped <DbContext>(sp => sp.GetRequiredService <AppDbContext>());
            services.AddScoped <DbConnection>(sp => sp.GetRequiredService <DbContext>().Database.GetDbConnection());
            services.AddScoped <AppUserManager>();
            services.AddScoped <AppUserStore>();

            services.AddScoped <AppOwnerRepository>();
            services.AddScoped <CategoryRepository>();
            services.AddScoped <RecurringSheetEntryRepository>();
            services.AddScoped <SheetEntryRepository>();
            services.AddScoped <SheetLastVisitedMarkerRepository>();
            services.AddScoped <SheetRepository>();
            services.AddScoped <TagRepository>();

            services.AddScoped <SheetRetrievalService>();
            services.AddScoped <EntityOwnerService>();
            services.AddScoped <SheetOffsetCalculationService>();
            services.AddScoped <SheetStatisticsService>();
            services.AddScoped <BudgetRetrievalService>();

            services.AddScoped <SheetLastVisitedMarkerService>();
            services.AddScoped <DelayedSheetVisitUpdateMarkerJob>();
            services.AddScoped <DelayedSheetVisitUpdateJobInvoker>();

            services.AddAutoMapper();

            services.AddSingleton <IAppVersionService, AppVersionService>();

            services.AddSingleton <IBuildAssetVersionCache, BuildAssetVersionCache>();

            // ... Impersonation
            services.AddScoped <AppUserTrustedUserRepository>();
            services.AddScoped <AppImpersonationTokenService>();
            services.AddScoped <AppOwnerTokenChangeService>();

            // ... Setup
            services.AddScoped <SetupService>();
            services.AddScoped <SetupStepFactory>();
            services.AddScoped <RequestAppSetupState>();
            services.AddSingleton <AppSetupState>();

            services.AddScoped <AuthenticationInfoFactory>();
            services.AddSingleton <IAuthorizationHandler, SetupNotRunAuthorizationHandler>();

            // ... Mail
            services.AddScoped <MailService>();
            services.AddScoped <TemplateProvider>();

            // Needed for TemplateProvider
            services.AddSingleton <ISiteUrlDetectionService, SiteUrlDetectionService>();

            // ... Mailers
            services.AddScoped <TwoFactorChangeNotificationMailer>();
            services.AddScoped <PasswordChangeNotificationMailer>();
            services.AddScoped <ForgotPasswordMailer>();
            services.AddScoped <ConfirmEmailMailer>();

            // ... Monthly digest
            services.AddScoped <MonthlyDigestInvocationJob>();
            services.AddScoped <MonthlyDigestForAppOwnerJob>();
            services.AddScoped <MonthlyDigestMailer>();
            services.AddScoped <MonthlyDigestDataFactory>();

            // ... App login notification
            services.AddScoped <AppUserLoginEventRepository>();
            services.AddScoped <AppUserLoginEventService>();
            services.AddScoped <AppUserLoginEventMailer>();

            // ... Startup health checks
            services.AddStartupChecks();
        }