Exemple #1
0
        public static async Task SeedIdentityAsync(UserManager <IdentityUser> userManager, RoleManager <IdentityRole> roleManager)
        {
            // Create role(s) first.
            if (!await roleManager.RoleExistsAsync(Roles.Administrator))
            {
                await roleManager.CreateAsync(new IdentityRole { Name = Roles.Administrator });
            }

            // Prompt to create the first Administrator user.
            if (!await userManager.Users.AnyAsync())
            {
                // Add some delay so the prompt shows up after all the Microsoft.Hosting info output.
                await Task.Delay(TimeSpan.FromSeconds(1));

                while (true)
                {
                    Console.WriteLine($"Please create the first {Roles.Administrator} user below.");

                    // Ask for email address
                    Console.Write("Enter an email address for the admin account: ");
                    var email = Console.ReadLine();

                    // Ask for password
                    Console.Write("Enter a password for the admin account: ");
                    var password = ConsoleUtility.GetHiddenConsoleInput();

                    // Create the user
                    var user = new IdentityUser {
                        Email = email, EmailConfirmed = true, UserName = email
                    };
                    Console.WriteLine(); // CreateAsync() may show a warning, so a new line would make it look better.
                    var userCreationResult = await userManager.CreateAsync(user, password);

                    // Restart prompt on failed attempt.
                    // Could be caused by an invalid email address or not meeting password complexity requirements.
                    if (!userCreationResult.Succeeded)
                    {
                        Console.WriteLine(Environment.NewLine + "INPUT ERROR: User could not be created. Please try again.");
                        continue;
                    }

                    // User was created with no issues, so add the user to the Administrator role.
                    await userManager.AddToRoleAsync(user, Roles.Administrator);

                    // End the prompting.
                    Console.WriteLine("User created successfully.");
                    break;
                }
            }
        }