Example #1
0
        private static void UpdateDatabase(IApplicationBuilder app)
        {
            using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                using (ApplicationDbContext context = serviceScope.ServiceProvider.GetService <ApplicationDbContext>())
                    using (ApplicationIdentityDbContext identityContext = serviceScope.ServiceProvider.GetService <ApplicationIdentityDbContext>())
                    {
                        identityContext.Database.Migrate();
                        context.Database.Migrate();

                        // Seeding identity
                        UserManager <ApplicationUser> userMgr =
                            serviceScope.ServiceProvider.GetService <UserManager <ApplicationUser> >();
                        RoleManager <IdentityRole> roleMgr =
                            serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >();

                        IdentitySeedData identitySeeder = new IdentitySeedData(identityContext, userMgr, roleMgr);
                        identitySeeder.Seed();

                        try
                        {
                            SeedData.EnsurePopulated(context);
                        }
                        catch (Exception ex)
                        {
                            ILogger <Startup> logger = serviceScope.ServiceProvider.GetRequiredService <ILogger <Startup> >();
                            logger.LogError(ex, "An error occured seeding the database.");
                        }
                    }
            }
        }
 public AccountController(UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager, IConfiguration configuration, ApplicationIdentityDbContext applicationIdentityDbContext)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _configuration = configuration;
     _context       = applicationIdentityDbContext;
 }
Example #3
0
        public Tools(IApplicationBuilder builder)
        {
            this.app = builder;
            ApplicationIdentityDbContext context = app.ApplicationServices.GetRequiredService <ApplicationIdentityDbContext>();

            context.Database.Migrate();
        }
Example #4
0
 public ServiceRepository(
     ApplicationDbContext applicationDbContext,
     ApplicationIdentityDbContext applicationIdentityDbContext)
 {
     _applicationDbContext         = applicationDbContext;
     _applicationIdentityDbContext = applicationIdentityDbContext;
 }
Example #5
0
        public static async Task <ApplicationUser> SeedRootAdmin(ApplicationIdentityDbContext context, IServiceProvider serviceProvider)
        {
            const string ROOT_ADMIN_EMAIL = "*****@*****.**";
            var          owner            = context.Users.FirstOrDefault(user => user.UserName == ROOT_ADMIN_EMAIL);

            if (owner is null)
            {
                var userManager = serviceProvider.GetService <UserManager <ApplicationUser> >();
                owner = new ApplicationUser()
                {
                    Email                = ROOT_ADMIN_EMAIL,
                    NormalizedEmail      = ROOT_ADMIN_EMAIL.ToUpper(),
                    UserName             = ROOT_ADMIN_EMAIL,
                    NormalizedUserName   = ROOT_ADMIN_EMAIL.ToUpper(),
                    PhoneNumber          = "+123456789",
                    EmailConfirmed       = true,
                    PhoneNumberConfirmed = true,
                };

                await userManager.CreateAsync(owner, "`12QWEasd");                 // user must be warned to change this

                context.SaveChanges();

                await userManager.AddToRoleAsync(owner, Role.Admin);

                context.SaveChanges();
            }
            return(owner);
        }
        public async Task SeedAsync(ApplicationIdentityDbContext context, IWebHostEnvironment env,
                                    ILogger <ApplicationIdentityDbContextSeed> logger, IOptions <AppSettings> settings, int?retry = 0)
        {
            int retryForAvaiability = retry.Value;

            try
            {
                var useCustomizationData = settings.Value.UseCustomizationData;
                var contentRootPath      = env.ContentRootPath;
                var webroot = env.WebRootPath;

                if (!context.Users.Any())
                {
                    context.Users.AddRange(useCustomizationData ? GetUsersFromFile(contentRootPath, logger) : GetDefaultUser());
                    await context.SaveChangesAsync();
                }

                if (useCustomizationData)
                {
                    GetPreconfiguredImages(contentRootPath, webroot, logger);
                }
            }
            catch (Exception ex)
            {
                if (retryForAvaiability < 10)
                {
                    retryForAvaiability++;
                    logger.LogError(ex, "EXCEPTION ERROR while migrating {DbContextName}", nameof(ApplicationIdentityDbContext));
                    await SeedAsync(context, env, logger, settings, retryForAvaiability);
                }
            }
        }
