-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSeedData.cs
74 lines (65 loc) · 2.39 KB
/
SeedData.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using BlazorTemplate.Server.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorTemplate.Server.Data
{
public class SeedData
{
private readonly ApplicationDbContext ctx;
public SeedData(ApplicationDbContext dbContext)
{
ctx = dbContext;
}
public async Task CreateUserAndRoles(IServiceProvider serviceProvider)
{
if (ctx.Users.Any())
{
return;
}
// Initializing Custom Roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Administrators", "Users" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
// Create Administrator
ApplicationUser admin = await UserManager.FindByEmailAsync("[email protected]");
if (admin == null)
{
admin = new ApplicationUser()
{
UserName = "[email protected]",
Email = "[email protected]",
CustomClaim = "AdminClaim"
};
await UserManager.CreateAsync(admin, "Qwerty1234#");
}
// Add Roles
await UserManager.AddToRoleAsync(admin, "Administrators");
await UserManager.AddToRoleAsync(admin, "Users");
// Create User
ApplicationUser user = await UserManager.FindByEmailAsync("[email protected]");
if (user == null)
{
user = new ApplicationUser()
{
UserName = "[email protected]",
Email = "[email protected]",
CustomClaim = "UserClaim"
};
await UserManager.CreateAsync(user, "Qwerty1234#");
}
await UserManager.AddToRoleAsync(user, "Users");
}
}
}