add roles seeding
This commit is contained in:
@@ -46,16 +46,13 @@ builder.Services.AddAuthentication(options => {
|
||||
};
|
||||
});
|
||||
|
||||
// TODO: adding roles doesnt work atm because roles need to be seeded in the database first
|
||||
// maybe programamatically checking them at startup like if(roleManager_.FindAsync("Admin") == null { roleManager_.addAsync("Admin"); })
|
||||
// or something
|
||||
builder.Services.AddAuthorization(options => {
|
||||
options.AddPolicy("RequireAdmin", policy => {
|
||||
policy.RequireRole("Admin", "Superuser");
|
||||
});
|
||||
options.AddPolicy("RequireSuperuser", policy => {
|
||||
policy.RequireRole("Superuser");
|
||||
});
|
||||
|
||||
options.AddPolicy("SensitiveDataRead", policy =>
|
||||
policy.RequireRole("admin", "superuser"));
|
||||
options.AddPolicy("SensitiveDataModify", policy =>
|
||||
policy.RequireRole("superuser"));
|
||||
|
||||
});
|
||||
|
||||
// configuration for behind my nginx proxy
|
||||
@@ -123,6 +120,18 @@ using (var scope = app.Services.CreateScope()) {
|
||||
Thread.Sleep(5000);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: abstract this away
|
||||
// auto seed Identity roles
|
||||
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
|
||||
string[] roles = { "guest", "user", "dev", "mod", "admin", "superuser", "role1", "role2" };
|
||||
foreach(string role in roles) {
|
||||
if(!await roleManager.RoleExistsAsync(role)) {
|
||||
await roleManager.CreateAsync(new IdentityRole(role));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -37,12 +37,13 @@ public class AuthController : ControllerBase {
|
||||
// assigning roles to user
|
||||
string role = "base";
|
||||
if(dto.UserName == "bard") {
|
||||
role = "Superuser";
|
||||
role = "superuser";
|
||||
} else if(dto.UserName.StartsWith("x")) {
|
||||
role = "Admin";
|
||||
role = "admin";
|
||||
}
|
||||
await userManager_.AddToRoleAsync(user, role); // TODO: error check this
|
||||
// await _userManager.RemoveFromRoleAsync(user, "Admin"); // remove role
|
||||
// these are here just in case you need them
|
||||
// await _userManager.RemoveFromRoleAsync(user, "admin"); // remove role
|
||||
// var roles = await _userManager.GetRolesAsync(user); // get list of roles for user
|
||||
|
||||
return CreatedAtAction(
|
||||
|
||||
Reference in New Issue
Block a user