Example #7
0
        public static async Task <List <IdentityRole> > SeedRoles(ApplicationIdentityDbContext context, IServiceProvider serviceProvider)
        {
            var roles = context.Roles.ToList();

            if (!roles.Any())
            {
                var roleStore = serviceProvider.GetService <RoleManager <IdentityRole> >();
                roles = new List <IdentityRole>
                {
                    new IdentityRole(Role.Admin)
                    {
                        Id = Constants.AdminRoleId
                    },
                    new IdentityRole(Role.AreaAdmin)
                    {
                        Id = Constants.AreaAdminRoleId
                    },
                    new IdentityRole(Role.ReadOnlyUser)
                    {
                        Id = Constants.ReadOnlyUserRoleId
                    },
                    new IdentityRole(Role.ReadWriteUser)
                    {
                        Id = Constants.ReadWriteUserRoleId
                    }
                };
                foreach (var role in roles)
                {
                    await roleStore.CreateAsync(role);
                }
            }
            return(roles);
        }
Example #8
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationIdentityDbContext identityDbContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.Use((ctx, next) =>
                {
                    return(next());
                });
            }

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });

            identityDbContext.Database.Migrate();

            OnConfigure(app, env);
        }
        public void Setup()
        {
            // Build service colection to create identity UserManager and RoleManager.
            IServiceCollection serviceCollection = new ServiceCollection();

            // Add ASP.NET Core Identity database in memory.
            sqliteConnection = new SqliteConnection("DataSource=:memory:");
            serviceCollection.AddDbContext <ApplicationIdentityDbContext>(options => options.UseSqlite(sqliteConnection));

            identityDbContext = serviceCollection.BuildServiceProvider().GetService <ApplicationIdentityDbContext>();
            identityDbContext.Database.OpenConnection();
            identityDbContext.Database.EnsureCreated();

            // Add Identity using in memory database to create UserManager and RoleManager.
            serviceCollection.AddApplicationIdentity();

            // Get UserManager and RoleManager.
            userManager = serviceCollection.BuildServiceProvider().GetService <UserManager <ApplicationUser> >();
            roleManager = serviceCollection.BuildServiceProvider().GetService <RoleManager <ApplicationRole> >();

            // Get token validation settings.
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            IConfigurationRoot configuration = builder.Build();

            var tokenValidationSection = configuration.GetSection("TokenValidation");

            serviceCollection.Configure <TokenValidation>(tokenValidationSection);

            tokenValidationSettings = serviceCollection.BuildServiceProvider().GetService <IOptions <TokenValidation> >().Value;
        }
Example #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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });
            ApplicationIdentityDbContext.CreateAdminAccount(app.ApplicationServices,
                                                            Configuration).Wait();
            ApplicationIdentityDbContext.CreateMentorsRole(app.ApplicationServices,
                                                           Configuration).Wait();
        }
Example #11
0
 public static void Main(string[] args)
 {
     using (var identitycontext = new ApplicationIdentityDbContext())
     {
         identitycontext.Database.EnsureDeleted();
         identitycontext.Database.EnsureCreated();
     }
     CreateHostBuilder(args).Build().Run();
 }
Example #12
0
 public IndexModel(
     UserManager <ApplicationUser> userManager,
     RoleManager <Domain.Identity.ApplicationRole> roleManager,
     ApplicationIdentityDbContext dbContext)
 {
     _userManager = userManager;
     _roleManager = roleManager;
     _dbContext   = dbContext;
 }
