This repository has been archived by the owner on Jun 20, 2024. It is now read-only.
forked from abrl91/dot-net8-api-sample
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSeedDevelopmentData.cs
49 lines (42 loc) · 1.58 KB
/
SeedDevelopmentData.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using MyService.Infrastructure;
namespace MyService;
public class SeedDevelopmentData
{
private static string devEmail = "[email protected]";
private static string devPassword = "1Password!";
public static async Task SeedDevUser(
IServiceProvider serviceProvider,
IConfiguration configuration
)
{
var context = serviceProvider.GetRequiredService<MyServiceContext>();
var amplicationRoles = configuration
.GetSection("AmplicationRoles")
.AsEnumerable()
.Where(x => x.Value != null)
.Select(x => x.Value?.ToString())
.ToArray();
var user = new User
{
UserName = devEmail,
NormalizedUserName = devEmail.ToUpperInvariant(),
Email = devEmail,
NormalizedEmail = devEmail.ToUpperInvariant(),
EmailConfirmed = true,
LockoutEnabled = false,
};
if (!context.Users.Any(u => u.UserName == user.UserName))
{
var userManager = serviceProvider.GetRequiredService<UserManager<User>>();
var ca = await userManager.CreateAsync(user);
var ap = await userManager.AddPasswordAsync(user, devPassword);
var _roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
foreach (var role in amplicationRoles)
{
await userManager.AddToRoleAsync(user, _roleManager.NormalizeKey(role));
}
}
}
}