User Management - Developer Documentation
Seed users
Note
- Change usersSeedDatabase.json file according to the needs of the application
- Manage application.json file according to the needs of the application
Users seeding is invoked during the application's initialization phase
- A Super admin user is seeded with necessary claims and role assignments.
- Additional Admin users are created and assigned roles as specified in the configuration.
Pre-conditions
- Configuration Settings: Ensure the following configuration keys are correctly set in the application configuration:
- SeedDatabaseFilePaths:SeedDatabaseUsers - Path to the JSON file containing user data.
- SeedDatabaseDefaultValues:SeedDatabaseDefaultPasswordForAdminUsers - Default password for admin users.
- SeedDatabaseDefaultValues:SeedDatabaseDefaultPasswordForSuperAdmin - Default password for the super admin user.
- SeedDatabaseDefaultValues:SeedDatabaseDefaultSuperAdminUserName - The username for the default super admin user.
- Database Initialization: Ensure that the database schema is initialized and tables for Users, Roles, and UserRoles exist.
Implementation Details
- Validate JSON File Path:
- Retrieve the JSON file path.
- Exit the method if the path is missing or empty.
- Check for Existing Users:
- If there are already users in the database (_db.Users.Any()), skip seeding.
- Read and Parse JSON Data:
- Load JSON data from the specified file.
- Extract the super admin and initial users sections.
- Seed super admin:
- Check if the super admin section exists and has valid data.
- Create the super admin user with a default password.
- Assign the super admin role.
- Add default claims, such as SpecialAuthClaim and PreferedLanguageClaim.
- Seed Additional Users:
- Check if the initial users section exists and contains user data.
- Create each user with a default password.
- Assign roles specified in the JSON file to the user.
- Save Changes:
- Persist all user, role, and claim assignments to the database.
//shortened code snippet
private void SeedUsers()
{
if (!_db.Users.Any())
{
var usersData = File.ReadAllText(usersPath);
var jsonArray = JArray.Parse(usersData);
//seed super admin
if (superadminDataJson != null)
{
if (string.IsNullOrEmpty(defaultPasswordSuperAdminUser))
{
return;
}
if (superadmin != null)
{
if (resultCreatedSuperAdmin.Succeeded)
{
// Add claims to super admin
if (string.IsNullOrEmpty(defaultSuperAdminUserName))
{
return;
}
if (superAdminUser != null)
{
//Assign super admin to role superadmin
if (superAdminRole != null && !string.IsNullOrEmpty(superAdminRole.Name))
{
_db.UserRoles.Add(new IdentityUserRole<string>
{
UserId = superAdminUser.Id,
RoleId = superAdminRole.Id
});
_db.SaveChanges();
}
}
}
}
}
//seed other users
...
}
}