Добавил администратора

parent f3393b50
...@@ -85,6 +85,7 @@ public class AccountsController : Controller ...@@ -85,6 +85,7 @@ public class AccountsController : Controller
var result = await _userManager.CreateAsync(user, viewModel.Password); var result = await _userManager.CreateAsync(user, viewModel.Password);
if (result.Succeeded) if (result.Succeeded)
{ {
await _userManager.AddToRoleAsync(user, "user");
await _signInManager.SignInAsync(user, true); await _signInManager.SignInAsync(user, true);
return RedirectToAction("Index", "Home"); return RedirectToAction("Index", "Home");
} }
......
...@@ -19,7 +19,7 @@ public class HomeController : Controller ...@@ -19,7 +19,7 @@ public class HomeController : Controller
{ {
return View(); return View();
} }
[Authorize(Roles = "admin")]
public IActionResult Privacy() public IActionResult Privacy()
{ {
return View(); return View();
......
using Microsoft.AspNetCore.Identity;
using Store.Models.Users;
namespace Store.Helpers;
public class AdminInitializer
{
public static async Task SeedAdminUser(
RoleManager<IdentityRole> roleManager,
UserManager<User> userManager)
{
string adminEmail = "admin@admin.com";
string adminPassword = "password";
var roles = new [] { "admin", "user" };
foreach (var role in roles)
{
if (await roleManager.FindByNameAsync(role) is null)
await roleManager.CreateAsync(new IdentityRole(role));
}
if (await userManager.FindByNameAsync(adminEmail) == null)
{
User admin = new User { Email = adminEmail, UserName = adminEmail };
IdentityResult result = await userManager.CreateAsync(admin, adminPassword);
if (result.Succeeded)
await userManager.AddToRoleAsync(admin, "admin");
}
}
}
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Store.Extensions; using Store.Extensions;
using Store.Helpers;
using Store.Models; using Store.Models;
using Store.Models.Users;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
var services = builder.Services; var services = builder.Services;
...@@ -14,13 +16,12 @@ services.AddAppServices(configuration); ...@@ -14,13 +16,12 @@ services.AddAppServices(configuration);
services.Configure<IdentityOptions>(options => services.Configure<IdentityOptions>(options =>
{ {
// Default Password settings. options.Password.RequiredLength = 5; // минимальная длина
options.Password.RequireDigit = true; options.Password.RequireNonAlphanumeric = false; // требуются ли не алфавитно-цифровые символы
options.Password.RequireLowercase = true; options.Password.RequireLowercase = false; // требуются ли символы в нижнем регистре
options.Password.RequireNonAlphanumeric = true; options.Password.RequireUppercase = false; // требуются ли символы в верхнем регистре
options.Password.RequireUppercase = true; options.Password.RequireDigit = false; // требуются ли цифры
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
}); });
services.ConfigureApplicationCookie(options => services.ConfigureApplicationCookie(options =>
...@@ -59,4 +60,18 @@ app.MapControllerRoute( ...@@ -59,4 +60,18 @@ app.MapControllerRoute(
name: "default", name: "default",
pattern: "{controller=Accounts}/{action=Login}"); pattern: "{controller=Accounts}/{action=Login}");
using var scope = app.Services.CreateScope();
var serviceProvider = scope.ServiceProvider;
try
{
var userManager = serviceProvider.GetRequiredService<UserManager<User>>();
var rolesManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
await AdminInitializer.SeedAdminUser(rolesManager, userManager);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred while seeding the database.");
}
app.Run(); app.Run();
\ No newline at end of file
...@@ -10,6 +10,6 @@ public class LoginViewModel ...@@ -10,6 +10,6 @@ public class LoginViewModel
public string Password { get; set; } public string Password { get; set; }
[Display(Name = "Запомнить?")] [Display(Name = "Запомнить?")]
public bool RememberMe { get; set; } public bool RememberMe { get; set; }
public string ReturnUrl { get; set; } public string? ReturnUrl { get; set; }
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment