[CHANGE] Updated role repository tasks

This commit is contained in:
max 2025-04-11 19:57:20 +02:00
parent 0a5950cfa2
commit f0cb7218ac
3 changed files with 151 additions and 233 deletions

View File

@ -2,17 +2,15 @@ using DotBased.AspNet.Authority.EFCore.Models;
using DotBased.AspNet.Authority.Models; using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Repositories; using DotBased.AspNet.Authority.Repositories;
using DotBased.Monads;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DotBased.AspNet.Authority.EFCore.Repositories; namespace DotBased.AspNet.Authority.EFCore.Repositories;
public class RoleRepository(IDbContextFactory<AuthorityContext> contextFactory) : RepositoryBase, IRoleRepository public class RoleRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<RoleRepository> logger) : RepositoryBase, IRoleRepository
{ {
public async Task<Result<QueryItems<AuthorityRoleItem>>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default) public async Task<QueryItems<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var query = context.Roles.AsQueryable(); var query = context.Roles.AsQueryable();
@ -30,179 +28,106 @@ public class RoleRepository(IDbContextFactory<AuthorityContext> contextFactory)
}).ToListAsync(cancellationToken: cancellationToken); }).ToListAsync(cancellationToken: cancellationToken);
return QueryItems<AuthorityRoleItem>.Create(select, total, limit, offset); return QueryItems<AuthorityRoleItem>.Create(select, total, limit, offset);
} }
catch (Exception e)
{
return e;
}
}
public async Task<Result<AuthorityRole>> GetRoleByIdAsync(Guid id, CancellationToken cancellationToken = default) public async Task<AuthorityRole?> GetRoleByIdAsync(Guid id, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var role = await context.Roles.Where(r => r.Id == id).Include(r => r.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken); var role = await context.Roles.Where(r => r.Id == id).Include(r => r.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
if (role != null)
{
return role; return role;
} }
return ResultError.Fail("Role not found!");
}
catch (Exception e)
{
return e;
}
}
public async Task<Result<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default) public async Task<AuthorityRole?> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (role.Id == Guid.Empty) if (role.Id == Guid.Empty)
{ {
return ResultError.Fail("Id cannot be empty!"); throw new Exception("Role id is required!");
} }
var entity = context.Roles.Add(role); var entity = context.Roles.Add(role);
var saveResult = await context.SaveChangesAsync(cancellationToken); var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult <= 0 ? ResultError.Fail("Failed to create role!") : entity.Entity;
} return saveResult != 0 ? entity.Entity : null;
catch (Exception e)
{
return e;
}
} }
public async Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default) public async Task<AuthorityRole?> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentRole = await context.Roles.FirstOrDefaultAsync(r => r.Id == role.Id, cancellationToken: cancellationToken); var currentRole = await context.Roles.FirstOrDefaultAsync(r => r.Id == role.Id, cancellationToken: cancellationToken);
if (currentRole == null) if (currentRole == null)
{ {
return ResultError.Fail("Role not found!"); throw new Exception($"Role with id {role.Id} not found!");
} }
if (role.Version != currentRole.Version) if (role.Version != currentRole.Version)
{ {
return ResultError.Fail("Role version does not match, version validation failed!"); throw new Exception("Role version does not match!");
} }
var entity = context.Roles.Update(role); var entity = context.Roles.Update(role);
var saveResult = await context.SaveChangesAsync(cancellationToken); var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult <= 0 ? ResultError.Fail("Failed to update role!") : entity.Entity; return saveResult != 0 ? entity.Entity : null;
}
catch (Exception e)
{
return e;
}
} }
public async Task<Result> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default) public async Task<bool> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var roleIds = roles.Select(r => r.Id).ToList(); var roleIds = roles.Select(r => r.Id).ToList();
context.Roles.RemoveRange(roles); context.Roles.RemoveRange(roles);
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rg => roleIds.Contains(rg.RoleId))); context.RoleLinks.RemoveRange(context.RoleLinks.Where(rl => roleIds.Contains(rl.RoleId)));
var removeResult = await context.SaveChangesAsync(cancellationToken); var removedRoles = await context.SaveChangesAsync(cancellationToken);
return removeResult == roles.Count? Result.Success() : ResultError.Fail($"Not all roles have been removed! {removeResult} of {roles.Count} roles removed!"); if (removedRoles == roles.Count)
}
catch (Exception e)
{ {
return e; return true;
} }
logger.LogError("Failed to remove all roles, {removedRoles}/{totalRoles} roles removed!", removedRoles, roles.Count);
return false;
} }
public async Task<ListResultOld<AuthorityRoleItem>> GetUserRolesAsync(AuthorityUser user, int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default) public async Task<bool> AddRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default)
{
try
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var roleIds = await context.RoleLinks.Where(r => r.LinkId == user.Id).Select(i => i.RoleId).ToListAsync(cancellationToken: cancellationToken);
var rolesQuery = context.Roles.Where(r => roleIds.Contains(r.Id));
if (!string.IsNullOrEmpty(search))
{
rolesQuery = rolesQuery.Where(r => r.Name.Contains(search));
}
var roles = rolesQuery.Where(r => roleIds.Contains(r.Id)).Skip(offset).Take(limit).Select(r => new AuthorityRoleItem()
{
Id = r.Id,
Name = r.Name
});
return ListResultOld<AuthorityRoleItem>.Ok(roles, limit, offset);
}
catch (Exception e)
{
return HandleExceptionListResult<AuthorityRoleItem>("Failed to get user roles.", e);
}
}
public async Task<Result> AddRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
foreach (var role in roles) foreach (var role in roles)
{ {
context.RoleLinks.Add(new RoleLink() { LinkId = linkId, RoleId = role.Id }); context.RoleLinks.Add(new RoleLink { LinkId = linkId, RoleId = role.Id });
} }
var saveResult = await context.SaveChangesAsync(cancellationToken); var linkedRoles = await context.SaveChangesAsync(cancellationToken);
return saveResult == roles.Count ? Result.Success() : ResultError.Fail($"Not all roles have been linked! {saveResult} of {roles.Count} roles linked!"); if (linkedRoles == roles.Count)
}
catch (Exception e)
{ {
return e; return true;
}
} }
public async Task<Result<List<AuthorityRole>>> GetLinkedRolesAsync(List<Guid> linkIds, CancellationToken cancellationToken = default) logger.LogError("Failed to link all given roles, {linkedRoles}/{totalRoles} roles linked!", linkedRoles, roles.Count);
{ return false;
try }
public async Task<List<AuthorityRole>> GetLinkedRolesAsync(List<Guid> linkIds, CancellationToken cancellationToken = default)
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var linkedRoles = context.RoleLinks.Where(r => linkIds.Contains(r.LinkId)).Select(r => r.RoleId); var linkedRoles = context.RoleLinks.Where(r => linkIds.Contains(r.LinkId)).Select(r => r.RoleId);
var roleList = await context.Roles.Where(r => linkedRoles.Contains(r.Id)).ToListAsync(cancellationToken); var roleList = await context.Roles.Where(r => linkedRoles.Contains(r.Id)).ToListAsync(cancellationToken);
return roleList.DistinctBy(r => r.Id).ToList(); return roleList.DistinctBy(r => r.Id).ToList();
} }
catch (Exception e)
{
return e;
}
}
public async Task<Result> DeleteRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default) public async Task<bool> UnlinkRolesAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default)
{
try
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var roleIds = roles.Select(r => r.Id).ToList(); var roleIds = roles.Select(r => r.Id).ToList();
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rg => rg.LinkId == linkId && roleIds.Contains(rg.RoleId))); context.RoleLinks.RemoveRange(context.RoleLinks.Where(rg => rg.LinkId == linkId && roleIds.Contains(rg.RoleId)));
var saveResult = await context.SaveChangesAsync(cancellationToken); var unlinkedRoles = await context.SaveChangesAsync(cancellationToken);
return saveResult == roles.Count ? Result.Success() : ResultError.Fail($"Not all roles have been unlinked! {saveResult} of {roles.Count} roles unlinked!"); if (unlinkedRoles == roles.Count)
}
catch (Exception e)
{ {
return e; return true;
}
} }
public async Task<Result<List<Guid>>> HasRolesAsync(Guid linkId, List<AuthorityRole> roles, CancellationToken cancellationToken = default) logger.LogError("Failed to remove all linked roles, {unlinkedRoles}/{totalRoles} roles unlinked!", unlinkedRoles, roles.Count);
{ return false;
try }
public async Task<List<Guid>> GetRolesFromLinkAsync(Guid linkId, List<AuthorityRole> roles, CancellationToken cancellationToken = default)
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var hasRoles = await context.RoleLinks.Where(r => r.LinkId == linkId && roles.Any(ar => ar.Id == r.RoleId)).Select(r => r.RoleId).ToListAsync(cancellationToken); return await context.RoleLinks.Where(r => r.LinkId == linkId && roles.Any(ar => ar.Id == r.RoleId)).Select(r => r.RoleId).ToListAsync(cancellationToken);
return hasRoles;
}
catch (Exception e)
{
return e;
}
} }
} }

