Пример #1
0
        private static async Task CreateAdminAccountAsync(IServiceProvider serviceProvider, IConfiguration configuration)
        {
            serviceProvider = serviceProvider.CreateScope().ServiceProvider;
            IWorkshopUserRepository _userManager       = serviceProvider.GetRequiredService <IWorkshopUserRepository>();
            IWorkshopRoleRepository _roleManager       = serviceProvider.GetRequiredService <IWorkshopRoleRepository>();
            IdentityContext         _IdentityDbContext = serviceProvider.GetRequiredService <IdentityContext>();

            _IdentityDbContext.Database.Migrate();

            string firstName = configuration.GetValue("Admin:AdminUser:FirstName", "Admin");
            string lastName  = configuration.GetValue("Admin:AdminUser:LastName", "Admin");
            string userName  = configuration.GetValue("Admin:AdminUser:UserName", "Admin");
            string email     = configuration.GetValue("Admin:AdminUser:Email", "*****@*****.**");
            string password  = configuration.GetValue("Admin:AdminUser:Password", "Pa$$w0rd");
            string role      = "Admin";

            if (await _roleManager.FindByNameAsync(role) == null)
            {
                IdentityResult result = await _roleManager.CreateAsync(new IdentityRole { Name = role });

                if (!result.Succeeded)
                {
                    throw new Exception("Admin error");
                }
            }

            if ((await _userManager.GetUsersInRoleAsync(role)).Count < 1)
            {
                IdentityResult result;
                User           user = await _userManager.FindByNameAsync(userName);

                if (user == null)
                {
                    user = new User
                    {
                        FirstName = firstName,
                        LastName  = lastName,
                        UserName  = userName,
                        Email     = email
                    };
                    result = await _userManager.CreateAsync(user, password);

                    if (!result.Succeeded)
                    {
                        throw new Exception("Admin error");
                    }
                }

                _userManager.RecoverUser(userName);

                await _userManager.AddToRoleAsync(user, role);
            }
        }
Пример #2
0
        public async Task <IActionResult> CreateUser(User model)
        {
            if (ModelState.IsValid)
            {
                IdentityResult result = await _userManager.CreateAsync(model, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction(nameof(UserIndex)));
                }
                foreach (IdentityError error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return(View(model));
        }