public async Task <IActionResult> EditRole(string id)
        {
            IdentityRole role = await _roleManager.FindByIdAsync(id);

            IEnumerable <User> members = await _userManager.GetUsersInRoleAsync(role.Name);

            IEnumerable <User> nonmembers = await _userManager.GetUsersNotInRoleAsync(role.Name);

            RoleEditViewModel model = new RoleEditViewModel()
            {
                Members    = members,
                NonMembers = nonmembers,
                Role       = role
            };

            return(View(model));
        }
Esempio n. 2
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);
            }
        }