View File

@ -10,18 +10,28 @@ public partial class AuthorityManager
{ {
role.Version = GenerateVersion(); role.Version = GenerateVersion();
var createResult = await RoleRepository.CreateRoleAsync(role, cancellationToken); var createResult = await RoleRepository.CreateRoleAsync(role, cancellationToken);
if (createResult == null)
{
return ResultError.Fail("Failed to create new role.");
}
return createResult; return createResult;
} }
public async Task<Result> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default) public async Task<Result> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default)
{ {
var result = await RoleRepository.DeleteRolesAsync(roles, cancellationToken); var success = await RoleRepository.DeleteRolesAsync(roles, cancellationToken);
return result; return success ? Result.Success() : ResultError.Fail("Failed to delete roles.");
} }
public async Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default) public async Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
{ {
var result = await RoleRepository.UpdateRoleAsync(role, cancellationToken); var result = await RoleRepository.UpdateRoleAsync(role, cancellationToken);
if (result == null)
{
return ResultError.Fail("Failed to update role.");
}
return result; return result;
} }
@ -31,81 +41,59 @@ public partial class AuthorityManager
return searchResult; return searchResult;
} }
public async Task AddRolesToUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default) public async Task<Result> AddRolesToUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
{ {
var usrValidation = await IsValidUserAsync(user, cancellationToken); var usrValidation = await IsValidUserAsync(user, cancellationToken);
if (!usrValidation.Success) if (!usrValidation.Success)
{ {
_logger.Error(usrValidation.Exception ?? new Exception("Validation for user failed!"), "Invalid user!"); return ResultError.Fail("Validation for user failed!");
return;
} }
var checkResult = await RoleRepository.HasRolesAsync(user.Id, roles, cancellationToken); var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(user.Id, roles, cancellationToken);
var hasRolesList = checkResult.Match<List<Guid>>(success: v => v, (_) => []);
var rolesToAdd = roles; var rolesToAdd = roles;
if (hasRolesList.Count != 0) if (linkedRoles.Count != 0)
{ {
rolesToAdd = roles.Where(r => !hasRolesList.Contains(r.Id)).ToList(); rolesToAdd = roles.Where(r => !linkedRoles.Contains(r.Id)).ToList();
} }
var addResult = await RoleRepository.AddRolesLinkAsync(rolesToAdd, user.Id, cancellationToken); var addSuccess = await RoleRepository.AddRolesLinkAsync(rolesToAdd, user.Id, cancellationToken);
addResult.Match(() =>
{ return addSuccess ? Result.Success() : ResultError.Fail("Failed to add roles.");
_logger.Debug("Role links successfully added!");
}, e =>
{
_logger.Error(e.Exception ?? new Exception("Match failed!"), e.Description);
});
} }
public async Task RemoveRolesFromUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default) public async Task<Result> RemoveRolesFromUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
{ {
var usrValidation = await IsValidUserAsync(user, cancellationToken); var usrValidation = await IsValidUserAsync(user, cancellationToken);
if (!usrValidation.Success) if (!usrValidation.Success)
{ {
_logger.Error(usrValidation.Exception ?? new Exception("Validation for user failed!"), "Invalid user!"); return ResultError.Fail("Validation for user failed!");
return;
} }
var checkResult = await RoleRepository.HasRolesAsync(user.Id, roles, cancellationToken); var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(user.Id, roles, cancellationToken);
var hasRolesList = checkResult.Match<List<Guid>>(success: v => v, (_) => []);
var rolesToRemove = roles; var rolesToRemove = roles;
if (hasRolesList.Count != 0) if (linkedRoles.Count != 0)
{ {
rolesToRemove = roles.Where(r => !hasRolesList.Contains(r.Id)).ToList(); rolesToRemove = roles.Where(r => !linkedRoles.Contains(r.Id)).ToList();
} }
var removeResult = await RoleRepository.DeleteRolesLinkAsync(rolesToRemove, user.Id, cancellationToken); var removeResult = await RoleRepository.UnlinkRolesAsync(rolesToRemove, user.Id, cancellationToken);
removeResult.Match(() => return removeResult ? Result.Success() : ResultError.Fail("Failed to remove roles.");
{
_logger.Debug("Removed roles from user!");
}, e =>
{
_logger.Error(e.Exception ?? new Exception("Removing roles from user failed!"), e.Description);
});
} }
public async Task AddRolesToGroupAsync(List<AuthorityRole> roles, AuthorityGroup group, CancellationToken cancellationToken = default) public async Task<Result> AddRolesToGroupAsync(List<AuthorityRole> roles, AuthorityGroup group, CancellationToken cancellationToken = default)
{ {
var checkResult = await RoleRepository.HasRolesAsync(group.Id, roles, cancellationToken); var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(group.Id, roles, cancellationToken);
var hasRolesList = checkResult.Match<List<Guid>>(success: v => v, (_) => []);
var rolesToAdd = roles; var rolesToAdd = roles;
if (hasRolesList.Count != 0) if (linkedRoles.Count != 0)
{ {
rolesToAdd = roles.Where(r => !hasRolesList.Contains(r.Id)).ToList(); rolesToAdd = roles.Where(r => !linkedRoles.Contains(r.Id)).ToList();
} }
var addResult = await RoleRepository.AddRolesLinkAsync(rolesToAdd, group.Id, cancellationToken); var linkResult = await RoleRepository.AddRolesLinkAsync(rolesToAdd, group.Id, cancellationToken);
addResult.Match(() => return linkResult ? Result.Success() : ResultError.Fail("Failed to add roles.");
{
_logger.Debug("Added roles to group.");
}, e =>
{
_logger.Error(e.Exception ?? new Exception("Adding roles to group failed!"), e.Description);
});
} }
/// <summary> /// <summary>
@ -114,6 +102,8 @@ public partial class AuthorityManager
/// <param name="user">The user to get the roles from</param> /// <param name="user">The user to get the roles from</param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
public async Task<Result<List<AuthorityRole>>> GetUserRolesAsync(AuthorityUser user, CancellationToken cancellationToken = default) public async Task<Result<List<AuthorityRole>>> GetUserRolesAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
try
{ {
var usrValidation = await IsValidUserAsync(user, cancellationToken); var usrValidation = await IsValidUserAsync(user, cancellationToken);
if (!usrValidation.Success) if (!usrValidation.Success)
@ -130,20 +120,24 @@ public partial class AuthorityManager
} }
var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(searchIds, cancellationToken); var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(searchIds, cancellationToken);
return linkedRolesResult.Match<List<AuthorityRole>>(roles => roles, e => return linkedRolesResult;
}
catch (Exception e)
{ {
_logger.Error(e.Exception ?? new Exception("Failed to get user roles!"), e.Description); return e;
return []; }
});
} }
public async Task<Result<List<AuthorityRole>>> GetGroupRolesAsync(List<Guid> groupIds, CancellationToken cancellationToken = default) public async Task<Result<List<AuthorityRole>>> GetGroupRolesAsync(List<Guid> groupIds, CancellationToken cancellationToken = default)
{ {
var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(groupIds, cancellationToken); try
return linkedRolesResult.Match<List<AuthorityRole>>(roles => roles, e =>
{ {
_logger.Error(e.Exception ?? new Exception("Failed to get group roles!"), e.Description); var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(groupIds, cancellationToken);
return []; return linkedRolesResult;
}); }
catch (Exception e)
{
return e;
}
} }
} }

