Add default roles and user

This commit is contained in:
2025-10-14 21:22:54 +09:00
parent 209cd79f01
commit 40b2a5f598
8 changed files with 159 additions and 12 deletions

View File

@ -14,7 +14,7 @@
</ChildContent> </ChildContent>
<Helper> <Helper>
<RadzenRequiredValidator Component="UserName" Text="Поле 'Логин' обязательно к заполнению" /> <RadzenRequiredValidator Component="UserName" Text="Поле 'Логин' обязательно к заполнению" />
<RadzenLengthValidator Component="UserName" Min="6" Text="Длина поля 'Логин' должна быть не меньше 6" /> <RadzenLengthValidator Component="UserName" Min="5" Text="Длина поля 'Логин' должна быть не меньше 5" />
<RadzenLengthValidator Component="UserName" Max="30" Text="Длина поля 'Логин' должна быть не больше 30" /> <RadzenLengthValidator Component="UserName" Max="30" Text="Длина поля 'Логин' должна быть не больше 30" />
</Helper> </Helper>
</RadzenFormField> </RadzenFormField>

View File

@ -14,7 +14,7 @@
</ChildContent> </ChildContent>
<Helper> <Helper>
<RadzenRequiredValidator Component="UserName" Text="Поле 'Логин' обязательно к заполнению" /> <RadzenRequiredValidator Component="UserName" Text="Поле 'Логин' обязательно к заполнению" />
<RadzenLengthValidator Component="UserName" Min="6" Text="Длина поля 'Логин' должна быть не меньше 6" /> <RadzenLengthValidator Component="UserName" Min="5" Text="Длина поля 'Логин' должна быть не меньше 5" />
<RadzenLengthValidator Component="UserName" Max="30" Text="Длина поля 'Логин' должна быть не больше 30" /> <RadzenLengthValidator Component="UserName" Max="30" Text="Длина поля 'Логин' должна быть не больше 30" />
</Helper> </Helper>
</RadzenFormField> </RadzenFormField>

View File

@ -39,7 +39,7 @@ namespace Hcs.WebApp.Controllers
if (string.IsNullOrEmpty(returnUrl)) if (string.IsNullOrEmpty(returnUrl))
{ {
Redirect("/"); return Redirect("/");
} }
return Redirect(returnUrl); return Redirect(returnUrl);
@ -63,7 +63,7 @@ namespace Hcs.WebApp.Controllers
if (string.IsNullOrEmpty(returnUrl)) if (string.IsNullOrEmpty(returnUrl))
{ {
Redirect("/"); return Redirect("/");
} }
return Redirect(returnUrl); return Redirect(returnUrl);

View File

