< Summary

Information
Class: Elsa.Identity.HostedServices.AdminUserInitializer
Assembly: Elsa.Identity
File(s): /home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Identity/HostedServices/AdminUserInitializer.cs
Line coverage
59%
Covered lines: 29
Uncovered lines: 20
Coverable lines: 49
Total lines: 95
Line coverage: 59.1%
Branch coverage
50%
Covered branches: 6
Total branches: 12
Branch coverage: 50%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
ExecuteAsync()50%281252.38%

File(s)

/home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Identity/HostedServices/AdminUserInitializer.cs

#LineLine coverage
 1using Elsa.Common;
 2using Elsa.Identity.Contracts;
 3using Elsa.Identity.Options;
 4using JetBrains.Annotations;
 5using Microsoft.Extensions.Logging;
 6using Microsoft.Extensions.Options;
 7
 8namespace Elsa.Identity.HostedServices;
 9
 10/// <summary>
 11/// Hosted service that initializes the admin user and role from <see cref="DefaultAdminUserOptions"/> configuration if 
 12/// </summary>
 13[UsedImplicitly]
 214public class AdminUserInitializer(
 215    IUserStore userStore,
 216    IRoleStore roleStore,
 217    IUserManager userManager,
 218    IRoleManager roleManager,
 219    IOptions<DefaultAdminUserOptions> options,
 220    ILogger<AdminUserInitializer> logger)
 21    : BackgroundTask
 22{
 23    public override async Task ExecuteAsync(CancellationToken cancellationToken)
 24    {
 325        var adminUserName = options.Value.AdminUserName;
 326        var adminPassword = options.Value.AdminPassword;
 327        var adminRoleName = options.Value.AdminRoleName;
 328        var adminRolePermissions = options.Value.AdminRolePermissions;
 329        if (string.IsNullOrWhiteSpace(adminRoleName))
 30        {
 031            logger.LogWarning("AdminRoleName is not configured. Skipping admin role and user creation.");
 032            return;
 33        }
 34
 335        var existingRole = await roleStore.FindAsync(new() { Id = adminRoleName }, cancellationToken);
 36
 337        if (existingRole == null)
 38        {
 039            var roleResult = await roleManager.CreateRoleAsync(
 040                adminRoleName,
 041                adminRolePermissions.ToList(),
 042                adminRoleName,
 043                cancellationToken);
 44
 045            logger.LogInformation("Admin role '{RoleName}' created successfully with {PermissionCount} permissions.",
 046                roleResult.Role.Name,
 047                roleResult.Role.Permissions.Count);
 48        }
 49        else
 50        {
 351            var missingPermissions = adminRolePermissions.Except(existingRole.Permissions, StringComparer.Ordinal).ToArr
 52
 353            if (missingPermissions.Length == 0)
 54            {
 255                logger.LogInformation("Admin role '{RoleName}' already exists with all configured permissions.", adminRo
 56            }
 57            else
 58            {
 159                existingRole.Permissions = existingRole.Permissions.Concat(missingPermissions).ToList();
 160                await roleStore.SaveAsync(existingRole, cancellationToken);
 161                logger.LogInformation(
 162                    "Admin role '{RoleName}' updated successfully with {PermissionCount} missing configured permissions.
 163                    adminRoleName,
 164                    missingPermissions.Length);
 65            }
 366        }
 67
 368        var roleToAssign = adminRoleName;
 69
 70        // Create user if configured
 371        if (string.IsNullOrWhiteSpace(adminUserName) || string.IsNullOrWhiteSpace(adminPassword))
 72        {
 373            logger.LogWarning("AdminUserName and/or AdminPassword not configured in DefaultAdminUserOptions. Skipping ad
 374            return;
 75        }
 76
 77        // Check if user already exists
 078        var existingUser = await userStore.FindAsync(new() { Name = adminUserName }, cancellationToken);
 79
 080        if (existingUser != null)
 81        {
 082            logger.LogInformation("Admin user '{User}' already exists. Skipping creation.", adminUserName);
 083            return;
 84        }
 85
 86        // Create the admin user
 087        var result = await userManager.CreateUserAsync(
 088            adminUserName,
 089            adminPassword,
 090            new List<string> { roleToAssign },
 091            cancellationToken);
 92
 093        logger.LogInformation("Admin user '{Name}' created successfully with role '{Role}'.", result.User.Name, roleToAs
 394    }
 95}