< Summary

Information
Class: OzonRepositories.Utils.DbInitializer
Assembly: OzonRepositories
File(s): /home/runner/work/Studio2Prod/Studio2Prod/OzonRepositories/Utils/DbInitializer.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 30
Coverable lines: 30
Total lines: 60
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 14
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
InitializeAsync()0%620%
CreateRoles()0%2040%
CreateAdmin()0%7280%

File(s)

/home/runner/work/Studio2Prod/Studio2Prod/OzonRepositories/Utils/DbInitializer.cs

#LineLine coverage
 1using Microsoft.AspNetCore.Identity;
 2using Microsoft.EntityFrameworkCore;
 3using Microsoft.Extensions.Options;
 4using OzonRepositories.Context.Identity;
 5
 6namespace OzonRepositories.Utils
 7{
 8    public class DbInitializer
 9    {
 10        private readonly RoleManager<IdentityRole> _roleManager;
 11        private readonly UserManager<CustomIdentityUser> _userManager;
 12        private readonly DbSeederOptions _options;
 13
 014        public DbInitializer(
 015            RoleManager<IdentityRole> roleManager,
 016            UserManager<CustomIdentityUser> userManager,
 017            IOptions<DbSeederOptions> options)
 18        {
 019            _roleManager = roleManager;
 020            _userManager = userManager;
 021            _options = options.Value;
 022        }
 23
 24        public async Task InitializeAsync(CancellationToken ct = default)
 25        {
 026            if (!await _roleManager.Roles.AnyAsync(ct))
 027                await CreateRoles(ct);
 28
 029            await CreateAdmin(ct);
 030        }
 31
 32        private async Task CreateRoles(CancellationToken ct)
 33        {
 034            string[] roleNames = { "Admin", "User" };
 035            foreach (var roleName in roleNames)
 36            {
 037                if (!await _roleManager.RoleExistsAsync(roleName))
 038                    await _roleManager.CreateAsync(new IdentityRole(roleName));
 039            }
 040        }
 41
 42        private async Task CreateAdmin(CancellationToken ct)
 43        {
 044            var email = _options.AdminEmail;
 045            var password = _options.AdminPassword;
 46
 047            if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
 048                return;
 49
 050            var existing = await _userManager.FindByEmailAsync(email);
 051            if (existing is not null)
 052                return;
 53
 054            var user = new CustomIdentityUser { UserName = email, Email = email };
 055            var result = await _userManager.CreateAsync(user, password);
 056            if (result.Succeeded)
 057                await _userManager.AddToRoleAsync(user, "Admin");
 058        }
 59    }
 60}