예제 #1
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.GetRequiredService <AuthDbContext>();
                    context.Database.Migrate();

                    // requires using Microsoft.Extensions.Configuration;
                    var config = host.Services.GetRequiredService <IConfiguration>();
                    // Set password with the Secret Manager tool.
                    // dotnet user-secrets set SeedUserPW <pw>



                    SeedUsers.Initialize(services).Wait();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }
예제 #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseSession();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            SeedRoles.Initialize(serviceProvider).GetAwaiter().GetResult();
            SeedUsers.Initialize(serviceProvider).GetAwaiter().GetResult();
        }
예제 #3
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiddleware <ErrorHandling>();

            app.UseHttpsRedirection();

            app.UseCors("AllowSpecificOriginPolicy");
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

            app.UseSwagger();
            app.UseSwaggerUI(s => s.SwaggerEndpoint("/swagger/v1/swagger.json", "RESApiService"));
            using var scope = app.ApplicationServices.CreateScope();
            var context = scope.ServiceProvider.GetRequiredService <AppDbContext>();

            context.Database.Migrate();
            var userManager = scope.ServiceProvider.GetRequiredService <UserManager <User> >();
            var roleManager = scope.ServiceProvider.GetRequiredService <RoleManager <IdentityRole> >();

            SeedRoles.SeedAdminRole(roleManager);
            SeedUsers.SeedAdminUser(userManager);
        }
예제 #4
0
        public unit_test_UserRepo()
        {
            //Setting up In memory dbs.
            userdb   = new SqliteConnection("DataSource=:memory:");
            passdb   = new SqliteConnection("DataSource=:memory:");
            walletdb = new SqliteConnection("DataSource=:memory:");
            userdb.Open();
            passdb.Open();
            walletdb.Open();
            var userbuild = new DbContextOptionsBuilder <UserModelContext>()
                            .UseSqlite(userdb).Options;
            var passbuild = new DbContextOptionsBuilder <PassModelContext>()
                            .UseSqlite(passdb).Options;
            var walletbuild = new DbContextOptionsBuilder <WalletContext>()
                              .UseSqlite(walletdb).Options;
            var userContext   = new UserModelContext(userbuild);
            var passContext   = new PassModelContext(passbuild);
            var walletContext = new WalletContext(walletbuild);

            //Drop and create
            userContext.Database.EnsureDeleted();
            userContext.Database.EnsureCreated();
            passContext.Database.EnsureDeleted();
            passContext.Database.EnsureCreated();
            walletContext.Database.EnsureDeleted();
            walletContext.Database.EnsureCreated();
            //Seeding data to test on
            SeedUsers.seedUsers(userContext, passContext, walletContext);

            _uut = new UserRepository(walletContext, userContext);
        }
예제 #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager <IdentityUser> userManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            SeedUsers.SeedTheUsers(userManager).Wait();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
예제 #6
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            // Initialize the database
            var scopeFactory = host.Services.GetRequiredService <IServiceScopeFactory>();

            using (var scope = scopeFactory.CreateScope())
            {
                var context     = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                var roleManager = scope.ServiceProvider.GetRequiredService <RoleManager <IdentityRole> >();
                var userManager = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();
                if (context.Database.EnsureCreated())
                {
                    SeedUsers.Initialize(roleManager, userManager);
                    SeedResume.Initialize(context);
                    SeedHireinator.Initialize(context);
                    SeedAbout.Initialize(context);
                    SeedSettings.Initialize(context);
                    SeedContact.Initialize(context);
                }
            }

            host.Run();
        }
예제 #7
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            // After Build has been called, all services have been registered (by running Startup)
            // By using a scope for the services to be requested below, we limit their lifetime to this set of calls.
            // See: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0#call-services-from-main
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    // Get the IConfiguration service that allows us to query user-secrets and
                    // the configuration on Azure
                    var config = host.Services.GetRequiredService <IConfiguration>();
                    // Set password with the Secret Manager tool, or store in Azure app configuration
                    // dotnet user-secrets set SeedUserPW <pw>

                    var testUserPw = config["SeedUserPW"];
                    var adminPw    = config["SeedAdminPW"];

                    SeedUsers.Initialize(services, SeedData.UserSeedData, testUserPw).Wait();
                    SeedUsers.InitializeAdmin(services, "*****@*****.**", "admin", adminPw, "The", "Admin").Wait();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }
            // Go ahead and run the app, everything should be ready
            host.Run();
        }
