Add user editing

This commit is contained in:
2025-10-20 16:40:12 +09:00
parent 772344649f
commit 7741b24859
4 changed files with 189 additions and 4 deletions

View File

@ -4,10 +4,14 @@ using Microsoft.EntityFrameworkCore;
namespace Hcs.WebApp.Services
{
public class UsersService(IDbContextFactory<AppIdentityDbContext> factory, UserManager<AppUser> userManager)
public class UsersService(
IDbContextFactory<AppIdentityDbContext> factory,
UserManager<AppUser> userManager,
IPasswordHasher<AppUser> passwordHasher)
{
private readonly IDbContextFactory<AppIdentityDbContext> factory = factory;
private readonly UserManager<AppUser> userManager = userManager;
private readonly IPasswordHasher<AppUser> passwordHasher = passwordHasher;
public async Task<IEnumerable<AppUserWithRole>> GetUsersWithRole()
{
@ -36,5 +40,53 @@ namespace Hcs.WebApp.Services
}
return result;
}
public async Task UpdateUser(string userId, string roleId, string password)
{
using var context = factory.CreateDbContext();
using var transaction = await context.Database.BeginTransactionAsync();
try
{
var curUserRole = await (from userRole in context.UserRoles
where userRole.UserId == userId
select userRole).SingleAsync();
var curRole = await (from role in context.Roles
where role.Id == curUserRole.RoleId
select role).SingleAsync();
if (curRole.Id != roleId)
{
context.UserRoles.Remove(curUserRole);
var newRole = await (from role in context.Roles
where role.Id == roleId
select role).SingleAsync();
await context.UserRoles.AddAsync(new IdentityUserRole<string>()
{
UserId = userId,
RoleId = newRole.Id
});
}
var curUser = await (from user in context.Users
where user.Id == userId
select user).SingleAsync();
var newPasswordHash = passwordHasher.HashPassword(curUser, password);
if (curUser.PasswordHash != newPasswordHash)
{
curUser.PasswordHash = newPasswordHash;
context.Users.Update(curUser);
}
await context.SaveChangesAsync();
}
catch (Exception)
{
await transaction.RollbackAsync();
throw;
}
await transaction.CommitAsync();
}
}
}