@ -1,7 +1,143 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Hcs.WebApp.Data namespace Hcs.WebApp.Data
{ {
public class AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options) : IdentityDbContext<AppUser, AppRole, string>(options) { } public class AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options) : IdentityDbContext<AppUser, AppRole, string>(options)
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSeeding((context, _) =>
{
var adminRole = context.Set<AppRole>().FirstOrDefault(x => x.Name == AppRole.ADMINISTRATOR_TYPE);
if (adminRole == null)
{
adminRole = new AppRole()
{
Name = AppRole.ADMINISTRATOR_TYPE,
NormalizedName = AppRole.ADMINISTRATOR_TYPE.Normalize()
};
context.Set<AppRole>().Add(adminRole);
}
var operatorRole = context.Set<AppRole>().FirstOrDefault(x => x.Name == AppRole.OPERATOR_TYPE);
if (operatorRole == null)
{
context.Set<AppRole>().Add(new AppRole()
{
Name = AppRole.OPERATOR_TYPE,
NormalizedName = AppRole.OPERATOR_TYPE.Normalize()
});
}
var observerRole = context.Set<AppRole>().FirstOrDefault(x => x.Name == AppRole.OBSERVER_TYPE);
if (observerRole == null)
{
context.Set<AppRole>().Add(new AppRole()
{
Name = AppRole.OBSERVER_TYPE,
NormalizedName = AppRole.OBSERVER_TYPE.Normalize()
});
}
var adminUser = context.Set<AppUser>().FirstOrDefault(x => x.UserName == AppUser.ADMINISTRATOR_USER_NAME);
var hasAdmin = adminUser != null;
if (adminUser == null)
{
adminUser = new AppUser()
{
UserName = AppUser.ADMINISTRATOR_USER_NAME,
NormalizedUserName = AppUser.ADMINISTRATOR_USER_NAME.Normalize(),
LockoutEnabled = true
};
var passwordHasher = context.GetService<IPasswordHasher<AppUser>>();
adminUser.PasswordHash = passwordHasher.HashPassword(adminUser, AppUser.ADMINISTRATOR_PASSWORD);
var entry = context.Set<AppUser>().Add(adminUser);
}
context.SaveChanges();
if (!hasAdmin)
{
context.Set<IdentityUserRole<string>>().Add(new IdentityUserRole<string>()
{
UserId = adminUser.Id,
RoleId = adminRole.Id
});
}
context.SaveChanges();
})
.UseAsyncSeeding(async (context, _, cancellationToken) =>
{
var adminRole = await context.Set<AppRole>().FirstOrDefaultAsync(x => x.Name == AppRole.ADMINISTRATOR_TYPE, cancellationToken);
if (adminRole == null)
{
adminRole = new AppRole()
{
Name = AppRole.ADMINISTRATOR_TYPE,
NormalizedName = AppRole.ADMINISTRATOR_TYPE.Normalize()
};
context.Set<AppRole>().Add(adminRole);
}
var operatorRole = await context.Set<AppRole>().FirstOrDefaultAsync(x => x.Name == AppRole.OPERATOR_TYPE, cancellationToken);
if (operatorRole == null)
{
context.Set<AppRole>().Add(new AppRole()
{
Name = AppRole.OPERATOR_TYPE,
NormalizedName = AppRole.OPERATOR_TYPE.Normalize()
});
}
var observerRole = await context.Set<AppRole>().FirstOrDefaultAsync(x => x.Name == AppRole.OBSERVER_TYPE, cancellationToken);
if (observerRole == null)
{
context.Set<AppRole>().Add(new AppRole()
{
Name = AppRole.OBSERVER_TYPE,
NormalizedName = AppRole.OBSERVER_TYPE.Normalize()
});
}
var adminUser = await context.Set<AppUser>().FirstOrDefaultAsync(x => x.UserName == AppUser.ADMINISTRATOR_USER_NAME, cancellationToken);
var hasAdmin = adminUser != null;
if (!hasAdmin)
{
adminUser = new AppUser()
{
UserName = AppUser.ADMINISTRATOR_USER_NAME,
NormalizedUserName = AppUser.ADMINISTRATOR_USER_NAME.Normalize(),
LockoutEnabled = true
};
var passwordHasher = context.GetService<IPasswordHasher<AppUser>>();
adminUser.PasswordHash = passwordHasher.HashPassword(adminUser, AppUser.ADMINISTRATOR_PASSWORD);
var entry = context.Set<AppUser>().Add(adminUser);
}
await context.SaveChangesAsync();
if (!hasAdmin)
{
context.Set<IdentityUserRole<string>>().Add(new IdentityUserRole<string>()
{
UserId = adminUser.Id,
RoleId = adminRole.Id
});
}
await context.SaveChangesAsync();
});
base.OnConfiguring(optionsBuilder);
}
}
} }

View File

@ -2,5 +2,10 @@
namespace Hcs.WebApp.Data namespace Hcs.WebApp.Data
{ {
public class AppRole : IdentityRole { } public class AppRole : IdentityRole
{
public const string ADMINISTRATOR_TYPE = "Administrator";
public const string OPERATOR_TYPE = "Operator";
public const string OBSERVER_TYPE = "Observer";
}
} }

View File

@ -2,5 +2,9 @@
namespace Hcs.WebApp.Data namespace Hcs.WebApp.Data
{ {
public class AppUser : IdentityUser { } public class AppUser : IdentityUser
{
public const string ADMINISTRATOR_USER_NAME = "admin";
public const string ADMINISTRATOR_PASSWORD = "qaz159357";
}
} }

View File

@ -1,10 +1,11 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
#nullable disable
namespace Hcs.WebApp.Data.Migrations namespace Hcs.WebApp.Data.Migrations
{ {
[DbContext(typeof(AppIdentityDbContext))] [DbContext(typeof(AppIdentityDbContext))]
public class AppIdentityDbContextModelSnapshot : ModelSnapshot public partial class AppIdentityDbContextModelSnapshot : ModelSnapshot
{ {
protected override void BuildModel(ModelBuilder modelBuilder) protected override void BuildModel(ModelBuilder modelBuilder)
{ {
@ -80,7 +81,7 @@ namespace Hcs.WebApp.Data.Migrations
b.ToTable("AspNetUsers", (string)null); b.ToTable("AspNetUsers", (string)null);
}); });
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => modelBuilder.Entity("Hcs.WebApp.Data.AppRole", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")
.HasColumnType("nvarchar(450)"); .HasColumnType("nvarchar(450)");

View File

@ -15,8 +15,9 @@
<PackageReference Include="Microsoft.AspNetCore.HeaderPropagation" Version="8.0.20" /> <PackageReference Include="Microsoft.AspNetCore.HeaderPropagation" Version="8.0.20" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.20" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.20" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="8.0.11" /> <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="8.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.20" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.20"> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.9">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>