protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Cities",
                columns: table => new
            {
                Id = table.Column <int>(nullable: false)
                     .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
                Name    = table.Column <string>(nullable: true),
                ZipCode = table.Column <string>(nullable: true)
            },
                constraints: table =>
            {
                table.PrimaryKey("PK_Cities", x => x.Id);
            });

            migrationBuilder.CreateTable(
                name: "WeatherForecasts",
                columns: table => new
            {
                Id = table.Column <int>(nullable: false)
                     .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
                Date        = table.Column <DateTime>(nullable: false),
                Temperature = table.Column <double>(nullable: false),
                Humidity    = table.Column <double>(nullable: false),
                WindSpeed   = table.Column <double>(nullable: false),
                CityId      = table.Column <int>(nullable: true)
            },
                constraints: table =>
            {
                table.PrimaryKey("PK_WeatherForecasts", x => x.Id);
                table.ForeignKey(
                    name: "FK_WeatherForecasts_Cities_CityId",
                    column: x => x.CityId,
                    principalTable: "Cities",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
            });


            SeedDataProvider.SeedGeneralData(migrationBuilder);

            migrationBuilder.CreateIndex(
                name: "IX_WeatherForecasts_CityId",
                table: "WeatherForecasts",
                column: "CityId");
        }
        private void SeedDelegations()
        {
            Logger.LogInformation("Seed Delegations");

            var delegations          = SeedDataProvider.GetEntities <Delegation>("delegations.json", Environment);
            var delegationsHistories = SeedDataProvider.GetEntities <DelegationHistory>("delegationsHistories.json", Environment);

            foreach (var delegation in delegations)
            {
                delegation.Policy = SeedDataProvider.GetRaw($"policies.{delegation.AuthorizationRegistryId}.json", Environment);
                Context.Set <Delegation>().AddOrUpdate(delegation);
            }

            foreach (var history in delegationsHistories)
            {
                var delegation = delegations.First(c => c.Id == history.DelegationId);
                history.Policy = SeedDataProvider.GetRaw($"policies.{delegation.AuthorizationRegistryId}.json", Environment);
                Context.Set <DelegationHistory>().AddOrUpdate(history);
            }
        }
Beispiel #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // register shutdown clean-up in application lifetime service
            lifetime.ApplicationStopped.Register(() =>
            {
                // clean up sqlite in-memory connection
                if (_connection != null)
                {
                    _connection.Dispose();
                }
            });

            // create migration for database, and create if it doesn't already exist
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                using (ApplicationDbContext context = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>())
                {
                    // if 'demo' mode, seed data after db deletion/creation
                    if (Configuration.GetValue <string>("BOOKING_DEMO") != "false" && !env.IsEnvironment("Development_WebAPI_Test"))
                    {
                        context.Database.EnsureDeleted();
                        context.Database.Migrate();

                        // seed data
                        var seedSection = Configuration.GetSection("BOOKING_DEMO_SEED");

                        SeedDataProvider.Generate
                        (
                            context,
                            seedSection.GetValue <int>("DAYS"),
                            seedSection.GetValue <int>("ROOMS"),
                            seedSection.GetValue <int>("MIN_ROOM_COLUMNS"),
                            seedSection.GetValue <int>("MAX_ROOM_COLUMNS"),
                            seedSection.GetValue <int>("MIN_ROOM_ROWS"),
                            seedSection.GetValue <int>("MAX_ROOM_ROWS")
                        );

                        string username = Configuration.GetValue <string>("BOOKING_DEMO_USER");
                        string password = Configuration.GetValue <string>("BOOKING_DEMO_PASSWORD");

                        // if demo user and password are specified, create admin user
                        if (username != null && password != null)
                        {
                            // get required services
                            using (UserManager <User> userManager = serviceScope.ServiceProvider.GetRequiredService <UserManager <User> >())
                            {
                                using (RoleManager <IdentityRole> roleManager = serviceScope.ServiceProvider.GetRequiredService <RoleManager <IdentityRole> >())
                                {
                                    User adminUser = new User
                                    {
                                        UserName       = username,
                                        Email          = password,
                                        EmailConfirmed = true
                                    };

                                    var createResult = userManager.CreateAsync(adminUser, password).Result;
                                    if (createResult.Succeeded)
                                    {
                                        context.Customers.Add(new Customer
                                        {
                                            UserId       = adminUser.Id,
                                            ContactEmail = username,
                                            FirstName    = "DEMO",
                                            LastName     = "DEMO"
                                        });
                                        context.SaveChanges();
                                        roleManager.CreateAsync(new IdentityRole {
                                            Name = "user"
                                        });
                                        roleManager.CreateAsync(new IdentityRole {
                                            Name = "admin"
                                        });
                                        userManager.AddToRoleAsync(adminUser, "user");
                                        userManager.AddToRoleAsync(adminUser, "admin");
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        context.Database.Migrate();
                    }
                }
            }

            /*
             * Configure request pipeline
             */

            // inline 'middleware' for extracting jwt from auth cookie and adding to context header
            app.Use(async(context, next) =>
            {
                string path = context.Request.Path.Value;

                if (path != null && path.Contains("/api"))
                {
                    // read authorization cookie, and add token to header
                    var authCookie = context.Request.Cookies["Authorization"];
                    if (authCookie != null)
                    {
                        context.Request.Headers.Append("Authorization", authCookie);
                    }
                }

                await next();
            });

            app.UseCors();

            app.UseAuthentication();

            app.UseMvc(config =>
            {
                config.MapRoute("default", "api/{controller}/{id}");
                // required for OData filter support
                config.EnableDependencyInjection();
                config.Expand().Filter().OrderBy().Select().MaxTop(null);
            });

            // exclude SPA configuration for test/debug purposes
            if (!env.IsEnvironment("Development_WebAPI_Test"))
            {
                if (env.IsProduction())
                {
                    app.UseSpaStaticFiles();
                }

                app.UseSpa(spa =>
                {
                    spa.Options.SourcePath     = "ClientApp";
                    spa.Options.StartupTimeout = TimeSpan.FromMinutes(2);
                    if (env.IsDevelopment())
                    {
                        spa.UseAngularCliServer(npmScript: "start");
                    }
                });
            }
        }