예제 #8
0
파일: Startup.cs 프로젝트: nkmnhan/E-Shop
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseCors("CorsPolicy");

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles")),
                RequestPath  = new PathString("/StaticFiles")
            });

            app.UseRouting();
            app.UseSwagger();

            app.UseIdentityServer();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseSwaggerUI(c =>
            {
                c.OAuthClientId("swagger");
                c.OAuthClientSecret("secret");
                c.OAuthUsePkce();
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyShop API V1");
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            SeedProductData.CreateData(app);
            SeedUsers.CreateData(app);
        }
예제 #9
0
        private static async Task InitializeDatabaseAsync(IWebHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services    = scope.ServiceProvider;
                var userManager = services.GetRequiredService <UserManager <ApplicationUser> >();
                var roleManager = services.GetRequiredService <RoleManager <ApplicationRole> >();
                await SeedUsers.EnsureSeedDataAsync(userManager, roleManager);

                var grantContext  = services.GetRequiredService <PersistedGrantDbContext>();
                var configContext = services.GetRequiredService <ConfigurationDbContext>();
                await SeedClients.EnsureSeedDataAsync(grantContext, configContext);
            }
        }
예제 #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            //  Redirect all http requests to https
            var options = new RewriteOptions().AddRedirectToHttps();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
            //  Add cookie middleware to the configure an identity request and persist it to a cookie.
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme  = "Cookie",
                LoginPath             = new PathString("/Account/Login/"),
                AccessDeniedPath      = new PathString("/Account/Forbidden/"),
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                //ExpireTimeSpan = TimeSpan.FromSeconds(10),
                ExpireTimeSpan    = TimeSpan.FromHours(10),
                SlidingExpiration = true,
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            SeedUsers.Initialize(app.ApplicationServices);
        }
예제 #11
0
        //Setup
        public unit_test_signupcontroller()
        {
            //Adding config to tests.
            var confbuilder = new ConfigurationBuilder();

            confbuilder.AddJsonFile("appsettings.json");
            _configuraion = confbuilder.Build();
            //Setting up In memory dbs.
            userdb   = new SqliteConnection("DataSource=:memory:");
            passdb   = new SqliteConnection("DataSource=:memory:");
            walletdb = new SqliteConnection("DataSource=:memory:");
            userdb.Open();
            passdb.Open();
            walletdb.Open();

            //Setting up contexts.
            var userbuild = new DbContextOptionsBuilder <UserModelContext>()
                            .UseSqlite(userdb).Options;
            var passbuild = new DbContextOptionsBuilder <PassModelContext>()
                            .UseSqlite(passdb).Options;
            var walletbuild = new DbContextOptionsBuilder <WalletContext>()
                              .UseSqlite(walletdb).Options;
            var userContext   = new UserModelContext(userbuild);
            var passContext   = new PassModelContext(passbuild);
            var walletContext = new WalletContext(walletbuild);

            //Drop and create
            userContext.Database.EnsureDeleted();
            userContext.Database.EnsureCreated();
            passContext.Database.EnsureDeleted();
            passContext.Database.EnsureCreated();
            walletContext.Database.EnsureDeleted();
            walletContext.Database.EnsureCreated();
            //Seeding data to test on
            SeedUsers.seedUsers(userContext, passContext, walletContext);

            //Mocking login
            supportLogin = new LoginController(_configuraion, passContext, userContext);
            //Setting uut
            _uut = new SignupController(passContext, userContext);
        }
예제 #12
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService <DataContext>();
                    context.Database.Migrate();
                    SeedUsers.Seedusers(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occured during migration");
                }
            }
            host.Run();
        }
예제 #13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              UserManager <IdentityUser> userManager, IConfiguration _config)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // Use this for localization for US as described in services section above.
            app.UseRequestLocalization();

            // For requesting static files
            app.UseStaticFiles();

            // For using identity authentication
            app.UseAuthentication();

            //Below class is used to seed Admin User in to Database
            SeedUsers.AddUsers(userManager, _config);

            // MVC Usage with inital route defined
            app.UseMvc(options =>
            {
                options.MapRoute(
                    name: "Default",
                    template: "{Controller=Webmaster}/{Action=LoginPanel}/{id?}"
                    );

                options.MapRoute(
                    name: "api",
                    template: "api/{Controller}/{Action}/{id?}"
                    );
            });

            // If Request is not handled by MVC, this last context is used in Request Pipeline , uncomment this if you want.
            app.Run(async(context) =>
            {
                await context.Response.WriteAsync("Nothing Found, Please Contact Admin.");
            });
        }
