| | | 1 | | using Microsoft.AspNetCore.Identity; |
| | | 2 | | using Microsoft.EntityFrameworkCore; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using OzonRepositories.Context.Identity; |
| | | 5 | | |
| | | 6 | | namespace 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 | | |
| | 0 | 14 | | public DbInitializer( |
| | 0 | 15 | | RoleManager<IdentityRole> roleManager, |
| | 0 | 16 | | UserManager<CustomIdentityUser> userManager, |
| | 0 | 17 | | IOptions<DbSeederOptions> options) |
| | | 18 | | { |
| | 0 | 19 | | _roleManager = roleManager; |
| | 0 | 20 | | _userManager = userManager; |
| | 0 | 21 | | _options = options.Value; |
| | 0 | 22 | | } |
| | | 23 | | |
| | | 24 | | public async Task InitializeAsync(CancellationToken ct = default) |
| | | 25 | | { |
| | 0 | 26 | | if (!await _roleManager.Roles.AnyAsync(ct)) |
| | 0 | 27 | | await CreateRoles(ct); |
| | | 28 | | |
| | 0 | 29 | | await CreateAdmin(ct); |
| | 0 | 30 | | } |
| | | 31 | | |
| | | 32 | | private async Task CreateRoles(CancellationToken ct) |
| | | 33 | | { |
| | 0 | 34 | | string[] roleNames = { "Admin", "User" }; |
| | 0 | 35 | | foreach (var roleName in roleNames) |
| | | 36 | | { |
| | 0 | 37 | | if (!await _roleManager.RoleExistsAsync(roleName)) |
| | 0 | 38 | | await _roleManager.CreateAsync(new IdentityRole(roleName)); |
| | 0 | 39 | | } |
| | 0 | 40 | | } |
| | | 41 | | |
| | | 42 | | private async Task CreateAdmin(CancellationToken ct) |
| | | 43 | | { |
| | 0 | 44 | | var email = _options.AdminEmail; |
| | 0 | 45 | | var password = _options.AdminPassword; |
| | | 46 | | |
| | 0 | 47 | | if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password)) |
| | 0 | 48 | | return; |
| | | 49 | | |
| | 0 | 50 | | var existing = await _userManager.FindByEmailAsync(email); |
| | 0 | 51 | | if (existing is not null) |
| | 0 | 52 | | return; |
| | | 53 | | |
| | 0 | 54 | | var user = new CustomIdentityUser { UserName = email, Email = email }; |
| | 0 | 55 | | var result = await _userManager.CreateAsync(user, password); |
| | 0 | 56 | | if (result.Succeeded) |
| | 0 | 57 | | await _userManager.AddToRoleAsync(user, "Admin"); |
| | 0 | 58 | | } |
| | | 59 | | } |
| | | 60 | | } |