View File

@ -1,19 +1,18 @@
using DotBased.AspNet.Authority.Models; using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
using DotBased.Monads;
namespace DotBased.AspNet.Authority.Repositories; namespace DotBased.AspNet.Authority.Repositories;
public interface IRoleRepository public interface IRoleRepository
{ {
public Task<Result<QueryItems<AuthorityRoleItem>>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default); public Task<QueryItems<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
public Task<Result<AuthorityRole>> GetRoleByIdAsync(Guid id, CancellationToken cancellationToken = default); public Task<AuthorityRole?> GetRoleByIdAsync(Guid id, CancellationToken cancellationToken = default);
public Task<Result<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default); public Task<AuthorityRole?> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
public Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default); public Task<AuthorityRole?> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
public Task<Result> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default); public Task<bool> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default);
public Task<Result> AddRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default); public Task<bool> AddRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default);
public Task<Result<List<AuthorityRole>>> GetLinkedRolesAsync(List<Guid> linkIds, CancellationToken cancellationToken = default); public Task<List<AuthorityRole>> GetLinkedRolesAsync(List<Guid> linkIds, CancellationToken cancellationToken = default);
public Task<Result> DeleteRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default); public Task<bool> UnlinkRolesAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default);
/// <summary> /// <summary>
/// Return the role ids the linkId has. /// Return the role ids the linkId has.
@ -22,5 +21,5 @@ public interface IRoleRepository
/// <param name="roles"></param> /// <param name="roles"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public Task<Result<List<Guid>>> HasRolesAsync(Guid linkId, List<AuthorityRole> roles, CancellationToken cancellationToken = default); public Task<List<Guid>> GetRolesFromLinkAsync(Guid linkId, List<AuthorityRole> roles, CancellationToken cancellationToken = default);
} }