41 lines
1.5 KiB
C#
41 lines
1.5 KiB
C#
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;
|
|
}
|
|
}
|
|
}
|