Manage data from code
The panel uses public services. Use them for seeding, imports and background jobs.
Seeding with the management services
Each method takes the acting user, so the same safety rules apply. Use AccessSnapshot.System for trusted code:
using var scope = app.Services.CreateScope();
var permissions = scope.ServiceProvider.GetRequiredService<PermissionAdminService>();
var roles = scope.ServiceProvider.GetRequiredService<RoleAdminService>();
var users = scope.ServiceProvider.GetRequiredService<UserAdminService>();
var menu = scope.ServiceProvider.GetRequiredService<MenuAdminService>();
var system = AccessSnapshot.System;
var list = await permissions.CreateAsync(system, new PermissionInput
{
Name = "List posts", Slug = "posts.list", GroupName = "Posts",
Routes = { new RouteInput { Methods = "GET", Pattern = "/admin/posts" } },
});
var editor = await roles.CreateAsync(system, new RoleInput { Name = "Editor", Slug = "editor", PermissionIds = { list.Id } });
await users.CreateAsync(system, new UserInput { UserName = "jane", DisplayName = "Jane", Password = "S3cure#pass", RoleIds = { editor.Id } });
await menu.CreateAsync(system, new MenuInput { Title = "Posts", Icon = "icon-newspaper", Url = "/admin/posts" });
If you write to the sa_ tables directly instead of through the services, call IRbacCache.InvalidateAsync() afterwards. Otherwise users keep their cached permissions.
The services create one short-lived DbContext per call (through IDbContextFactory<SuperAdminDbContext>). They are safe to call concurrently, for example from several Blazor components of one circuit.
Import users from another system
UserInput accepts an existing ASP.NET Core Identity password hash (PasswordHasher v2 or v3, the format of AspNetUsers.PasswordHash), the old user id, an existing lockout and extra fields. Users keep their passwords:
foreach (var old in legacyUsers)
{
await users.CreateAsync(AccessSnapshot.System, new UserInput
{
Id = old.Id, // optional: keep the id (identity insert is handled on SQL Server and PostgreSQL)
UserName = old.UserName,
DisplayName = old.FullName,
Email = old.Email,
PasswordHash = old.PasswordHash, // instead of Password, never both
LockoutEnd = old.LockoutEnd, // UTC
MustChangePassword = old.MustChangePassword,
Attributes = new() { ["mobile"] = old.Mobile, ["employeeId"] = old.EmployeeId },
RoleIds = { editorRoleId },
});
}
Extra user fields
sa_users.Attributes stores host-defined fields (mobile, employee id, ...) as a JSON object of strings.
- Set them with
UserInput.Attributes. - Read them with
SaUser.GetAttributes(), or from the cached snapshot:
var me = await admin.GetAsync();
var mobile = me?.Attributes.GetValueOrDefault("mobile");