Example #13
0
        public static UserManager <ApplicationUser> UserManager(IApplicationBuilder app)
        {
            ApplicationIdentityDbContext context = app.ApplicationServices.GetRequiredService <ApplicationIdentityDbContext>();

            context.Database.Migrate();
            UserManager <ApplicationUser> userManager = app.ApplicationServices.GetRequiredService <UserManager <ApplicationUser> >();

            return(userManager);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SeedController"/> class.
 /// </summary>
 /// <param name="appDbContext">Instance of <see cref="ApplicationDbContext"/>.</param>
 /// <param name="userManager">Instance of <see cref="ApplicationUserManager"/>.</param>
 /// <param name="identityDbContext">Instance of <see cref="ApplicationIdentityDbContext"/>.</param>
 public SeedController(
     ApplicationDbContext appDbContext,
     ApplicationUserManager userManager,
     ApplicationIdentityDbContext identityDbContext)
 {
     _appDbContext      = appDbContext ?? throw new ArgumentNullException(nameof(appDbContext));
     _userManager       = userManager ?? throw new ArgumentNullException(nameof(userManager));
     _identityDbContext = identityDbContext ?? throw new ArgumentNullException(nameof(identityDbContext));
 }
Example #15
0
        private void SeedUser(IApplicationBuilder app)
        {
            ApplicationIdentityDbContext context = app.ApplicationServices.GetRequiredService <ApplicationIdentityDbContext>();

            context.Database.Migrate();
            var userMager = app.ApplicationServices.GetRequiredService <UserManager <ApplicationUser> >();
            RoleManager <IdentityRole> roleManager = app.ApplicationServices.GetService <RoleManager <IdentityRole> >();

            SeedTools.SeedRoles(roleManager);
            SeedTools.SeedUsers(userMager);
        }
Example #16
0
 public UsersController(
     UserManager <ApplicationUser> userManager,
     ApplicationIdentityDbContext context,
     IEmailSender emailSender,
     ISmsSender smsSender,
     ILoggerFactory loggerFactory)
 {
     _userManager = userManager;
     _context     = context;
     _emailSender = emailSender;
     _smsSender   = smsSender;
     _logger      = loggerFactory.CreateLogger <UsersController>();
 }
Example #17
0
        public static ApplicationIdentityDbContext Create()
        {
            var options = new DbContextOptionsBuilder <ApplicationIdentityDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var context = new ApplicationIdentityDbContext(options);

            context.Database.EnsureCreated();

            context.SaveChanges();

            return(context);
        }
Example #18
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationIdentityDbContext identityDbContext)
        {
            OnConfiguring(app, env);

            var supportedCultures = new[]
            {
                new System.Globalization.CultureInfo("en-US"),
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-US"),
                SupportedCultures     = supportedCultures,
                SupportedUICultures   = supportedCultures
            });

            if (env.IsDevelopment())
            {
                Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.Use((ctx, next) =>
                {
                    return(next());
                });
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });

            identityDbContext.Database.Migrate();

            OnConfigure(app, env);
        }
Example #19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            //https://docs.microsoft.com/ru-ru/aspnet/core/fundamentals/localization?view=aspnetcore-2.2
            var supportedCultures = new[]
            {
                new CultureInfo("uk-UA"),
                //new CultureInfo("en-US"),
                //new CultureInfo("ru-RU")
            };

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("uk-UA"),
                //Formatting numbers, dates, etc.
                SupportedCultures = supportedCultures,
                //UI strings that we have localized
                SupportedUICultures = supportedCultures
            });

            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();

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

            ApplicationIdentityDbContext.CreateAdminAccount(app.ApplicationServices,
                                                            Configuration).Wait();
            ApplicationIdentityDbContext.InitializeRolesAsync(app.ApplicationServices).Wait();
            ApplicationIdentityDbContext.CreateUserAccounts(app.ApplicationServices, Configuration).Wait();
        }
Example #20
0
 public SecurityService(ApplicationIdentityDbContext context,
                        IWebHostEnvironment env,
                        UserManager <ApplicationUser> userManager,
                        RoleManager <IdentityRole> roleManager,
                        SignInManager <ApplicationUser> signInManager,
                        NavigationManager uriHelper,
                        GlobalsService globals)
 {
     this.context       = context;
     this.userManager   = userManager;
     this.roleManager   = roleManager;
     this.signInManager = signInManager;
     this.env           = env;
     this.uriHelper     = uriHelper;
     this.globals       = globals;
 }
Example #21
0
        public static void Initialize(ApplicationIdentityDbContext context, IServiceProvider serviceProvider)
        {
            using (var transaction = context.Database.BeginTransaction())
            {
                try
                {
                    SeedRoles(context, serviceProvider).Wait();
                    SeedRootAdmin(context, serviceProvider).Wait();

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    File.WriteAllText($"log{DateTime.UtcNow.Date.ToString("yyyyMMdd")}.txt", e.ToString());
                }
            }
        }
