Add user editing
This commit is contained in:
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user