Add new user creation
This commit is contained in:
40
Hcs.WebApp/Services/UsersService.cs
Normal file
40
Hcs.WebApp/Services/UsersService.cs
Normal file
@ -0,0 +1,40 @@
|
||||
using Hcs.WebApp.Data;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Hcs.WebApp.Services
|
||||
{
|
||||
public class UsersService(IDbContextFactory<AppIdentityDbContext> factory, UserManager<AppUser> userManager)
|
||||
{
|
||||
private readonly IDbContextFactory<AppIdentityDbContext> factory = factory;
|
||||
private readonly UserManager<AppUser> userManager = userManager;
|
||||
|
||||
public async Task<IEnumerable<AppUserWithRole>> GetUsersWithRole()
|
||||
{
|
||||
using var context = factory.CreateDbContext();
|
||||
return await (from user in context.Users
|
||||
join userRole in context.UserRoles on user.Id equals userRole.UserId
|
||||
join role in context.Roles on userRole.RoleId equals role.Id
|
||||
select new AppUserWithRole()
|
||||
{
|
||||
User = user,
|
||||
Role = role
|
||||
}).ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<IdentityResult> CreateUser(string userName, string roleName, string password)
|
||||
{
|
||||
var user = new AppUser()
|
||||
{
|
||||
UserName = userName,
|
||||
NormalizedUserName = userName.Normalize()
|
||||
};
|
||||
var result = await userManager.CreateAsync(user, password);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
result = await userManager.AddToRolesAsync(user, [roleName]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user