Example #22
0
        public AccountController(
            ApplicationIdentityDbContext appIdentityDbContext,
            ApplicationDbContext appDdContext,
            UserManager <ApplicationIdentityUser> userManager,
            SignInManager <ApplicationIdentityUser> loginManager,
            RoleManager <ApplicationIdentityRole> roleManager)
        {
            _appDdContext         = appDdContext;
            _appIdentityDdContext = appIdentityDbContext;

            _appIdentityDdContext.Database.EnsureCreated();
            _appDdContext.Database.EnsureCreated();

            this.userManager  = userManager;
            this.loginManager = loginManager;
            this.roleManager  = roleManager;
        }
Example #23
0
 public SecurityService(ApplicationIdentityDbContext context,
                        IWebHostEnvironment env,
                        UserManager <ApplicationUser> userManager,
                        RoleManager <IdentityRole> roleManager,
                        SignInManager <ApplicationUser> signInManager,
                        IHttpContextAccessor httpContextAccessor,
                        NavigationManager uriHelper,
                        AuthenticationStateProvider authenticationStateProvider)
 {
     this.context                     = context;
     this.userManager                 = userManager;
     this.roleManager                 = roleManager;
     this.signInManager               = signInManager;
     this.env                         = env;
     this.httpContextAccessor         = httpContextAccessor;
     this.uriHelper                   = uriHelper;
     this.authenticationStateProvider = authenticationStateProvider;
 }
Example #24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationIdentityDbContext dbContext, IServiceProvider serviceProvider)
        {
            app.UseCors("AllowCors");
            // ===== Create tables ======
            dbContext.Database.EnsureCreated();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseAuthentication();

            app.UseHttpsRedirection();
            app.UseMvc();
            CreateUserRoles(serviceProvider).Wait();
        }
Example #25
0
        public SecurityService(ApplicationIdentityDbContext context,
                               IWebHostEnvironment env,
                               UserManager <ApplicationUser> userManager,
                               RoleManager <IdentityRole> roleManager,
                               SignInManager <ApplicationUser> signInManager,
                               IHttpContextAccessor httpContextAccessor,
                               NavigationManager uriHelper)
        {
            this.context             = context;
            this.userManager         = userManager;
            this.roleManager         = roleManager;
            this.signInManager       = signInManager;
            this.env                 = env;
            this.httpContextAccessor = httpContextAccessor;
            this.uriHelper           = uriHelper;

            if (httpContextAccessor.HttpContext != null)
            {
                Principal = httpContextAccessor.HttpContext.User;
                User      = context.Users.FirstOrDefault(u => u.Email == Principal.Identity.Name);
            }
        }
Example #26
0
        public AccountController(
            UserManager <ApplicationUser> userManager,
            SignInManager <ApplicationUser> signInManager,
            IEmailSender emailSender,
            ISmsSender smsSender,
            ILoggerFactory loggerFactory,
            IIdentityServerInteractionService interaction,
            IHttpContextAccessor httpContext,
            IClientStore clientStore,
            ApplicationIdentityDbContext context)
        {
            _userManager   = userManager;
            _signInManager = signInManager;
            _emailSender   = emailSender;
            _smsSender     = smsSender;
            _logger        = loggerFactory.CreateLogger <AccountController>();
            _interaction   = interaction;
            _clientStore   = clientStore;
            _context       = context;

            _account = new AccountService(interaction, httpContext, clientStore);
        }
Example #27
0
 public CreateModel(ApplicationIdentityDbContext context, UserManager <ApplicationUser> userManager)
 {
     _context     = context;
     _userManager = userManager;
 }
 public ApplicationRolesController(RoleManager <IdentityRole> roleManager, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env, ApplicationIdentityDbContext context)
 {
     this.roleManager = roleManager;
     this.env         = env;
     this.context     = context;
 }
Example #29
0
 public TodoItemsController(ApplicationIdentityDbContext context)
 {
     _context = context;
 }
Example #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ApplicationUserManager"/> class.
 /// </summary>
 /// <param name="store">The IUserStore is responsible for commiting changes via the UpdateAsync/CreateAsync methods.</param>
 /// <param name="context"><see cref="DbContext"/> for ASP.NET Identity infrastructure.</param>
 public ApplicationUserManager(IUserStore <ApplicationUser> store, ApplicationIdentityDbContext context)
     : base(store)
 {
     _context = context ?? throw new ArgumentNullException(nameof(context));
 }
Example #31
0
 public ClaimManager(ApplicationIdentityDbContext dbContext)
 {
     this.dbContext = dbContext;
 }