예제 #14
0
        public static async Task Initialize(GoDbContext context,
                                            UserManager <GoUser> userManager,
                                            RoleManager <ApplicationRole> roleManager,
                                            IServiceProvider serviceProvider)
        {
            context.Database.EnsureCreated();
            await SeedUsers.Seed(serviceProvider, context, userManager, roleManager);

            await SeedCourses.Seed(serviceProvider, context);

            await SeedCoursesUsers.Seed(serviceProvider, context);

            await SeedDestinations.Seed(serviceProvider, context);

            await SeedDestinationsUsers.Seed(serviceProvider, context);

            await SeedComments.Seed(serviceProvider, context);

            await SeedStories.Seed(serviceProvider, context);

            await SeedGames.Seed(serviceProvider, context);

            await SeedLevelGameParticipants.Seed(serviceProvider, context);
        }
예제 #15
0
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    SeedPublishers.InitialPublisher(services);
                    SeedGames.InitialGames(services);
                    SeedStores.InitialStores(services);
                    SeedUsers.InitialUsers(services);
                    SeedOrders.InitialOrders(services);
                    SeedOrdersItems.InitialOrderItems(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error ocurred while seeding Games");
                }
            }
            host.Run();
        }
예제 #16
0
 public AccountController(SignInManager <IdentityUser> signInManager, UserManager <IdentityUser> userManager)
 {
     _signInManager = signInManager;
     SeedUsers.Seed(userManager).Wait();
 }
예제 #17
0
 public ActionResult Login(string returnUrl)
 {
     SeedUsers.CheckAndAddUsers(Db);
     ViewBag.ReturnUrl = returnUrl;
     return(View());
 }
예제 #18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, SeedGames seedGames, SeedUsers seedUsers)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(builder => {
                    builder.Run(async context =>
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                        var error = context.Features.Get <IExceptionHandlerFeature>();
                        if (error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
                //app.UseHsts();
            }

            //app.UseHttpsRedirection();
            seedGames.SeedBoardGames();
            //seedUsers.SeedBoardologyUsers();
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            app.UseAuthentication();
            app.UseMvc();
        }
예제 #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                var hostname   = Environment.GetEnvironmentVariable("SQLSERVER_HOST") ?? "localhost";
                var password   = Environment.GetEnvironmentVariable("SQLSERVER_SA_PASSWORD") ?? "123..abc";
                var connString = $"Data Source={hostname};Initial Catalog=filmdesigners.at;User ID=sa;Password={password};";

                //add framework services.
                services.AddDbContext <ApplicationDbContext>(options =>
                                                             //Old LocalDB Config
                                                             //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
                                                             // NEW DOCKER SQL SERVER
                                                             options.UseSqlServer($"Data Source=localhost;Initial Catalog=filmdesigners.at;User ID=sa;Password=123..abc"));
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // Require SSL
                // TODO: Enable RequireHttps again (disabled for development on Mac)
                services.Configure <MvcOptions>(options =>
                {
                    options.Filters.Add(new RequireHttpsAttribute());
                });

                //add framework services.
                //services.AddDbContext<ApplicationDbContext>(options =>
                //Old LocalDB Config
                //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
                // NEW DOCKER SQL SERVER
                //options.UseSqlServer($"Data Source=localhost;Initial Catalog=filmdesigners.at;User ID=sa;Password=123..abc"));
            }
            // Require SSL
            // TODO: Enable RequireHttps again (disabled for development on Mac)
            services.Configure <MvcOptions>(options =>
            {
                //options.Filters.Add(new RequireHttpsAttribute());
            });

            //add framework services.
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         //Old LocalDB Config
                                                         //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
                                                         // NEW DOCKER SQL SERVER
                                                         options.UseSqlServer($"Data Source=localhost;Initial Catalog=filmdesigners.at;User ID=sa;Password=123..abc"));

            services.AddIdentity <ApplicationUser, IdentityRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail = true;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();


            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();

            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();

                config.Filters.Add(new AuthorizeFilter(policy));
            });

            services.Configure <AuthMessageSenderOptions>(Configuration);

            //AuthorizationHandlers
            services.AddScoped <IAuthorizationHandler, MemberIsOwnerAuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, MemberAdministratorAuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, MemberManagerAuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, ChapterAdministratorAuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, EnrollmentAdministratorAuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, EventsAdministratorAuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, JobsAdministratorAuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, NewslettersAdministratorAuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, RolesAdministratorAuthorizationHandler>();
            services.AddSingleton <IAuthorizationHandler, UsersAdministratorAuthorizationHandler>();



            var serviceProvider = services.BuildServiceProvider();

            var dbContext = serviceProvider.GetService <ApplicationDbContext>();

            SeedUsers.Initialize(serviceProvider);
            //SeedJobs.Initialize(serviceProvider);
            //SeedMembers.Initialize(serviceProvider);

            return(serviceProvider);
        }