mirror of
https://github.com/hmaxnl/DotBased.git
synced 2025-04-19 03:58:12 +02:00
[CHANGE] Adding functionality to manager
This commit is contained in:
parent
d6c0ad1138
commit
d8b08a763e
|
@ -11,54 +11,47 @@ public class AuthorityContext(DbContextOptions<AuthorityContext> options) : DbCo
|
||||||
public DbSet<AuthorityRole> Roles { get; set; }
|
public DbSet<AuthorityRole> Roles { get; set; }
|
||||||
public DbSet<AuthorityUser> Users { get; set; }
|
public DbSet<AuthorityUser> Users { get; set; }
|
||||||
|
|
||||||
public DbSet<RoleGroup> RoleGroup { get; set; }
|
public DbSet<RoleLink> RoleLinks { get; set; }
|
||||||
public DbSet<RoleUser> RoleUser { get; set; }
|
public DbSet<UserGroups> UserGroups { get; set; }
|
||||||
public DbSet<UserGroup> UserGroup { get; set; }
|
|
||||||
|
|
||||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
{
|
{
|
||||||
modelBuilder.Entity<AuthorityAttribute>(attributeEntity =>
|
modelBuilder.Entity<AuthorityAttribute>(attributeEntity =>
|
||||||
{
|
{
|
||||||
attributeEntity.ToTable("authority_attributes");
|
attributeEntity.ToTable("authority_attributes");
|
||||||
attributeEntity.HasKey(a => new { a.BoundId, a.AttributeKey });
|
attributeEntity.HasKey(a => new { a.ForeignKey, a.AttributeKey });
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity<AuthorityGroup>(groupEntity =>
|
modelBuilder.Entity<AuthorityGroup>(groupEntity =>
|
||||||
{
|
{
|
||||||
groupEntity.ToTable("authority_groups");
|
groupEntity.ToTable("authority_groups");
|
||||||
groupEntity.HasKey(x => x.Id);
|
groupEntity.HasKey(x => x.Id);
|
||||||
groupEntity.HasMany(g => g.Attributes).WithOne().HasForeignKey(a => a.BoundId).OnDelete(DeleteBehavior.Cascade);
|
groupEntity.HasMany(g => g.Attributes).WithOne().HasForeignKey(a => a.ForeignKey).OnDelete(DeleteBehavior.Cascade);
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity<AuthorityRole>(roleEntity =>
|
modelBuilder.Entity<AuthorityRole>(roleEntity =>
|
||||||
{
|
{
|
||||||
roleEntity.ToTable("authority_roles");
|
roleEntity.ToTable("authority_roles");
|
||||||
roleEntity.HasKey(x => x.Id);
|
roleEntity.HasKey(x => x.Id);
|
||||||
roleEntity.HasMany(r => r.Attributes).WithOne().HasForeignKey(a => a.BoundId).OnDelete(DeleteBehavior.Cascade);
|
roleEntity.HasMany(r => r.Attributes).WithOne().HasForeignKey(a => a.ForeignKey).OnDelete(DeleteBehavior.Cascade);
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity<AuthorityUser>(userEntity =>
|
modelBuilder.Entity<AuthorityUser>(userEntity =>
|
||||||
{
|
{
|
||||||
userEntity.ToTable("authority_users");
|
userEntity.ToTable("authority_users");
|
||||||
userEntity.HasKey(x => x.Id);
|
userEntity.HasKey(x => x.Id);
|
||||||
userEntity.HasMany(u => u.Attributes).WithOne().HasForeignKey(a => a.BoundId).OnDelete(DeleteBehavior.Cascade);
|
userEntity.HasMany(u => u.Attributes).WithOne().HasForeignKey(a => a.ForeignKey).OnDelete(DeleteBehavior.Cascade);
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity<RoleGroup>(rgEntity =>
|
modelBuilder.Entity<RoleLink>(rgEntity =>
|
||||||
{
|
{
|
||||||
rgEntity.ToTable("role_group");
|
rgEntity.ToTable("role_links");
|
||||||
rgEntity.HasKey(rg => new { rg.RoleId, rg.GroupId });
|
rgEntity.HasKey(rg => new { rg.RoleId, rg.LinkId });
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity<RoleUser>(ruEntity =>
|
modelBuilder.Entity<UserGroups>(ugEntity =>
|
||||||
{
|
{
|
||||||
ruEntity.ToTable("role_user");
|
ugEntity.ToTable("user_groups");
|
||||||
ruEntity.HasKey(ru => new { ru.RoleId, ru.UserId });
|
|
||||||
});
|
|
||||||
|
|
||||||
modelBuilder.Entity<UserGroup>(ugEntity =>
|
|
||||||
{
|
|
||||||
ugEntity.ToTable("user_group");
|
|
||||||
ugEntity.HasKey(ug => new { ug.UserId, ug.GroupId });
|
ugEntity.HasKey(ug => new { ug.UserId, ug.GroupId });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
namespace DotBased.AspNet.Authority.EFCore.Models;
|
namespace DotBased.AspNet.Authority.EFCore.Models;
|
||||||
|
|
||||||
public class RoleGroup
|
public class RoleLink
|
||||||
{
|
{
|
||||||
public Guid RoleId { get; set; }
|
public Guid RoleId { get; set; }
|
||||||
public Guid GroupId { get; set; }
|
public Guid LinkId { get; set; }
|
||||||
}
|
}
|
|
@ -1,6 +1,6 @@
|
||||||
namespace DotBased.AspNet.Authority.EFCore.Models;
|
namespace DotBased.AspNet.Authority.EFCore.Models;
|
||||||
|
|
||||||
public class UserGroup
|
public class UserGroups
|
||||||
{
|
{
|
||||||
public Guid UserId { get; set; }
|
public Guid UserId { get; set; }
|
||||||
public Guid GroupId { get; set; }
|
public Guid GroupId { get; set; }
|
|
@ -1,6 +1,6 @@
|
||||||
namespace DotBased.AspNet.Authority.EFCore.Models;
|
namespace DotBased.AspNet.Authority.EFCore.Models;
|
||||||
|
|
||||||
public class RoleUser
|
public class UserRoles
|
||||||
{
|
{
|
||||||
public Guid RoleId { get; set; }
|
public Guid RoleId { get; set; }
|
||||||
public Guid UserId { get; set; }
|
public Guid UserId { get; set; }
|
|
@ -15,13 +15,13 @@ public class AttributeRepository(IDbContextFactory<AuthorityContext> contextFact
|
||||||
var query = context.Attributes.AsQueryable();
|
var query = context.Attributes.AsQueryable();
|
||||||
if (!string.IsNullOrEmpty(search))
|
if (!string.IsNullOrEmpty(search))
|
||||||
{
|
{
|
||||||
query = query.Where(a => $"{a.AttributeKey} {a.BoundId} {a.AttributeValue}".Contains(search, StringComparison.CurrentCultureIgnoreCase));
|
query = query.Where(a => $"{a.AttributeKey} {a.ForeignKey} {a.AttributeValue}".Contains(search, StringComparison.CurrentCultureIgnoreCase));
|
||||||
}
|
}
|
||||||
|
|
||||||
var total = await query.CountAsync(cancellationToken);
|
var total = await query.CountAsync(cancellationToken);
|
||||||
var select = await query.OrderBy(a => a.AttributeKey).Skip(offset).Take(limit).Select(a => new AuthorityAttributeItem()
|
var select = await query.OrderBy(a => a.AttributeKey).Skip(offset).Take(limit).Select(a => new AuthorityAttributeItem()
|
||||||
{
|
{
|
||||||
BoundId = a.BoundId,
|
BoundId = a.ForeignKey,
|
||||||
AttributeKey = a.AttributeKey,
|
AttributeKey = a.AttributeKey,
|
||||||
AttributeValue = a.AttributeValue
|
AttributeValue = a.AttributeValue
|
||||||
}).ToListAsync(cancellationToken);
|
}).ToListAsync(cancellationToken);
|
||||||
|
@ -52,7 +52,7 @@ public class AttributeRepository(IDbContextFactory<AuthorityContext> contextFact
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
if (string.IsNullOrWhiteSpace(attribute.AttributeKey) || attribute.BoundId == Guid.Empty)
|
if (string.IsNullOrWhiteSpace(attribute.AttributeKey) || attribute.ForeignKey == Guid.Empty)
|
||||||
{
|
{
|
||||||
return Result<AuthorityAttribute>.Failed("Attribute key and/or bound id is empty");
|
return Result<AuthorityAttribute>.Failed("Attribute key and/or bound id is empty");
|
||||||
}
|
}
|
||||||
|
|
|
@ -48,6 +48,21 @@ public class GroupRepository(IDbContextFactory<AuthorityContext> contextFactory)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<ListResult<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
|
var userJoinGroups = context.UserGroups.Where(ug => ug.UserId == user.Id).Select(ug => ug.GroupId);
|
||||||
|
var userGroups = context.Groups.Where(g => userJoinGroups.Contains(g.Id));
|
||||||
|
return ListResult<AuthorityGroup>.Ok(userGroups, userGroups.Count());
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
return HandleExceptionListResult<AuthorityGroup>("Failed to get Groups", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<Result<AuthorityGroup>> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
|
public async Task<Result<AuthorityGroup>> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|
|
@ -1,9 +1,11 @@
|
||||||
|
using DotBased.AspNet.Authority.EFCore.Models;
|
||||||
using DotBased.AspNet.Authority.Models.Authority;
|
using DotBased.AspNet.Authority.Models.Authority;
|
||||||
using DotBased.AspNet.Authority.Repositories;
|
using DotBased.AspNet.Authority.Repositories;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
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) : RepositoryBase, IRoleRepository
|
||||||
{
|
{
|
||||||
public async Task<ListResult<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
public async Task<ListResult<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
||||||
|
@ -95,19 +97,18 @@ public class RoleRepository(IDbContextFactory<AuthorityContext> contextFactory)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Result> DeleteRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
public async Task<Result> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
try
|
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 roleIds = roles.Select(r => r.Id).ToList();
|
||||||
if (currentRole == null)
|
|
||||||
{
|
context.Roles.RemoveRange(roles);
|
||||||
return Result.Failed("Role not found, could not delete!");
|
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rg => roleIds.Contains(rg.RoleId)));
|
||||||
}
|
|
||||||
context.Roles.Remove(currentRole);
|
|
||||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||||
return saveResult <= 0 ? Result.Failed("Failed to delete role!") : Result.Ok();
|
return saveResult <= 0 ? Result.Failed("Failed to delete roles!") : Result.Ok();
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
|
@ -117,6 +118,89 @@ public class RoleRepository(IDbContextFactory<AuthorityContext> contextFactory)
|
||||||
|
|
||||||
public async Task<ListResult<AuthorityRoleItem>> GetUserRolesAsync(AuthorityUser user, int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
public async Task<ListResult<AuthorityRoleItem>> GetUserRolesAsync(AuthorityUser user, int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
return ListResult<AuthorityRoleItem>.Failed("Not implemented!");
|
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 ListResult<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);
|
||||||
|
foreach (var role in roles)
|
||||||
|
{
|
||||||
|
context.RoleLinks.Add(new RoleLink() { LinkId = linkId, RoleId = role.Id });
|
||||||
|
}
|
||||||
|
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||||
|
return saveResult <= 0 ? Result.Failed("Failed to ad role link!") : Result.Ok();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
return HandleException("Failed to add role link!", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ListResult<AuthorityRole>> GetLinkedRolesAsync(List<Guid> linkIds, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
|
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);
|
||||||
|
return ListResult<AuthorityRole>.Ok(roleList.DistinctBy(r => r.Id));
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
return HandleExceptionListResult<AuthorityRole>("Failed to get linked roles!", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Result> DeleteRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
|
var roleIds = roles.Select(r => r.Id).ToList();
|
||||||
|
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rg => rg.LinkId == linkId && roleIds.Contains(rg.RoleId)));
|
||||||
|
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||||
|
return saveResult <= 0 ? Result.Failed("Failed to delete role links!") : Result.Ok();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
return HandleException("Failed to delete role link!", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ListResult<Guid>> HasRolesAsync(Guid linkId, List<AuthorityRole> roles, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
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 ListResult<Guid>.Ok(hasRoles);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
return HandleExceptionListResult<Guid>("Failed to determine role for user!", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -4,8 +4,8 @@ namespace DotBased.AspNet.Authority.Managers;
|
||||||
|
|
||||||
public partial class AuthorityManager
|
public partial class AuthorityManager
|
||||||
{
|
{
|
||||||
public async Task<ListResult<AuthorityGroupItem>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
public async Task<ListResult<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
return ListResult<AuthorityGroupItem>.Failed("Not implemented!");
|
return await GroupRepository.GetUserGroupsAsync(user, cancellationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -14,6 +14,7 @@ public partial class AuthorityManager(
|
||||||
IServiceProvider services,
|
IServiceProvider services,
|
||||||
ICryptographer cryptographer,
|
ICryptographer cryptographer,
|
||||||
IUserRepository userRepository,
|
IUserRepository userRepository,
|
||||||
|
IGroupRepository groupRepository,
|
||||||
IRoleRepository roleRepository,
|
IRoleRepository roleRepository,
|
||||||
IPasswordHasher passwordHasher)
|
IPasswordHasher passwordHasher)
|
||||||
{
|
{
|
||||||
|
@ -24,6 +25,7 @@ public partial class AuthorityManager(
|
||||||
public ICryptographer Cryptographer { get; } = cryptographer;
|
public ICryptographer Cryptographer { get; } = cryptographer;
|
||||||
|
|
||||||
public IUserRepository UserRepository { get; } = userRepository;
|
public IUserRepository UserRepository { get; } = userRepository;
|
||||||
|
public IGroupRepository GroupRepository { get; } = groupRepository;
|
||||||
public IRoleRepository RoleRepository { get; } = roleRepository;
|
public IRoleRepository RoleRepository { get; } = roleRepository;
|
||||||
|
|
||||||
public IPasswordHasher PasswordHasher { get; } = passwordHasher;
|
public IPasswordHasher PasswordHasher { get; } = passwordHasher;
|
||||||
|
|
|
@ -8,43 +8,103 @@ public partial class AuthorityManager
|
||||||
public async Task<AuthorityResult<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
public async Task<AuthorityResult<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
role.Version = GenerateVersion();
|
role.Version = GenerateVersion();
|
||||||
var createResult = await roleRepository.CreateRoleAsync(role, cancellationToken);
|
var createResult = await RoleRepository.CreateRoleAsync(role, cancellationToken);
|
||||||
return AuthorityResult<AuthorityRole>.FromResult(createResult);
|
return AuthorityResult<AuthorityRole>.FromResult(createResult);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Result> DeleteRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
public async Task<Result> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var result = await roleRepository.DeleteRoleAsync(role, cancellationToken);
|
var result = await RoleRepository.DeleteRolesAsync(roles, cancellationToken);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ListResult<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
public async Task<ListResult<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var searchResult = await roleRepository.GetRolesAsync(limit, offset, search, cancellationToken);
|
var searchResult = await RoleRepository.GetRolesAsync(limit, offset, search, cancellationToken);
|
||||||
return searchResult;
|
return searchResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task AddRoleToUserAsync(AuthorityUser user, AuthorityRole role, CancellationToken cancellationToken = default)
|
public async Task AddRolesToUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
/*
|
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
||||||
- Validate User & Role
|
if (!usrValidation.Success)
|
||||||
- Check if role is already in linked to user (if user already has the role, return)
|
{
|
||||||
- Add to UsersRoles table
|
_logger.Error(usrValidation.Exception ?? new Exception("Validation for user failed!"), "Invalid user!");
|
||||||
*/
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task RemoveRoleFromUserAsync(AuthorityRole role, AuthorityUser user, CancellationToken cancellationToken = default)
|
var checkResult = await RoleRepository.HasRolesAsync(user.Id, roles, cancellationToken);
|
||||||
|
if (!checkResult.Success)
|
||||||
{
|
{
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task AddRoleToGroupAsync(AuthorityRole role, AuthorityGroup group, CancellationToken cancellationToken = default)
|
var rolesToAdd = roles;
|
||||||
|
if (checkResult.Count != 0)
|
||||||
{
|
{
|
||||||
|
rolesToAdd = roles.Where(r => !checkResult.Items.Contains(r.Id)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
var addResult = await RoleRepository.AddRolesLinkAsync(rolesToAdd, user.Id, cancellationToken);
|
||||||
|
if (!addResult.Success)
|
||||||
|
{
|
||||||
|
_logger.Error(addResult.Exception ?? new Exception("Adding role to user failed!, No further information available!"),"Failed to add role to user!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task RemoveRolesFromUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
||||||
|
if (!usrValidation.Success)
|
||||||
|
{
|
||||||
|
_logger.Error(usrValidation.Exception ?? new Exception("Validation for user failed!"), "Invalid user!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var checkResult = await RoleRepository.HasRolesAsync(user.Id, roles, cancellationToken);
|
||||||
|
if (!checkResult.Success)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var rolesToRemove = roles;
|
||||||
|
if (checkResult.Count != 0)
|
||||||
|
{
|
||||||
|
rolesToRemove = roles.Where(r => !checkResult.Items.Contains(r.Id)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
var removeResult = await RoleRepository.DeleteRolesLinkAsync(rolesToRemove, user.Id, cancellationToken);
|
||||||
|
if (!removeResult.Success)
|
||||||
|
{
|
||||||
|
_logger.Error(removeResult.Exception ?? new Exception("Removing roles from user failed!"), "Failed to remove roles from user!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task AddRolesToGroupAsync(List<AuthorityRole> roles, AuthorityGroup group, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var checkResult = await RoleRepository.HasRolesAsync(group.Id, roles, cancellationToken);
|
||||||
|
if (!checkResult.Success)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var rolesToAdd = roles;
|
||||||
|
if (checkResult.Count != 0)
|
||||||
|
{
|
||||||
|
rolesToAdd = roles.Where(r => !checkResult.Items.Contains(r.Id)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
var addResult = await RoleRepository.AddRolesLinkAsync(rolesToAdd, group.Id, cancellationToken);
|
||||||
|
if (!addResult.Success)
|
||||||
|
{
|
||||||
|
_logger.Error(addResult.Exception ?? new Exception("Adding roles to group failed!"), "Failed to add roles to group!");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
@ -60,26 +120,19 @@ public partial class AuthorityManager
|
||||||
return ListResult<AuthorityRole>.Failed("Invalid user");
|
return ListResult<AuthorityRole>.Failed("Invalid user");
|
||||||
}
|
}
|
||||||
|
|
||||||
List<AuthorityRole> roles = [];
|
var searchIds = new List<Guid> { user.Id };
|
||||||
var usrRoles = await GetUserRolesAsync(user, cancellationToken);
|
|
||||||
if (usrRoles.Success)
|
|
||||||
{
|
|
||||||
roles.AddRange(usrRoles.Items);
|
|
||||||
}
|
|
||||||
var usrGroups = await GetUserGroupsAsync(user, cancellationToken);
|
var usrGroups = await GetUserGroupsAsync(user, cancellationToken);
|
||||||
if (usrGroups.Success)
|
if (usrGroups.Success)
|
||||||
{
|
{
|
||||||
var groupRolesResult = await GetGroupRolesAsync(usrGroups.Items.Select(g => g.Id).ToList(), cancellationToken);
|
searchIds.AddRange(usrGroups.Items.Select(g => g.Id).ToList());
|
||||||
if (groupRolesResult.Success)
|
|
||||||
{
|
|
||||||
roles.AddRange(groupRolesResult.Items);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return ListResult<AuthorityRole>.Ok(roles, roles.Count);
|
return await RoleRepository.GetLinkedRolesAsync(searchIds, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ListResult<AuthorityRole>> GetGroupRolesAsync(List<Guid> groupIds, CancellationToken cancellationToken = default)
|
public async Task<ListResult<AuthorityRole>> GetGroupRolesAsync(List<Guid> groupIds, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
return ListResult<AuthorityRole>.Failed("Not implemented!");
|
return await RoleRepository.GetLinkedRolesAsync(groupIds, cancellationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -91,7 +91,7 @@ public partial class AuthorityManager
|
||||||
|
|
||||||
public async Task<Result> IsValidUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
public async Task<Result> IsValidUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var usrResult = await userRepository.GetVersionAsync(user, cancellationToken);
|
var usrResult = await UserRepository.GetVersionAsync(user, cancellationToken);
|
||||||
return usrResult;
|
return usrResult;
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,12 +1,8 @@
|
||||||
namespace DotBased.AspNet.Authority.Models.Authority;
|
namespace DotBased.AspNet.Authority.Models.Authority;
|
||||||
|
|
||||||
public class AuthorityAttribute(string attributeKey, Guid bound)
|
public class AuthorityAttribute(string attributeKey, Guid foreignKey)
|
||||||
{
|
{
|
||||||
public AuthorityAttribute() : this(string.Empty, Guid.NewGuid())
|
public Guid ForeignKey { get; set; } = foreignKey;
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
public Guid BoundId { get; set; } = bound;
|
|
||||||
|
|
||||||
public string AttributeKey { get; set; } = attributeKey;
|
public string AttributeKey { get; set; } = attributeKey;
|
||||||
|
|
||||||
|
|
|
@ -9,7 +9,7 @@ public class AuthorityRole()
|
||||||
|
|
||||||
public Guid Id { get; set; } = Guid.NewGuid();
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
|
||||||
public string? Name { get; set; }
|
public string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
public long Version { get; set; }
|
public long Version { get; set; }
|
||||||
|
|
||||||
|
@ -17,5 +17,5 @@ public class AuthorityRole()
|
||||||
|
|
||||||
public IEnumerable<AuthorityAttribute> Attributes { get; set; } = [];
|
public IEnumerable<AuthorityAttribute> Attributes { get; set; } = [];
|
||||||
|
|
||||||
public override string ToString() => Name ?? string.Empty;
|
public override string ToString() => Name;
|
||||||
}
|
}
|
|
@ -23,7 +23,7 @@ public class AuthorityResult<TResultValue> : Result<TResultValue>
|
||||||
public IReadOnlyList<ValidationError>? ValidationErrors { get; }
|
public IReadOnlyList<ValidationError>? ValidationErrors { get; }
|
||||||
|
|
||||||
|
|
||||||
public static AuthorityResult<TResultValue> Ok(TResultValue? value) => new AuthorityResult<TResultValue>(true, value:value);
|
public new static AuthorityResult<TResultValue> Ok(TResultValue? value) => new AuthorityResult<TResultValue>(true, value:value);
|
||||||
|
|
||||||
public static AuthorityResult<TResultValue> Error(string errorMessage, ResultFailReason reason = ResultFailReason.Error) =>
|
public static AuthorityResult<TResultValue> Error(string errorMessage, ResultFailReason reason = ResultFailReason.Error) =>
|
||||||
new AuthorityResult<TResultValue>(false, errorMessage, reason:reason);
|
new AuthorityResult<TResultValue>(false, errorMessage, reason:reason);
|
||||||
|
|
|
@ -6,6 +6,7 @@ public interface IGroupRepository
|
||||||
{
|
{
|
||||||
public Task<ListResult<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
public Task<ListResult<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||||
public Task<Result<AuthorityGroup>> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default);
|
public Task<Result<AuthorityGroup>> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default);
|
||||||
|
public Task<ListResult<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||||
public Task<Result<AuthorityGroup>> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
public Task<Result<AuthorityGroup>> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||||
public Task<Result<AuthorityGroup>> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
public Task<Result<AuthorityGroup>> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||||
public Task<Result> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
public Task<Result> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||||
|
|
|
@ -8,5 +8,17 @@ public interface IRoleRepository
|
||||||
public Task<Result<AuthorityRole>> GetRoleByIdAsync(string id, CancellationToken cancellationToken = default);
|
public Task<Result<AuthorityRole>> GetRoleByIdAsync(string id, CancellationToken cancellationToken = default);
|
||||||
public Task<Result<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
public Task<Result<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
||||||
public Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
public Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
||||||
public Task<Result> DeleteRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
public Task<Result> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default);
|
||||||
|
public Task<Result> AddRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default);
|
||||||
|
public Task<ListResult<AuthorityRole>> GetLinkedRolesAsync(List<Guid> linkIds, CancellationToken cancellationToken = default);
|
||||||
|
public Task<Result> DeleteRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Return the role ids the linkId has.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="linkId"></param>
|
||||||
|
/// <param name="roles"></param>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public Task<ListResult<Guid>> HasRolesAsync(Guid linkId, List<AuthorityRole> roles, CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
|
@ -44,7 +44,7 @@ public class Result<TValue> : Result
|
||||||
public new static Result<TValue> Failed(string message, Exception? exception = null) =>
|
public new static Result<TValue> Failed(string message, Exception? exception = null) =>
|
||||||
new(false, message, default, exception);
|
new(false, message, default, exception);
|
||||||
|
|
||||||
public new static Result<TValue> HandleResult(TValue? value, string failedMessage, Exception? exception = null)
|
public static Result<TValue> HandleResult(TValue? value, string failedMessage, Exception? exception = null)
|
||||||
{
|
{
|
||||||
return value == null ? Failed(failedMessage, exception) : Ok(value);
|
return value == null ? Failed(failedMessage, exception) : Ok(value);
|
||||||
}
|
}
|
||||||
|
@ -56,6 +56,8 @@ public class ListResult<TItem> : Result
|
||||||
{
|
{
|
||||||
Items = items != null ? new List<TItem>(items) : new List<TItem>();
|
Items = items != null ? new List<TItem>(items) : new List<TItem>();
|
||||||
TotalCount = totalCount;
|
TotalCount = totalCount;
|
||||||
|
Limit = limit;
|
||||||
|
Offset = offset;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ListResult(Result bObj) : base(bObj)
|
public ListResult(Result bObj) : base(bObj)
|
||||||
|
@ -85,8 +87,8 @@ public class ListResult<TItem> : Result
|
||||||
public int Offset { get; }
|
public int Offset { get; }
|
||||||
|
|
||||||
public static ListResult<TItem> Ok(IEnumerable<TItem> items, int totalCount = -1, int limit = -1, int offset = -1) =>
|
public static ListResult<TItem> Ok(IEnumerable<TItem> items, int totalCount = -1, int limit = -1, int offset = -1) =>
|
||||||
new(true, string.Empty, totalCount, items);
|
new(true, string.Empty, totalCount, items, limit, offset);
|
||||||
|
|
||||||
public new static ListResult<TItem> Failed(string message, Exception? exception = null) =>
|
public new static ListResult<TItem> Failed(string message, Exception? exception = null) =>
|
||||||
new(false, message, -1, null);
|
new(false, message, -1, null, exception: exception);
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user