示例#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);
            }
        }
        public async Task <IActionResult> CreateRole(IdentityRole model)
        {
            if (ModelState.IsValid)
            {
                IdentityResult res = await _roleManager.CreateAsync(model);

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