mirror of
https://github.com/hmaxnl/DotBased.git
synced 2025-04-19 20:18:13 +02:00
Compare commits
1 Commits
ffa982e91d
...
419b58a97a
Author | SHA1 | Date | |
---|---|---|---|
|
419b58a97a |
|
@ -15,26 +15,26 @@ public class AuthDataCache
|
|||
|
||||
private readonly AuthStateCacheCollection<AuthenticationStateModel, AuthenticationState> _authenticationStateCollection = [];
|
||||
|
||||
public ResultOld PurgeSessionState(string id) => _authenticationStateCollection.Remove(id) ? ResultOld.Ok() : ResultOld.Failed("Failed to purge session state from cache! Or the session was not cached...");
|
||||
public Result PurgeSessionState(string id) => _authenticationStateCollection.Remove(id) ? Result.Ok() : Result.Failed("Failed to purge session state from cache! Or the session was not cached...");
|
||||
|
||||
public void CacheSessionState(AuthenticationStateModel stateModel, AuthenticationState? state = null) => _authenticationStateCollection[stateModel.Id] =
|
||||
new AuthStateCacheNode<AuthenticationStateModel, AuthenticationState>(stateModel, state);
|
||||
|
||||
public ResultOld<Tuple<AuthenticationStateModel, AuthenticationState?>> RequestSessionState(string id)
|
||||
public Result<Tuple<AuthenticationStateModel, AuthenticationState?>> RequestSessionState(string id)
|
||||
{
|
||||
if (!_authenticationStateCollection.TryGetValue(id, out var node))
|
||||
return ResultOld<Tuple<AuthenticationStateModel, AuthenticationState?>>.Failed("No cached object found!");
|
||||
return Result<Tuple<AuthenticationStateModel, AuthenticationState?>>.Failed("No cached object found!");
|
||||
string failedMsg;
|
||||
if (node.StateModel != null)
|
||||
{
|
||||
if (node.IsValidLifespan(_configuration.CachedAuthSessionLifespan))
|
||||
return ResultOld<Tuple<AuthenticationStateModel, AuthenticationState?>>.Ok(new Tuple<AuthenticationStateModel, AuthenticationState?>(node.StateModel, node.State));
|
||||
return Result<Tuple<AuthenticationStateModel, AuthenticationState?>>.Ok(new Tuple<AuthenticationStateModel, AuthenticationState?>(node.StateModel, node.State));
|
||||
failedMsg = $"Session has invalid lifespan, removing entry: [{id}] from cache!";
|
||||
}
|
||||
else
|
||||
failedMsg = $"Returned object is null, removing entry: [{id}] from cache!";
|
||||
_authenticationStateCollection.Remove(id);
|
||||
return ResultOld<Tuple<AuthenticationStateModel, AuthenticationState?>>.Failed(failedMsg);
|
||||
return Result<Tuple<AuthenticationStateModel, AuthenticationState?>>.Failed(failedMsg);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -5,18 +5,18 @@ namespace DotBased.ASP.Auth;
|
|||
|
||||
public interface IAuthDataRepository
|
||||
{
|
||||
public Task<ResultOld> CreateUserAsync(UserModel user);
|
||||
public Task<ResultOld> UpdateUserAsync(UserModel user);
|
||||
public Task<ResultOld> DeleteUserAsync(UserModel user);
|
||||
public Task<ResultOld<UserModel>> GetUserAsync(string id, string email, string username);
|
||||
public Task<ListResultOld<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "");
|
||||
public Task<ResultOld> CreateGroupAsync(GroupModel group);
|
||||
public Task<ResultOld> UpdateGroupAsync(GroupModel group);
|
||||
public Task<ResultOld> DeleteGroupAsync(GroupModel group);
|
||||
public Task<ResultOld<GroupModel>> GetGroupAsync(string id);
|
||||
public Task<ListResultOld<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "");
|
||||
public Task<ResultOld> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<ResultOld> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<ResultOld> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<ResultOld<AuthenticationStateModel>> GetAuthenticationStateAsync(string id);
|
||||
public Task<Result> CreateUserAsync(UserModel user);
|
||||
public Task<Result> UpdateUserAsync(UserModel user);
|
||||
public Task<Result> DeleteUserAsync(UserModel user);
|
||||
public Task<Result<UserModel>> GetUserAsync(string id, string email, string username);
|
||||
public Task<ListResult<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "");
|
||||
public Task<Result> CreateGroupAsync(GroupModel group);
|
||||
public Task<Result> UpdateGroupAsync(GroupModel group);
|
||||
public Task<Result> DeleteGroupAsync(GroupModel group);
|
||||
public Task<Result<GroupModel>> GetGroupAsync(string id);
|
||||
public Task<ListResult<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "");
|
||||
public Task<Result> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<Result> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<Result> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState);
|
||||
public Task<Result<AuthenticationStateModel>> GetAuthenticationStateAsync(string id);
|
||||
}
|
|
@ -3,6 +3,6 @@ namespace DotBased.ASP.Auth;
|
|||
public interface ISessionStateProvider
|
||||
{
|
||||
public const string SessionStateName = "BasedServerSession";
|
||||
public Task<ResultOld<string>> GetSessionStateAsync();
|
||||
public Task<ResultOld> SetSessionStateAsync(string state);
|
||||
public Task<Result<string>> GetSessionStateAsync();
|
||||
public Task<Result> SetSessionStateAsync(string state);
|
||||
}
|
|
@ -10,28 +10,28 @@ namespace DotBased.ASP.Auth;
|
|||
[SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")]
|
||||
public class MemoryAuthDataRepository : IAuthDataRepository
|
||||
{
|
||||
public async Task<ResultOld> CreateUserAsync(UserModel user)
|
||||
public async Task<Result> CreateUserAsync(UserModel user)
|
||||
{
|
||||
if (MemoryData.users.Any(x => x.Id == user.Id || x.Email == user.Email))
|
||||
return ResultOld.Failed("User already exists.");
|
||||
return Result.Failed("User already exists.");
|
||||
MemoryData.users.Add(user);
|
||||
return ResultOld.Ok();
|
||||
return Result.Ok();
|
||||
}
|
||||
|
||||
public async Task<ResultOld> UpdateUserAsync(UserModel user)
|
||||
public async Task<Result> UpdateUserAsync(UserModel user)
|
||||
{
|
||||
if (MemoryData.users.All(x => x.Id != user.Id))
|
||||
return ResultOld.Failed("User does not exist!");
|
||||
return Result.Failed("User does not exist!");
|
||||
|
||||
return ResultOld.Ok();
|
||||
return Result.Ok();
|
||||
}
|
||||
|
||||
public Task<ResultOld> DeleteUserAsync(UserModel user)
|
||||
public Task<Result> DeleteUserAsync(UserModel user)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<ResultOld<UserModel>> GetUserAsync(string id, string email, string username)
|
||||
public async Task<Result<UserModel>> GetUserAsync(string id, string email, string username)
|
||||
{
|
||||
UserModel? userModel = null;
|
||||
if (!id.IsNullOrEmpty())
|
||||
|
@ -40,62 +40,62 @@ public class MemoryAuthDataRepository : IAuthDataRepository
|
|||
userModel = MemoryData.users.FirstOrDefault(u => u.Email.Equals(email, StringComparison.OrdinalIgnoreCase));
|
||||
if (!username.IsNullOrEmpty())
|
||||
userModel = MemoryData.users.FirstOrDefault(u => u.UserName.Equals(username, StringComparison.OrdinalIgnoreCase));
|
||||
return userModel != null ? ResultOld<UserModel>.Ok(userModel) : ResultOld<UserModel>.Failed("No user found!");
|
||||
return userModel != null ? Result<UserModel>.Ok(userModel) : Result<UserModel>.Failed("No user found!");
|
||||
}
|
||||
|
||||
public Task<ListResultOld<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "")
|
||||
public Task<ListResult<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "")
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<ResultOld> CreateGroupAsync(GroupModel group)
|
||||
public Task<Result> CreateGroupAsync(GroupModel group)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<ResultOld> UpdateGroupAsync(GroupModel group)
|
||||
public Task<Result> UpdateGroupAsync(GroupModel group)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<ResultOld> DeleteGroupAsync(GroupModel group)
|
||||
public Task<Result> DeleteGroupAsync(GroupModel group)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<ResultOld<GroupModel>> GetGroupAsync(string id)
|
||||
public Task<Result<GroupModel>> GetGroupAsync(string id)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<ListResultOld<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "")
|
||||
public Task<ListResult<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "")
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<ResultOld> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
public async Task<Result> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
{
|
||||
if (MemoryData.AuthenticationStates.Contains(authenticationState)) return ResultOld.Failed("Item already exists!");
|
||||
if (MemoryData.AuthenticationStates.Contains(authenticationState)) return Result.Failed("Item already exists!");
|
||||
MemoryData.AuthenticationStates.Add(authenticationState);
|
||||
return ResultOld.Ok();
|
||||
return Result.Ok();
|
||||
}
|
||||
|
||||
public Task<ResultOld> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
public Task<Result> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<ResultOld> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
public async Task<Result> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState)
|
||||
{
|
||||
MemoryData.AuthenticationStates.Remove(authenticationState);
|
||||
return ResultOld.Ok();
|
||||
return Result.Ok();
|
||||
}
|
||||
|
||||
public async Task<ResultOld<AuthenticationStateModel>> GetAuthenticationStateAsync(string id)
|
||||
public async Task<Result<AuthenticationStateModel>> GetAuthenticationStateAsync(string id)
|
||||
{
|
||||
var item = MemoryData.AuthenticationStates.FirstOrDefault(x => x.Id == id);
|
||||
if (item == null) return ResultOld<AuthenticationStateModel>.Failed("Could not get the session state!");
|
||||
return ResultOld<AuthenticationStateModel>.Ok(item);
|
||||
if (item == null) return Result<AuthenticationStateModel>.Failed("Could not get the session state!");
|
||||
return Result<AuthenticationStateModel>.Ok(item);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -24,10 +24,10 @@ public class SecurityService
|
|||
private readonly ProtectedLocalStorage _localStorage;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public async Task<ResultOld<AuthenticationState>> GetAuthenticationStateFromSessionAsync(string id)
|
||||
public async Task<Result<AuthenticationState>> GetAuthenticationStateFromSessionAsync(string id)
|
||||
{
|
||||
if (id.IsNullOrEmpty())
|
||||
return ResultOld<AuthenticationState>.Failed("No valid id!");
|
||||
return Result<AuthenticationState>.Failed("No valid id!");
|
||||
AuthenticationStateModel? authStateModel = null;
|
||||
var stateCache = _dataCache.RequestSessionState(id);
|
||||
if (!stateCache.Success || stateCache.Value == null)
|
||||
|
@ -42,16 +42,16 @@ public class SecurityService
|
|||
else
|
||||
{
|
||||
if (stateCache.Value.Item2 != null)
|
||||
return ResultOld<AuthenticationState>.Ok(stateCache.Value.Item2);
|
||||
return Result<AuthenticationState>.Ok(stateCache.Value.Item2);
|
||||
authStateModel = stateCache.Value.Item1;
|
||||
}
|
||||
|
||||
if (authStateModel == null)
|
||||
return ResultOld<AuthenticationState>.Failed("Failed to get auth state!");
|
||||
return Result<AuthenticationState>.Failed("Failed to get auth state!");
|
||||
|
||||
var userResult = await _authDataRepository.GetUserAsync(authStateModel.UserId, string.Empty, string.Empty);
|
||||
if (userResult is not { Success: true, Value: not null })
|
||||
return ResultOld<AuthenticationState>.Failed("Failed to get user from state!");
|
||||
return Result<AuthenticationState>.Failed("Failed to get user from state!");
|
||||
var claims = new List<Claim>()
|
||||
{
|
||||
new(ClaimTypes.Sid, userResult.Value.Id),
|
||||
|
@ -66,56 +66,56 @@ public class SecurityService
|
|||
var claimsIdentity = new ClaimsIdentity(claims, BasedAuthDefaults.AuthenticationScheme);
|
||||
var authState = new AuthenticationState(new ClaimsPrincipal(claimsIdentity));
|
||||
_dataCache.CacheSessionState(authStateModel, authState);
|
||||
return ResultOld<AuthenticationState>.Ok(authState);
|
||||
return Result<AuthenticationState>.Ok(authState);
|
||||
}
|
||||
|
||||
public async Task<ResultOld<AuthenticationStateModel>> LoginAsync(LoginModel login)
|
||||
public async Task<Result<AuthenticationStateModel>> LoginAsync(LoginModel login)
|
||||
{
|
||||
try
|
||||
{
|
||||
UserModel? user = null;
|
||||
ResultOld<UserModel> usrResultOld;
|
||||
Result<UserModel> usrResult;
|
||||
if (!login.UserName.IsNullOrEmpty())
|
||||
{
|
||||
usrResultOld = await _authDataRepository.GetUserAsync(string.Empty, string.Empty, login.UserName);
|
||||
if (usrResultOld is { Success: true, Value: not null })
|
||||
user = usrResultOld.Value;
|
||||
usrResult = await _authDataRepository.GetUserAsync(string.Empty, string.Empty, login.UserName);
|
||||
if (usrResult is { Success: true, Value: not null })
|
||||
user = usrResult.Value;
|
||||
}
|
||||
else if (!login.Email.IsNullOrEmpty())
|
||||
{
|
||||
usrResultOld = await _authDataRepository.GetUserAsync(string.Empty, login.Email, string.Empty);
|
||||
if (usrResultOld is { Success: true, Value: not null })
|
||||
user = usrResultOld.Value;
|
||||
usrResult = await _authDataRepository.GetUserAsync(string.Empty, login.Email, string.Empty);
|
||||
if (usrResult is { Success: true, Value: not null })
|
||||
user = usrResult.Value;
|
||||
}
|
||||
else
|
||||
return ResultOld<AuthenticationStateModel>.Failed("Username & Email is empty, cannot login!");
|
||||
return Result<AuthenticationStateModel>.Failed("Username & Email is empty, cannot login!");
|
||||
|
||||
if (user == null || !usrResultOld.Success)
|
||||
return ResultOld<AuthenticationStateModel>.Failed("No user found!");
|
||||
if (user == null || !usrResult.Success)
|
||||
return Result<AuthenticationStateModel>.Failed("No user found!");
|
||||
|
||||
if (user.PasswordHash != login.Password) //TODO: Hash password and compare
|
||||
return ResultOld<AuthenticationStateModel>.Failed("Login failed, invalid password.");
|
||||
return Result<AuthenticationStateModel>.Failed("Login failed, invalid password.");
|
||||
var state = new AuthenticationStateModel(user);
|
||||
var authResult = await _authDataRepository.CreateAuthenticationStateAsync(state);
|
||||
if (!authResult.Success)
|
||||
return ResultOld<AuthenticationStateModel>.Failed("Failed to store session to database!");
|
||||
return Result<AuthenticationStateModel>.Failed("Failed to store session to database!");
|
||||
_dataCache.CacheSessionState(state);
|
||||
await _localStorage.SetAsync(BasedAuthDefaults.StorageKey, state.Id);
|
||||
return ResultOld<AuthenticationStateModel>.Ok(state);
|
||||
return Result<AuthenticationStateModel>.Ok(state);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, "Failed to login!");
|
||||
return ResultOld<AuthenticationStateModel>.Failed("Login failed, exception thrown!");
|
||||
return Result<AuthenticationStateModel>.Failed("Login failed, exception thrown!");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ResultOld> LogoutAsync(string state)
|
||||
public async Task<Result> LogoutAsync(string state)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (state.IsNullOrEmpty())
|
||||
return ResultOld.Failed($"Argument {nameof(state)} is empty!");
|
||||
return Result.Failed($"Argument {nameof(state)} is empty!");
|
||||
|
||||
var stateResult = await _authDataRepository.GetAuthenticationStateAsync(state);
|
||||
if (!stateResult.Success || stateResult.Value == null)
|
||||
|
@ -131,7 +131,7 @@ public class SecurityService
|
|||
catch (Exception e)
|
||||
{
|
||||
_logger.Error(e, "Failed to logout!");
|
||||
return ResultOld.Failed("Failed to logout, exception thrown!");
|
||||
return Result.Failed("Failed to logout, exception thrown!");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -11,47 +11,54 @@ public class AuthorityContext(DbContextOptions<AuthorityContext> options) : DbCo
|
|||
public DbSet<AuthorityRole> Roles { get; set; }
|
||||
public DbSet<AuthorityUser> Users { get; set; }
|
||||
|
||||
public DbSet<RoleLink> RoleLinks { get; set; }
|
||||
public DbSet<UserGroups> UserGroups { get; set; }
|
||||
public DbSet<RoleGroup> RoleGroup { get; set; }
|
||||
public DbSet<RoleUser> RoleUser { get; set; }
|
||||
public DbSet<UserGroup> UserGroup { get; set; }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<AuthorityAttribute>(attributeEntity =>
|
||||
{
|
||||
attributeEntity.ToTable("authority_attributes");
|
||||
attributeEntity.HasKey(a => new { a.ForeignKey, a.AttributeKey });
|
||||
attributeEntity.HasKey(a => new { a.BoundId, a.AttributeKey });
|
||||
});
|
||||
|
||||
modelBuilder.Entity<AuthorityGroup>(groupEntity =>
|
||||
{
|
||||
groupEntity.ToTable("authority_groups");
|
||||
groupEntity.HasKey(x => x.Id);
|
||||
groupEntity.HasMany(g => g.Attributes).WithOne().HasForeignKey(a => a.ForeignKey).OnDelete(DeleteBehavior.Cascade);
|
||||
groupEntity.HasMany(g => g.Attributes).WithOne().HasForeignKey(a => a.BoundId).OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<AuthorityRole>(roleEntity =>
|
||||
{
|
||||
roleEntity.ToTable("authority_roles");
|
||||
roleEntity.HasKey(x => x.Id);
|
||||
roleEntity.HasMany(r => r.Attributes).WithOne().HasForeignKey(a => a.ForeignKey).OnDelete(DeleteBehavior.Cascade);
|
||||
roleEntity.HasMany(r => r.Attributes).WithOne().HasForeignKey(a => a.BoundId).OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<AuthorityUser>(userEntity =>
|
||||
{
|
||||
userEntity.ToTable("authority_users");
|
||||
userEntity.HasKey(x => x.Id);
|
||||
userEntity.HasMany(u => u.Attributes).WithOne().HasForeignKey(a => a.ForeignKey).OnDelete(DeleteBehavior.Cascade);
|
||||
userEntity.HasMany(u => u.Attributes).WithOne().HasForeignKey(a => a.BoundId).OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<RoleLink>(rgEntity =>
|
||||
modelBuilder.Entity<RoleGroup>(rgEntity =>
|
||||
{
|
||||
rgEntity.ToTable("role_links");
|
||||
rgEntity.HasKey(rg => new { rg.RoleId, rg.LinkId });
|
||||
rgEntity.ToTable("role_group");
|
||||
rgEntity.HasKey(rg => new { rg.RoleId, rg.GroupId });
|
||||
});
|
||||
|
||||
modelBuilder.Entity<UserGroups>(ugEntity =>
|
||||
modelBuilder.Entity<RoleUser>(ruEntity =>
|
||||
{
|
||||
ugEntity.ToTable("user_groups");
|
||||
ruEntity.ToTable("role_user");
|
||||
ruEntity.HasKey(ru => new { ru.RoleId, ru.UserId });
|
||||
});
|
||||
|
||||
modelBuilder.Entity<UserGroup>(ugEntity =>
|
||||
{
|
||||
ugEntity.ToTable("user_group");
|
||||
ugEntity.HasKey(ug => new { ug.UserId, ug.GroupId });
|
||||
});
|
||||
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
namespace DotBased.AspNet.Authority.EFCore.Models;
|
||||
|
||||
public class RoleLink
|
||||
public class RoleGroup
|
||||
{
|
||||
public Guid RoleId { get; set; }
|
||||
public Guid LinkId { get; set; }
|
||||
public Guid GroupId { get; set; }
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
namespace DotBased.AspNet.Authority.EFCore.Models;
|
||||
|
||||
public class UserRoles
|
||||
public class RoleUser
|
||||
{
|
||||
public Guid RoleId { get; set; }
|
||||
public Guid UserId { get; set; }
|
|
@ -1,6 +1,6 @@
|
|||
namespace DotBased.AspNet.Authority.EFCore.Models;
|
||||
|
||||
public class UserGroups
|
||||
public class UserGroup
|
||||
{
|
||||
public Guid UserId { get; set; }
|
||||
public Guid GroupId { get; set; }
|
|
@ -1,86 +1,33 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Repositories;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace DotBased.AspNet.Authority.EFCore.Repositories;
|
||||
|
||||
public class AttributeRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<AttributeRepository> logger) : RepositoryBase, IAttributeRepository
|
||||
public class AttributeRepository : IAttributeRepository
|
||||
{
|
||||
public async Task<QueryItems<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "",
|
||||
public Task<ListResult<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "",
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var query = context.Attributes.AsQueryable();
|
||||
if (!string.IsNullOrEmpty(search))
|
||||
{
|
||||
query = query.Where(a => $"{a.AttributeKey} {a.ForeignKey} {a.AttributeValue}".Contains(search, StringComparison.CurrentCultureIgnoreCase));
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
var total = await query.CountAsync(cancellationToken);
|
||||
var select = await query.OrderBy(a => a.AttributeKey).Skip(offset).Take(limit).Select(a => new AuthorityAttributeItem()
|
||||
public Task<Result<AuthorityAttribute>> GetAttributeByIdAsync(string id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
BoundId = a.ForeignKey,
|
||||
AttributeKey = a.AttributeKey,
|
||||
AttributeValue = a.AttributeValue
|
||||
}).ToListAsync(cancellationToken);
|
||||
return QueryItems<AuthorityAttributeItem>.Create(select, total, limit, offset);
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<AuthorityAttribute?> GetAttributeByKeyAsync(string key, CancellationToken cancellationToken = default)
|
||||
public Task<Result<AuthorityAttribute>> CreateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
return await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == key, cancellationToken);
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<AuthorityAttribute?> CreateAttributeAsync(AuthorityAttribute attribute,
|
||||
CancellationToken cancellationToken = default)
|
||||
public Task<Result<AuthorityAttribute>> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
if (string.IsNullOrWhiteSpace(attribute.AttributeKey) || attribute.ForeignKey == Guid.Empty)
|
||||
{
|
||||
throw new Exception($"Attribute {attribute.AttributeKey} not found");
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
var entry = context.Attributes.Add(attribute);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0 ? entry.Entity : null;
|
||||
}
|
||||
|
||||
public async Task<AuthorityAttribute?> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
|
||||
public Task<Result> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken);
|
||||
if (currentAttribute == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (currentAttribute.Version != attribute.Version)
|
||||
{
|
||||
logger.LogError("Attribute version validation failed for attribute {attribute}", currentAttribute.AttributeKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
var entry = context.Attributes.Update(currentAttribute);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0 ? entry.Entity : null;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken);
|
||||
|
||||
if (currentAttribute == null)
|
||||
{
|
||||
logger.LogError("Attribute not found.");
|
||||
return false;
|
||||
}
|
||||
|
||||
context.Attributes.Remove(currentAttribute);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0;
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
|
@ -1,94 +1,32 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Repositories;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace DotBased.AspNet.Authority.EFCore.Repositories;
|
||||
|
||||
public class GroupRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<GroupRepository> logger) : RepositoryBase, IGroupRepository
|
||||
public class GroupRepository : IGroupRepository
|
||||
{
|
||||
public async Task<QueryItems<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)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var query = context.Groups.AsQueryable();
|
||||
if (!string.IsNullOrWhiteSpace(search))
|
||||
{
|
||||
query = query.Where(g => $"{g.Name} {g.Id}".Contains(search));
|
||||
}
|
||||
var total = await query.CountAsync(cancellationToken);
|
||||
var select = await query.OrderBy(g => g.Name).Skip(offset).Take(limit).Select(g => new AuthorityGroupItem()
|
||||
{
|
||||
Id = g.Id,
|
||||
Name = g.Name
|
||||
}).ToListAsync(cancellationToken);
|
||||
return QueryItems<AuthorityGroupItem>.Create(select, total, limit, offset);
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<AuthorityGroup?> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default)
|
||||
public Task<Result<AuthorityAttribute>> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (!Guid.TryParse(id, out var groupId))
|
||||
{
|
||||
throw new Exception($"Invalid group id: {id}");
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
return await context.Groups.Where(g => g.Id == groupId).Include(g => g.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
|
||||
public Task<Result<AuthorityAttribute>> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<List<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
public Task<Result<AuthorityAttribute>> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
|
||||
{
|
||||
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 userGroups.ToList();
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<AuthorityGroup?> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
|
||||
public Task<Result> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
if (group.Id == Guid.Empty)
|
||||
{
|
||||
throw new Exception($"Invalid group id: {group.Id}");
|
||||
}
|
||||
var entry = context.Groups.Add(group);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0 ? entry.Entity : null;
|
||||
}
|
||||
|
||||
public async Task<AuthorityGroup?> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id ,cancellationToken);
|
||||
if (currentGroup == null)
|
||||
{
|
||||
logger.LogError("Group with id {groupId} not found.", group.Id);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (currentGroup.Version != group.Version)
|
||||
{
|
||||
logger.LogError("Group version validation failed.");
|
||||
return null;
|
||||
}
|
||||
|
||||
var entry = context.Groups.Update(group);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0 ? entry.Entity : null;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id, cancellationToken);
|
||||
if (currentGroup == null)
|
||||
{
|
||||
logger.LogError("Group with id {groupId} not found.", group.Id);
|
||||
return false;
|
||||
}
|
||||
context.Groups.Remove(currentGroup);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0;
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
namespace DotBased.AspNet.Authority.EFCore.Repositories;
|
||||
|
||||
public abstract class RepositoryBase
|
||||
{
|
||||
|
||||
}
|
|
@ -1,126 +1,32 @@
|
|||
using DotBased.AspNet.Authority.EFCore.Models;
|
||||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Repositories;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace DotBased.AspNet.Authority.EFCore.Repositories;
|
||||
|
||||
|
||||
public class RoleRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<RoleRepository> logger) : RepositoryBase, IRoleRepository
|
||||
public class RoleRepository : IRoleRepository
|
||||
{
|
||||
public async Task<QueryItems<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
||||
public Task<ListResult<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var query = context.Roles.AsQueryable();
|
||||
if (!string.IsNullOrWhiteSpace(search))
|
||||
{
|
||||
query = query.Where(r =>
|
||||
$"{r.Name} {r.Id}".Contains(search, StringComparison.CurrentCultureIgnoreCase));
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
var total = await query.CountAsync(cancellationToken);
|
||||
var select = await query.OrderBy(r => r.Name).Skip(offset).Take(limit).Select(r => new AuthorityRoleItem()
|
||||
public Task<Result<AuthorityRole>> GetRoleByIdAsync(string id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Id = r.Id,
|
||||
Name = r.Name
|
||||
}).ToListAsync(cancellationToken: cancellationToken);
|
||||
return QueryItems<AuthorityRoleItem>.Create(select, total, limit, offset);
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<AuthorityRole?> GetRoleByIdAsync(Guid id, CancellationToken cancellationToken = default)
|
||||
public Task<Result<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
||||
{
|
||||
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);
|
||||
return role;
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<AuthorityRole?> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
||||
public Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
if (role.Id == Guid.Empty)
|
||||
{
|
||||
throw new Exception("Role id is required!");
|
||||
}
|
||||
var entity = context.Roles.Add(role);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return saveResult != 0 ? entity.Entity : null;
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public async Task<AuthorityRole?> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
||||
public Task<Result> DeleteRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var currentRole = await context.Roles.FirstOrDefaultAsync(r => r.Id == role.Id, cancellationToken: cancellationToken);
|
||||
if (currentRole == null)
|
||||
{
|
||||
throw new Exception($"Role with id {role.Id} not found!");
|
||||
}
|
||||
|
||||
if (role.Version != currentRole.Version)
|
||||
{
|
||||
throw new Exception("Role version does not match!");
|
||||
}
|
||||
|
||||
var entity = context.Roles.Update(role);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0 ? entity.Entity : null;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var roleIds = roles.Select(r => r.Id).ToList();
|
||||
|
||||
context.Roles.RemoveRange(roles);
|
||||
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rl => roleIds.Contains(rl.RoleId)));
|
||||
|
||||
var removedRoles = await context.SaveChangesAsync(cancellationToken);
|
||||
if (removedRoles != 0) return true;
|
||||
logger.LogError("Failed to remove roles");
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<bool> AddRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
foreach (var role in roles)
|
||||
{
|
||||
context.RoleLinks.Add(new RoleLink { LinkId = linkId, RoleId = role.Id });
|
||||
}
|
||||
var linkedRoles = await context.SaveChangesAsync(cancellationToken);
|
||||
if (linkedRoles == roles.Count)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
logger.LogError("Failed to link all given roles, {linkedRoles}/{totalRoles} roles linked!", linkedRoles, roles.Count);
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<List<AuthorityRole>> GetLinkedRolesAsync(List<Guid> linkIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
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 roleList.DistinctBy(r => r.Id).ToList();
|
||||
}
|
||||
|
||||
public async Task<bool> UnlinkRolesAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
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 unlinkedRoles = await context.SaveChangesAsync(cancellationToken);
|
||||
if (unlinkedRoles != 0) return true;
|
||||
logger.LogError("Failed to remove linked roles");
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<List<Guid>> GetRolesFromLinkAsync(Guid linkId, List<AuthorityRole> roles, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
return await context.RoleLinks.Where(r => r.LinkId == linkId && roles.Any(ar => ar.Id == r.RoleId)).Select(r => r.RoleId).ToListAsync(cancellationToken);
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
|
@ -1,14 +1,14 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Repositories;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace DotBased.AspNet.Authority.EFCore.Repositories;
|
||||
|
||||
public class UserRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<UserRepository> logger) : RepositoryBase, IUserRepository
|
||||
public class UserRepository(IDbContextFactory<AuthorityContext> contextFactory) : IUserRepository
|
||||
{
|
||||
public async Task<QueryItems<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
||||
public async Task<ListResult<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var query = context.Users.AsQueryable();
|
||||
|
@ -18,130 +18,200 @@ public class UserRepository(IDbContextFactory<AuthorityContext> contextFactory,
|
|||
$"{u.Id} {u.Name} {u.UserName} {u.EmailAddress} {u.PhoneNumber}".Contains(search,
|
||||
StringComparison.CurrentCultureIgnoreCase));
|
||||
}
|
||||
|
||||
var totalCount = query.Count();
|
||||
var selected = await query.OrderBy(u => u.UserName).Skip(offset).Take(limit).Select(u => new AuthorityUserItem()
|
||||
var selected = query.Skip(offset).Take(limit).Select(u => new AuthorityUserItem()
|
||||
{
|
||||
Id = u.Id,
|
||||
UserName = u.UserName,
|
||||
EmailAddress = u.EmailAddress,
|
||||
PhoneNumber = u.PhoneNumber
|
||||
}).ToListAsync(cancellationToken: cancellationToken);
|
||||
return QueryItems<AuthorityUserItem>.Create(selected, totalCount, limit, offset);
|
||||
});
|
||||
return ListResult<AuthorityUserItem>.Ok(selected, totalCount, limit, offset);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return ListResult<AuthorityUserItem>.Failed("Failed to get users.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<AuthorityUser?> GetAuthorityUserByIdAsync(Guid id, CancellationToken cancellationToken = default)
|
||||
public async Task<Result<AuthorityUser>> GetAuthorityUserByIdAsync(string id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
if (id == Guid.Empty)
|
||||
if (!Guid.TryParse(id, out var guid))
|
||||
{
|
||||
throw new Exception("Id is required!");
|
||||
return Result<AuthorityUser>.Failed("Invalid id!");
|
||||
}
|
||||
|
||||
return await context.Users.Where(u => u.Id == id).Include(u => u.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
|
||||
var user = await context.Users.FirstOrDefaultAsync(u => u.Id == guid, cancellationToken: cancellationToken);
|
||||
return Result<AuthorityUser>.HandleResult(user, "User not found.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Result<AuthorityUser>.Failed("Failed to get user.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<AuthorityUser?> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
public async Task<Result<AuthorityUser>> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
if (user.Id == Guid.Empty)
|
||||
{
|
||||
throw new Exception("User id is required!");
|
||||
return Result<AuthorityUser>.Failed("Id cannot be empty!");
|
||||
}
|
||||
var entity = context.Users.Add(user);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0 ? entity.Entity : null;
|
||||
return saveResult <= 0 ? Result<AuthorityUser>.Failed("Failed to create user!") : Result<AuthorityUser>.Ok(entity.Entity);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Result<AuthorityUser>.Failed("Failed to create user.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<AuthorityUser?> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
public async Task<Result<AuthorityUser>> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken: cancellationToken);
|
||||
if (usr == null)
|
||||
{
|
||||
throw new Exception("User not found!");
|
||||
return Result<AuthorityUser>.Failed("User not found!");
|
||||
}
|
||||
|
||||
if (usr.Version != user.Version || usr.SecurityVersion != user.SecurityVersion)
|
||||
{
|
||||
throw new Exception("User does not have the correct security version!");
|
||||
return Result<AuthorityUser>.Failed("Version validation failed!");
|
||||
}
|
||||
|
||||
var entity = context.Users.Update(user);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0 ? entity.Entity : null;
|
||||
return saveResult <= 0 ? Result<AuthorityUser>.Failed("Failed to save updated user!") : Result<AuthorityUser>.Ok(entity.Entity);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Result<AuthorityUser>.Failed("Failed to update user!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteUsersAsync(List<AuthorityUser> users, CancellationToken cancellationToken = default)
|
||||
public async Task<Result> DeleteUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var usrIds = users.Select(u => u.Id);
|
||||
|
||||
context.Users.RemoveRange(users);
|
||||
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rl => usrIds.Contains(rl.LinkId)));
|
||||
|
||||
var removedResult = await context.SaveChangesAsync(cancellationToken);
|
||||
if (removedResult != 0) return true;
|
||||
logger.LogError("Failed to delete users");
|
||||
return false;
|
||||
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken: cancellationToken);
|
||||
if (usr == null)
|
||||
{
|
||||
return Result.Failed("User not found!");
|
||||
}
|
||||
context.Users.Remove(usr);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult <= 0 ? Result.Failed("Failed to delete user!") : Result.Ok();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Result.Failed("Failed to delete user!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<AuthorityUser?> GetUserByEmailAsync(string email, CancellationToken cancellationToken = default)
|
||||
public async Task<Result<AuthorityUser>> GetUserByEmailAsync(string email, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
return await context.Users.Where(u => u.EmailAddress == email).Include(u => u.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
|
||||
var usr = await context.Users.FirstOrDefaultAsync(u => u.EmailAddress == email, cancellationToken: cancellationToken);
|
||||
return Result<AuthorityUser>.HandleResult(usr, "User not found by given email address.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Result<AuthorityUser>.Failed("An error occured while getting the user.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SetVersionAsync(AuthorityUser user, long version, CancellationToken cancellationToken = default)
|
||||
public async Task<Result> SetVersionAsync(AuthorityUser user, long version, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken);
|
||||
if (usr == null)
|
||||
{
|
||||
throw new Exception("User not found!");
|
||||
return Result.Failed("Failed to find user with given id!");
|
||||
}
|
||||
|
||||
if (usr.Version != user.Version)
|
||||
{
|
||||
throw new Exception("User does not have the correct security version!");
|
||||
return Result.Failed("Stored user version doesn't match current user version!");
|
||||
}
|
||||
|
||||
usr.Version = version;
|
||||
context.Users.Update(usr);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0;
|
||||
return saveResult <= 0 ? Result.Failed("Failed to update user!") : Result.Ok();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Result.Failed("An error occured while updating the version.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<long> GetVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
public async Task<Result<long>> GetVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var usrVersion = await context.Users.Where(u => u.Id == user.Id).Select(u => u.Version).FirstOrDefaultAsync(cancellationToken);
|
||||
return usrVersion;
|
||||
return Result<long>.HandleResult(usrVersion, "Failed to get user version!");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Result<long>.Failed("An error occured while getting the user version.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SetSecurityVersionAsync(AuthorityUser user, long securityVersion, CancellationToken cancellationToken = default)
|
||||
public async Task<Result> SetSecurityVersionAsync(AuthorityUser user, long securityVersion, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken);
|
||||
if (usr == null)
|
||||
{
|
||||
throw new Exception("User not found!");
|
||||
return Result.Failed("Failed to find user with given id!");
|
||||
}
|
||||
|
||||
if (usr.SecurityVersion != user.SecurityVersion)
|
||||
{
|
||||
throw new Exception("User does not have the correct security version!");
|
||||
return Result.Failed("Stored user version doesn't match current user version!");
|
||||
}
|
||||
|
||||
usr.SecurityVersion = securityVersion;
|
||||
context.Users.Update(usr);
|
||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||
return saveResult != 0;
|
||||
return saveResult <= 0 ? Result.Failed("Failed to update user!") : Result.Ok();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Result.Failed("An error occured while updating the security version.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<long> GetSecurityVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
public async Task<Result<long>> GetSecurityVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
var usrVersion = await context.Users.Where(u => u.Id == user.Id).Select(u => u.SecurityVersion).FirstOrDefaultAsync(cancellationToken);
|
||||
return usrVersion;
|
||||
return Result<long>.HandleResult(usrVersion, "Failed to get user security version!");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Result<long>.Failed("An error occured while getting the user security version.", e);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,19 +1,10 @@
|
|||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.Monads;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Managers;
|
||||
|
||||
public partial class AuthorityManager
|
||||
{
|
||||
public async Task<Result<List<AuthorityGroup>>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await GroupRepository.GetUserGroupsAsync(user, cancellationToken);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return e;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* - Validate User & Group
|
||||
* - Check if user is already in group (if already in group return)
|
||||
* - Add to UsersGroups table
|
||||
*/
|
||||
}
|
|
@ -14,7 +14,6 @@ public partial class AuthorityManager(
|
|||
IServiceProvider services,
|
||||
ICryptographer cryptographer,
|
||||
IUserRepository userRepository,
|
||||
IGroupRepository groupRepository,
|
||||
IRoleRepository roleRepository,
|
||||
IPasswordHasher passwordHasher)
|
||||
{
|
||||
|
@ -25,7 +24,6 @@ public partial class AuthorityManager(
|
|||
public ICryptographer Cryptographer { get; } = cryptographer;
|
||||
|
||||
public IUserRepository UserRepository { get; } = userRepository;
|
||||
public IGroupRepository GroupRepository { get; } = groupRepository;
|
||||
public IRoleRepository RoleRepository { get; } = roleRepository;
|
||||
|
||||
public IPasswordHasher PasswordHasher { get; } = passwordHasher;
|
||||
|
|
|
@ -1,138 +1,65 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.Monads;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Managers;
|
||||
|
||||
public partial class AuthorityManager
|
||||
{
|
||||
public async Task<Result<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
||||
public async Task<Result<AuthorityRole>> CreateRoleAsync(AuthorityRole role, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
role.Version = GenerateVersion();
|
||||
var createResult = await RoleRepository.CreateRoleAsync(role, cancellationToken);
|
||||
if (createResult == null)
|
||||
{
|
||||
return ResultError.Fail("Failed to create new role.");
|
||||
return Result<AuthorityRole>.Failed("Not implemented!");
|
||||
}
|
||||
|
||||
return createResult;
|
||||
public async Task<Result> DeleteRoleAsync(AuthorityRole role, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
return Result.Failed("Not implemented!");
|
||||
}
|
||||
|
||||
public async Task<Result> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default)
|
||||
public async Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
var success = await RoleRepository.DeleteRolesAsync(roles, cancellationToken);
|
||||
return success ? Result.Success() : ResultError.Fail("Failed to delete roles.");
|
||||
return Result<AuthorityRole>.Failed("Not implemented!");
|
||||
}
|
||||
|
||||
public async Task<Result<AuthorityRole>> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default)
|
||||
public async Task<ListResult<AuthorityRole>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken? cancellationToken = null)
|
||||
{
|
||||
var result = await RoleRepository.UpdateRoleAsync(role, cancellationToken);
|
||||
if (result == null)
|
||||
{
|
||||
return ResultError.Fail("Failed to update role.");
|
||||
/*
|
||||
* Search by role name & id
|
||||
* Order by name, created date, creator? (paging)
|
||||
*/
|
||||
return ListResult<AuthorityRole>.Failed("Not implemented!");
|
||||
}
|
||||
|
||||
return result;
|
||||
public async Task AddRoleToUserAsync(AuthorityUser user, AuthorityRole role, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
/*
|
||||
- Validate User & Role
|
||||
- Check if role is already in linked to user (if user already has the role, return)
|
||||
- Add to UsersRoles table
|
||||
*/
|
||||
}
|
||||
|
||||
public async Task<Result<QueryItems<AuthorityRoleItem>>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
||||
public async Task RemoveRoleFromUserAsync(AuthorityRole role, AuthorityUser user, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
var searchResult = await RoleRepository.GetRolesAsync(limit, offset, search, cancellationToken);
|
||||
return searchResult;
|
||||
}
|
||||
|
||||
public async Task<Result> AddRolesToUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
public async Task AddRoleToGroupAsync(AuthorityRole role, AuthorityGroup group, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
||||
if (!usrValidation.IsSuccess)
|
||||
{
|
||||
return usrValidation;
|
||||
}
|
||||
|
||||
var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(user.Id, roles, cancellationToken);
|
||||
|
||||
var rolesToAdd = roles;
|
||||
if (linkedRoles.Count != 0)
|
||||
/// <summary>
|
||||
/// Get all roles (including group roles) that the user has.
|
||||
/// </summary>
|
||||
/// <param name="user">The user to get the roles from</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
public async Task<ListResult<AuthorityRole>> GetUserRolesAsync(AuthorityUser user, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
rolesToAdd = roles.Where(r => !linkedRoles.Contains(r.Id)).ToList();
|
||||
}
|
||||
/*
|
||||
* - Validate user
|
||||
* - Get user groups (id)
|
||||
* - Get roles contained from user
|
||||
* - Get roles contained from groups (if any)
|
||||
* - Order by (for paging)
|
||||
*/
|
||||
|
||||
var addSuccess = await RoleRepository.AddRolesLinkAsync(rolesToAdd, user.Id, cancellationToken);
|
||||
|
||||
return addSuccess ? Result.Success() : ResultError.Fail("Failed to add roles.");
|
||||
}
|
||||
|
||||
public async Task<Result> RemoveRolesFromUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
||||
if (!usrValidation.IsSuccess)
|
||||
{
|
||||
return usrValidation;
|
||||
}
|
||||
|
||||
var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(user.Id, roles, cancellationToken);
|
||||
|
||||
var rolesToRemove = roles;
|
||||
if (linkedRoles.Count != 0)
|
||||
{
|
||||
rolesToRemove = roles.Where(r => !linkedRoles.Contains(r.Id)).ToList();
|
||||
}
|
||||
|
||||
var removeResult = await RoleRepository.UnlinkRolesAsync(rolesToRemove, user.Id, cancellationToken);
|
||||
return removeResult ? Result.Success() : ResultError.Fail("Failed to remove roles.");
|
||||
}
|
||||
|
||||
public async Task<Result> AddRolesToGroupAsync(List<AuthorityRole> roles, AuthorityGroup group, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(group.Id, roles, cancellationToken);
|
||||
|
||||
var rolesToAdd = roles;
|
||||
if (linkedRoles.Count != 0)
|
||||
{
|
||||
rolesToAdd = roles.Where(r => !linkedRoles.Contains(r.Id)).ToList();
|
||||
}
|
||||
|
||||
var linkResult = await RoleRepository.AddRolesLinkAsync(rolesToAdd, group.Id, cancellationToken);
|
||||
return linkResult ? Result.Success() : ResultError.Fail("Failed to add roles.");
|
||||
}
|
||||
|
||||
public async Task<Result<List<AuthorityRole>>> GetAllUserRolesAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
||||
if (!usrValidation.IsSuccess)
|
||||
{
|
||||
return usrValidation.Error ?? ResultError.Fail("User validation failed.");
|
||||
}
|
||||
|
||||
var searchIds = new List<Guid> { user.Id };
|
||||
|
||||
var usrGroups = await GetUserGroupsAsync(user, cancellationToken);
|
||||
if (usrGroups.IsSuccess)
|
||||
{
|
||||
searchIds.AddRange(usrGroups.Value.Select(g => g.Id).ToList());
|
||||
}
|
||||
|
||||
var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(searchIds, cancellationToken);
|
||||
return linkedRolesResult;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return e;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result<List<AuthorityRole>>> GetGroupRolesAsync(List<Guid> groupIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(groupIds, cancellationToken);
|
||||
return linkedRolesResult;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return e;
|
||||
}
|
||||
return ListResult<AuthorityRole>.Failed("Not implemented!");
|
||||
}
|
||||
}
|
|
@ -1,8 +1,6 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.AspNet.Authority.Monads;
|
||||
using DotBased.Monads;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Managers;
|
||||
|
||||
|
@ -14,12 +12,12 @@ public partial class AuthorityManager
|
|||
foreach (var validator in PasswordValidators)
|
||||
{
|
||||
var validatorResult = await validator.ValidatePasswordAsync(this, user, password);
|
||||
if (!validatorResult.IsSuccess)
|
||||
if (!validatorResult.Success)
|
||||
{
|
||||
errors.AddRange(validatorResult.ValidationErrors);
|
||||
errors.AddRange(validatorResult.Errors);
|
||||
}
|
||||
}
|
||||
return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
|
||||
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
|
||||
}
|
||||
|
||||
public async Task<ValidationResult> ValidateUserAsync(AuthorityUser user)
|
||||
|
@ -28,15 +26,15 @@ public partial class AuthorityManager
|
|||
foreach (var userValidator in UserValidators)
|
||||
{
|
||||
var validationResult = await userValidator.ValidateUserAsync(this, user);
|
||||
if (!validationResult.IsSuccess)
|
||||
if (!validationResult.Success)
|
||||
{
|
||||
errors.AddRange(validationResult.ValidationErrors);
|
||||
errors.AddRange(validationResult.Errors);
|
||||
}
|
||||
}
|
||||
return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
|
||||
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
|
||||
}
|
||||
|
||||
public async Task<Result<QueryItems<AuthorityUserItem>>> SearchUsersAsync(string query, int maxResults = 20, int offset = 0, CancellationToken cancellationToken = default)
|
||||
public async Task<ListResult<AuthorityUserItem>> SearchUsersAsync(string query, int maxResults = 20, int offset = 0, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var result = await UserRepository.GetAuthorityUsersAsync(maxResults, offset, query, cancellationToken);
|
||||
return result;
|
||||
|
@ -45,33 +43,30 @@ public partial class AuthorityManager
|
|||
public async Task<AuthorityResult<AuthorityUser>> UpdatePasswordAsync(AuthorityUser user, string password, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var passwordValidation = await ValidatePasswordAsync(user, password);
|
||||
if (!passwordValidation.IsSuccess)
|
||||
if (!passwordValidation.Success)
|
||||
{
|
||||
return passwordValidation.ValidationErrors.ToList();
|
||||
List<ValidationError> errors = [];
|
||||
errors.AddRange(passwordValidation.Errors);
|
||||
return AuthorityResult<AuthorityUser>.Failed(errors, ResultFailReason.Validation);
|
||||
}
|
||||
|
||||
user.PasswordHash = await PasswordHasher.HashPasswordAsync(password);
|
||||
user.SecurityVersion = GenerateVersion();
|
||||
|
||||
var updateResult = await UserRepository.UpdateUserAsync(user, cancellationToken);
|
||||
if (updateResult == null)
|
||||
{
|
||||
return ResultError.Fail("Failed to update user password.");
|
||||
}
|
||||
|
||||
return updateResult;
|
||||
return AuthorityResult<AuthorityUser>.FromResult(updateResult);
|
||||
}
|
||||
|
||||
public async Task<AuthorityResult<AuthorityUser>> CreateUserAsync(AuthorityUser userModel, string password, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var userValidation = await ValidateUserAsync(userModel);
|
||||
var passwordValidation = await ValidatePasswordAsync(userModel, password);
|
||||
if (!userValidation.IsSuccess || !passwordValidation.IsSuccess)
|
||||
if (!userValidation.Success || !passwordValidation.Success)
|
||||
{
|
||||
List<ValidationError> errors = [];
|
||||
errors.AddRange(userValidation.ValidationErrors);
|
||||
errors.AddRange(passwordValidation.ValidationErrors);
|
||||
return errors;
|
||||
errors.AddRange(userValidation.Errors);
|
||||
errors.AddRange(passwordValidation.Errors);
|
||||
return AuthorityResult<AuthorityUser>.Failed(errors, ResultFailReason.Validation);
|
||||
}
|
||||
|
||||
userModel.Version = GenerateVersion();
|
||||
|
@ -80,34 +75,21 @@ public partial class AuthorityManager
|
|||
userModel.PasswordHash = hashedPassword;
|
||||
|
||||
var userCreationResult = await UserRepository.CreateUserAsync(userModel, cancellationToken);
|
||||
if (userCreationResult == null)
|
||||
{
|
||||
return ResultError.Fail("Failed to create user.");
|
||||
}
|
||||
|
||||
return userCreationResult;
|
||||
return AuthorityResult<AuthorityUser>.FromResult(userCreationResult);
|
||||
}
|
||||
|
||||
public async Task<Result<AuthorityUser>> UpdateUserAsync(AuthorityUser model, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var updateResult = await UserRepository.UpdateUserAsync(model, cancellationToken);
|
||||
if (updateResult == null)
|
||||
{
|
||||
return ResultError.Fail("Failed to update user.");
|
||||
}
|
||||
|
||||
return updateResult;
|
||||
}
|
||||
|
||||
public async Task<Result> DeleteUserAsync(AuthorityUser model, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var deleteResult = await UserRepository.DeleteUsersAsync([model], cancellationToken);
|
||||
return deleteResult ? Result.Success() : ResultError.Fail("Failed to delete user.");
|
||||
var deleteResult = await UserRepository.DeleteUserAsync(model, cancellationToken);
|
||||
return deleteResult;
|
||||
}
|
||||
|
||||
public async Task<Result> IsValidUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var usrResult = await UserRepository.GetVersionAsync(user, cancellationToken);
|
||||
return usrResult == 0 ? ResultError.Fail("Invalid user version detected.") : Result.Success();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,8 +1,12 @@
|
|||
namespace DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
public class AuthorityAttribute(string attributeKey, Guid foreignKey)
|
||||
public class AuthorityAttribute(string attributeKey, Guid bound)
|
||||
{
|
||||
public Guid ForeignKey { get; set; } = foreignKey;
|
||||
public AuthorityAttribute() : this(string.Empty, Guid.NewGuid())
|
||||
{
|
||||
}
|
||||
|
||||
public Guid BoundId { get; set; } = bound;
|
||||
|
||||
public string AttributeKey { get; set; } = attributeKey;
|
||||
|
||||
|
|
|
@ -2,9 +2,5 @@ namespace DotBased.AspNet.Authority.Models.Authority;
|
|||
|
||||
public class AuthorityAttributeItem
|
||||
{
|
||||
public Guid BoundId { get; set; }
|
||||
|
||||
public string AttributeKey { get; set; } = string.Empty;
|
||||
|
||||
public string AttributeValue { get; set; } = string.Empty;
|
||||
}
|
|
@ -2,7 +2,5 @@ namespace DotBased.AspNet.Authority.Models.Authority;
|
|||
|
||||
public class AuthorityGroupItem
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
public string? Name { get; set; }
|
||||
}
|
|
@ -9,7 +9,7 @@ public class AuthorityRole()
|
|||
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string? Name { get; set; }
|
||||
|
||||
public long Version { get; set; }
|
||||
|
||||
|
@ -17,5 +17,5 @@ public class AuthorityRole()
|
|||
|
||||
public IEnumerable<AuthorityAttribute> Attributes { get; set; } = [];
|
||||
|
||||
public override string ToString() => Name;
|
||||
public override string ToString() => Name ?? string.Empty;
|
||||
}
|
|
@ -2,7 +2,5 @@ namespace DotBased.AspNet.Authority.Models.Authority;
|
|||
|
||||
public class AuthorityRoleItem
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
public string? Name { get; set; }
|
||||
}
|
41
DotBased.AspNet.Authority/Models/AuthorityResult.cs
Executable file
41
DotBased.AspNet.Authority/Models/AuthorityResult.cs
Executable file
|
@ -0,0 +1,41 @@
|
|||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Models;
|
||||
|
||||
public class AuthorityResult<TResultValue> : Result<TResultValue>
|
||||
{
|
||||
public static AuthorityResult<TResultValue> FromResult(Result<TResultValue> result) => new AuthorityResult<TResultValue>(result);
|
||||
|
||||
public AuthorityResult(Result<TResultValue> result) : base(result)
|
||||
{
|
||||
Reason = ResultFailReason.Unknown;
|
||||
}
|
||||
|
||||
public AuthorityResult(bool success, string errorMessage = "", TResultValue? value = default, ResultFailReason reason = ResultFailReason.None, List<ValidationError>? errors = null) : base(success, errorMessage, value, null)
|
||||
{
|
||||
Success = success;
|
||||
Message = errorMessage;
|
||||
Value = value;
|
||||
Reason = reason;
|
||||
ValidationErrors = errors;
|
||||
}
|
||||
public ResultFailReason Reason { get; }
|
||||
public List<ValidationError>? ValidationErrors { get; }
|
||||
|
||||
|
||||
public static AuthorityResult<TResultValue> Ok(TResultValue? value) => new AuthorityResult<TResultValue>(true, value:value);
|
||||
|
||||
public static AuthorityResult<TResultValue> Error(string errorMessage, ResultFailReason reason = ResultFailReason.Error) =>
|
||||
new AuthorityResult<TResultValue>(false, errorMessage, reason:reason);
|
||||
|
||||
public static AuthorityResult<TResultValue> Failed(List<ValidationError> errors, ResultFailReason reason = ResultFailReason.None)
|
||||
=> new AuthorityResult<TResultValue>(false, errors:errors, reason:reason);
|
||||
}
|
||||
|
||||
public enum ResultFailReason
|
||||
{
|
||||
None,
|
||||
Unknown,
|
||||
Validation,
|
||||
Error
|
||||
}
|
|
@ -1,21 +0,0 @@
|
|||
namespace DotBased.AspNet.Authority.Models;
|
||||
|
||||
public class QueryItems<TItem>
|
||||
{
|
||||
private QueryItems(IEnumerable<TItem> items, int totalCount, int limit, int offset)
|
||||
{
|
||||
Items = items.ToList();
|
||||
TotalCount = totalCount;
|
||||
Limit = limit;
|
||||
Offset = offset;
|
||||
}
|
||||
|
||||
public readonly IReadOnlyCollection<TItem> Items;
|
||||
|
||||
public int Count => Items.Count;
|
||||
public int TotalCount { get; }
|
||||
public int Limit { get; }
|
||||
public int Offset { get; }
|
||||
|
||||
public static QueryItems<TItem> Create(IEnumerable<TItem> items, int totalCount, int limit, int offset) => new(items, totalCount, limit, offset);
|
||||
}
|
21
DotBased.AspNet.Authority/Models/Validation/ValidationResult.cs
Executable file
21
DotBased.AspNet.Authority/Models/Validation/ValidationResult.cs
Executable file
|
@ -0,0 +1,21 @@
|
|||
namespace DotBased.AspNet.Authority.Models.Validation;
|
||||
|
||||
public class ValidationResult
|
||||
{
|
||||
public ValidationResult(bool success, IEnumerable<ValidationError>? errors = null)
|
||||
{
|
||||
if (errors != null)
|
||||
{
|
||||
Errors = errors.ToList();
|
||||
}
|
||||
Success = success;
|
||||
}
|
||||
|
||||
public bool Success { get; }
|
||||
public IReadOnlyList<ValidationError> Errors { get; } = [];
|
||||
|
||||
public static ValidationResult Failed(IEnumerable<ValidationError> errors) => new(false, errors);
|
||||
public static ValidationResult Ok() => new(true);
|
||||
|
||||
public override string ToString() => Success ? "Success" : $"Failed ({Errors.Count} errors)";
|
||||
}
|
|
@ -1,40 +0,0 @@
|
|||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.Monads;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Monads;
|
||||
|
||||
public class AuthorityResult<TResult> : Result<TResult>
|
||||
{
|
||||
protected AuthorityResult(TResult result) : base(result)
|
||||
{
|
||||
}
|
||||
|
||||
protected AuthorityResult(Exception exception) : base(exception)
|
||||
{
|
||||
}
|
||||
|
||||
protected AuthorityResult(ResultError error) : base(error)
|
||||
{
|
||||
}
|
||||
|
||||
protected AuthorityResult(List<ValidationError> validationErrors) : base(ResultError.Fail("Validation failed!"))
|
||||
{
|
||||
_validationErrors = validationErrors;
|
||||
}
|
||||
|
||||
private readonly List<ValidationError> _validationErrors = [];
|
||||
public IReadOnlyList<ValidationError> ValidationErrors => _validationErrors;
|
||||
|
||||
public static implicit operator AuthorityResult<TResult>(TResult result) => new(result);
|
||||
public static implicit operator AuthorityResult<TResult>(Exception exception) => new(exception);
|
||||
public static implicit operator AuthorityResult<TResult>(ResultError error) => new(error);
|
||||
public static implicit operator AuthorityResult<TResult>(List<ValidationError> validationErrors) => new(validationErrors);
|
||||
|
||||
public static AuthorityResult<TResult> FromResult(Result<TResult> result)
|
||||
{
|
||||
var authorityResult = result.Match<AuthorityResult<TResult>>(
|
||||
r => new AuthorityResult<TResult>(r),
|
||||
error => new AuthorityResult<TResult>(error));
|
||||
return authorityResult;
|
||||
}
|
||||
}
|
|
@ -1,43 +0,0 @@
|
|||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.Monads;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Monads;
|
||||
|
||||
public class ValidationResult : Result
|
||||
{
|
||||
private ValidationResult()
|
||||
{
|
||||
}
|
||||
|
||||
private ValidationResult(Exception exception) : base(exception)
|
||||
{
|
||||
}
|
||||
|
||||
private ValidationResult(ResultError error) : base(error)
|
||||
{
|
||||
}
|
||||
|
||||
private ValidationResult(List<ValidationError> validationErrors) : base(ResultError.Fail("Validation failed!"))
|
||||
{
|
||||
_validationErrors = validationErrors;
|
||||
}
|
||||
|
||||
private readonly List<ValidationError> _validationErrors = [];
|
||||
public IReadOnlyList<ValidationError> ValidationErrors => _validationErrors;
|
||||
|
||||
|
||||
public static implicit operator ValidationResult(Exception exception) => new(exception);
|
||||
public static implicit operator ValidationResult(ResultError error) => new(error);
|
||||
public static implicit operator ValidationResult(List<ValidationError> validationErrors) => new(validationErrors);
|
||||
|
||||
public static ValidationResult FromResult(Result result)
|
||||
{
|
||||
var validationResult = result.Match<ValidationResult>(
|
||||
() => new ValidationResult(),
|
||||
error => new ValidationResult(error));
|
||||
return validationResult;
|
||||
}
|
||||
|
||||
public new static ValidationResult Success() => new();
|
||||
public static ValidationResult Fail(List<ValidationError> validationErrors) => new(validationErrors);
|
||||
}
|
|
@ -1,13 +1,12 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IAttributeRepository
|
||||
{
|
||||
public Task<QueryItems<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityAttribute?> GetAttributeByKeyAsync(string id, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityAttribute?> CreateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityAttribute?> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
|
||||
public Task<bool> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
|
||||
public Task<ListResult<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<Result<AuthorityAttribute>> GetAttributeByIdAsync(string id, CancellationToken cancellationToken = default);
|
||||
public Task<Result<AuthorityAttribute>> CreateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
|
||||
public Task<Result<AuthorityAttribute>> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
|
||||
public Task<Result> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
|
||||
}
|
|
@ -1,14 +1,12 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IGroupRepository
|
||||
{
|
||||
public Task<QueryItems<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityGroup?> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default);
|
||||
public Task<List<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityGroup?> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityGroup?> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||
public Task<bool> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||
public Task<ListResult<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<Result<AuthorityAttribute>> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default);
|
||||
public Task<Result<AuthorityAttribute>> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||
public Task<Result<AuthorityAttribute>> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||
public Task<Result> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
|
||||
}
|
|
@ -1,25 +1,12 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IRoleRepository
|
||||
{
|
||||
public Task<QueryItems<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityRole?> GetRoleByIdAsync(Guid id, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityRole?> CreateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityRole?> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
||||
public Task<bool> DeleteRolesAsync(List<AuthorityRole> roles, CancellationToken cancellationToken = default);
|
||||
public Task<bool> AddRolesLinkAsync(List<AuthorityRole> roles, Guid linkId, CancellationToken cancellationToken = default);
|
||||
public Task<List<AuthorityRole>> GetLinkedRolesAsync(List<Guid> linkIds, CancellationToken cancellationToken = default);
|
||||
public Task<bool> UnlinkRolesAsync(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<List<Guid>> GetRolesFromLinkAsync(Guid linkId, List<AuthorityRole> roles, CancellationToken cancellationToken = default);
|
||||
public Task<ListResult<AuthorityRoleItem>> GetRolesAsync(int limit = 20, int offset = 0, string search = "", 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>> UpdateRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
||||
public Task<Result> DeleteRoleAsync(AuthorityRole role, CancellationToken cancellationToken = default);
|
||||
}
|
|
@ -1,18 +1,17 @@
|
|||
using DotBased.AspNet.Authority.Models;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Repositories;
|
||||
|
||||
public interface IUserRepository
|
||||
{
|
||||
public Task<QueryItems<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityUser?> GetAuthorityUserByIdAsync(Guid id, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityUser?> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityUser?> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<bool> DeleteUsersAsync(List<AuthorityUser> users, CancellationToken cancellationToken = default);
|
||||
public Task<AuthorityUser?> GetUserByEmailAsync(string email, CancellationToken cancellationToken = default);
|
||||
public Task<bool> SetVersionAsync(AuthorityUser user, long version, CancellationToken cancellationToken = default);
|
||||
public Task<long> GetVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<bool> SetSecurityVersionAsync(AuthorityUser user, long securityVersion, CancellationToken cancellationToken = default);
|
||||
public Task<long> GetSecurityVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<ListResult<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||
public Task<Result<AuthorityUser>> GetAuthorityUserByIdAsync(string id, CancellationToken cancellationToken = default);
|
||||
public Task<Result<AuthorityUser>> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<Result<AuthorityUser>> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<Result> DeleteUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<Result<AuthorityUser>> GetUserByEmailAsync(string email, CancellationToken cancellationToken = default);
|
||||
public Task<Result> SetVersionAsync(AuthorityUser user, long version, CancellationToken cancellationToken = default);
|
||||
public Task<Result<long>> GetVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
public Task<Result> SetSecurityVersionAsync(AuthorityUser user, long securityVersion, CancellationToken cancellationToken = default);
|
||||
public Task<Result<long>> GetSecurityVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Monads;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Monads;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.AspNet.Authority.Monads;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
||||
|
@ -18,6 +17,6 @@ public class PasswordEqualsValidator : IPasswordValidator
|
|||
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.InUse", "User uses this password already!"));
|
||||
}
|
||||
|
||||
return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
|
||||
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
|
||||
}
|
||||
}
|
|
@ -1,7 +1,6 @@
|
|||
using DotBased.AspNet.Authority.Managers;
|
||||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using DotBased.AspNet.Authority.Monads;
|
||||
using DotBased.Extensions;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
@ -58,7 +57,7 @@ public class PasswordOptionsValidator : IPasswordValidator
|
|||
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.UniqueChars", $"Password must contain at least {passwordOptions.MinimalUniqueChars} unique chars."));
|
||||
}
|
||||
|
||||
return await Task.FromResult(errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success());
|
||||
return await Task.FromResult(errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok());
|
||||
}
|
||||
|
||||
private bool ContainsDigit(string strVal) => strVal.Any(char.IsDigit);
|
||||
|
|
|
@ -2,7 +2,6 @@ using DotBased.AspNet.Authority.Managers;
|
|||
using DotBased.AspNet.Authority.Models.Authority;
|
||||
using DotBased.AspNet.Authority.Models.Options;
|
||||
using DotBased.AspNet.Authority.Models.Validation;
|
||||
using ValidationResult = DotBased.AspNet.Authority.Monads.ValidationResult;
|
||||
|
||||
namespace DotBased.AspNet.Authority.Validators;
|
||||
|
||||
|
@ -54,7 +53,7 @@ public class UserValidator : IUserValidator
|
|||
chars.AddRange(user.UserName.Where(userNameChar => userOptions.UserNameCharacters.Contains(userNameChar)));
|
||||
}
|
||||
|
||||
if (chars.Count <= 0) return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
|
||||
if (chars.Count <= 0) return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
|
||||
var errorCode = "";
|
||||
var description = "";
|
||||
switch (userOptions.UserNameCharacterListType)
|
||||
|
@ -77,6 +76,6 @@ public class UserValidator : IUserValidator
|
|||
errors.Add(new ValidationError(ValidatorId, $"{ValidationBase}.InvalidUserName", "No username given!"));
|
||||
}
|
||||
|
||||
return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
|
||||
return errors.Count > 0 ? ValidationResult.Failed(errors) : ValidationResult.Ok();
|
||||
}
|
||||
}
|
|
@ -1,93 +0,0 @@
|
|||
namespace DotBased.Monads;
|
||||
|
||||
public class Result
|
||||
{
|
||||
protected Result()
|
||||
{
|
||||
IsSuccess = true;
|
||||
}
|
||||
|
||||
protected Result(Exception exception)
|
||||
{
|
||||
IsSuccess = false;
|
||||
Error = ResultError.Error(exception);
|
||||
}
|
||||
|
||||
protected Result(ResultError error)
|
||||
{
|
||||
IsSuccess = false;
|
||||
Error = error;
|
||||
}
|
||||
|
||||
public bool IsSuccess { get; }
|
||||
public ResultError? Error { get; set; }
|
||||
|
||||
public static implicit operator Result(Exception exception) => new(exception);
|
||||
public static implicit operator Result(ResultError error) => new(error);
|
||||
|
||||
public static Result Success() => new();
|
||||
public static Result Fail(ResultError error) => new(error);
|
||||
public static Result Exception(Exception exception) => new(exception);
|
||||
|
||||
|
||||
public TMatch Match<TMatch>(Func<TMatch> success, Func<ResultError, TMatch> failure) => IsSuccess ? success() : failure(Error!);
|
||||
|
||||
public void Match(Action success, Action<ResultError> failure)
|
||||
{
|
||||
if (IsSuccess)
|
||||
{
|
||||
success();
|
||||
}
|
||||
else
|
||||
{
|
||||
failure(Error!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Result<TResult> : Result
|
||||
{
|
||||
protected Result(TResult result)
|
||||
{
|
||||
_result = result;
|
||||
}
|
||||
|
||||
protected Result(Exception exception) : base(exception)
|
||||
{
|
||||
_result = default;
|
||||
}
|
||||
|
||||
protected Result(ResultError error) : base(error)
|
||||
{
|
||||
_result = default;
|
||||
}
|
||||
|
||||
private readonly TResult? _result;
|
||||
public TResult Value => IsSuccess ? _result! : throw new InvalidOperationException("Result is invalid");
|
||||
|
||||
public static implicit operator Result<TResult>(TResult result) => new(result);
|
||||
public static implicit operator Result<TResult>(Exception exception) => new(exception);
|
||||
public static implicit operator Result<TResult>(ResultError error) => new(error);
|
||||
|
||||
public static Result<TResult> Success(TResult result) => new(result);
|
||||
public new static Result<TResult> Fail(ResultError error) => new(error);
|
||||
public new static Result<TResult> Exception(Exception exception) => new(exception);
|
||||
|
||||
public TMatch Match<TMatch>(Func<TResult, TMatch> success, Func<ResultError, TMatch> failure) =>
|
||||
IsSuccess && Value != null ? success(Value) : failure(Error ?? ResultError.Fail("No error and value is null!"));
|
||||
}
|
||||
|
||||
public class ResultError
|
||||
{
|
||||
private ResultError(string description, Exception? exception)
|
||||
{
|
||||
Description = description;
|
||||
Exception = exception;
|
||||
}
|
||||
|
||||
public string Description { get; }
|
||||
public Exception? Exception { get; }
|
||||
|
||||
public static ResultError Fail(string description) => new(description, null);
|
||||
public static ResultError Error(Exception exception, string description = "") => new(description, exception);
|
||||
}
|
92
DotBased/Result.cs
Executable file
92
DotBased/Result.cs
Executable file
|
@ -0,0 +1,92 @@
|
|||
namespace DotBased;
|
||||
|
||||
/// <summary>
|
||||
/// Simple result class for returning a result state or a message and an exception.
|
||||
/// </summary>
|
||||
public class Result
|
||||
{
|
||||
public Result(bool success, string message, Exception? exception)
|
||||
{
|
||||
Success = success;
|
||||
Message = message;
|
||||
Exception = exception;
|
||||
}
|
||||
|
||||
public Result(Result bObj)
|
||||
{
|
||||
Success = bObj.Success;
|
||||
Message = bObj.Message;
|
||||
Exception = bObj.Exception;
|
||||
}
|
||||
|
||||
public bool Success { get; set; }
|
||||
public string Message { get; set; }
|
||||
public Exception? Exception { get; set; }
|
||||
|
||||
public static Result Ok() => new(true, string.Empty, null);
|
||||
public static Result Failed(string message, Exception? exception = null) => new(false, message, exception);
|
||||
}
|
||||
|
||||
public class Result<TValue> : Result
|
||||
{
|
||||
public Result(bool success, string message, TValue? value, Exception? exception) : base(success, message, exception)
|
||||
{
|
||||
Value = value;
|
||||
}
|
||||
public Result(Result bObj) : base(bObj)
|
||||
{
|
||||
|
||||
}
|
||||
public TValue? Value { get; set; }
|
||||
|
||||
public static Result<TValue> Ok(TValue value) => new(true, string.Empty, value, null);
|
||||
|
||||
public new static Result<TValue> Failed(string message, Exception? exception = null) =>
|
||||
new(false, message, default, exception);
|
||||
|
||||
public new static Result<TValue> HandleResult(TValue? value, string failedMessage, Exception? exception = null)
|
||||
{
|
||||
return value == null ? Failed(failedMessage, exception) : Ok(value);
|
||||
}
|
||||
}
|
||||
|
||||
public class ListResult<TItem> : Result
|
||||
{
|
||||
public ListResult(bool success, string message, int totalCount, IEnumerable<TItem>? items, int limit = -1, int offset = -1, Exception? exception = null) : base(success, message, exception)
|
||||
{
|
||||
Items = items != null ? new List<TItem>(items) : new List<TItem>();
|
||||
TotalCount = totalCount;
|
||||
}
|
||||
|
||||
public ListResult(Result bObj) : base(bObj)
|
||||
{
|
||||
Items = new List<TItem>();
|
||||
}
|
||||
|
||||
public readonly IReadOnlyList<TItem> Items;
|
||||
/// <summary>
|
||||
/// The amount of items that this result contains.
|
||||
/// </summary>
|
||||
public int Count => Items.Count;
|
||||
|
||||
/// <summary>
|
||||
/// The total amount of item that is available.
|
||||
/// </summary>
|
||||
public int TotalCount { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The limit this result contains
|
||||
/// </summary>
|
||||
public int Limit { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The offset this result has the items from.
|
||||
/// </summary>
|
||||
public int Offset { get; }
|
||||
|
||||
public static ListResult<TItem> Ok(IEnumerable<TItem> items, int totalCount = -1, int limit = -1, int offset = -1) =>
|
||||
new(true, string.Empty, totalCount, items);
|
||||
|
||||
public new static ListResult<TItem> Failed(string message, Exception? exception = null) =>
|
||||
new(false, message, -1, null);
|
||||
}
|
|
@ -1,5 +1,4 @@
|
|||
using System.Security.Cryptography;
|
||||
using DotBased.Monads;
|
||||
|
||||
namespace DotBased.Utilities;
|
||||
|
||||
|
@ -13,7 +12,7 @@ public static class Cryptography
|
|||
var outputStream = new StringWriter();
|
||||
var parameters = csp.ExportParameters(false);
|
||||
if (parameters.Exponent == null || parameters.Modulus == null)
|
||||
return ResultError.Fail("RSAParameters are empty!");
|
||||
return Result<string>.Failed("RSAParameters are empty!");
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
var writer = new BinaryWriter(stream);
|
||||
|
@ -24,7 +23,7 @@ public static class Cryptography
|
|||
innerWriter.Write((byte)0x30); // SEQUENCE
|
||||
EncodeLength(innerWriter, 13);
|
||||
innerWriter.Write((byte)0x06); // OBJECT IDENTIFIER
|
||||
var rsaEncryptionOid = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };
|
||||
byte[] rsaEncryptionOid = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };
|
||||
EncodeLength(innerWriter, rsaEncryptionOid.Length);
|
||||
innerWriter.Write(rsaEncryptionOid);
|
||||
innerWriter.Write((byte)0x05); // NULL
|
||||
|
@ -45,20 +44,20 @@ public static class Cryptography
|
|||
bitStringWriter.Write(paramsStream.GetBuffer(), 0, paramsLength);
|
||||
}
|
||||
|
||||
var bitStringLength = (int)bitStringStream.Length;
|
||||
int bitStringLength = (int)bitStringStream.Length;
|
||||
EncodeLength(innerWriter, bitStringLength);
|
||||
innerWriter.Write(bitStringStream.GetBuffer(), 0, bitStringLength);
|
||||
}
|
||||
|
||||
var length = (int)innerStream.Length;
|
||||
int length = (int)innerStream.Length;
|
||||
EncodeLength(writer, length);
|
||||
writer.Write(innerStream.GetBuffer(), 0, length);
|
||||
}
|
||||
|
||||
var base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
|
||||
char[] base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
|
||||
// WriteLine terminates with \r\n, we want only \n
|
||||
outputStream.Write("-----BEGIN PUBLIC KEY-----\n");
|
||||
for (var i = 0; i < base64.Length; i += 64)
|
||||
for (int i = 0; i < base64.Length; i += 64)
|
||||
{
|
||||
outputStream.Write(base64, i, Math.Min(64, base64.Length - i));
|
||||
outputStream.Write("\n");
|
||||
|
@ -67,7 +66,7 @@ public static class Cryptography
|
|||
outputStream.Write("-----END PUBLIC KEY-----");
|
||||
}
|
||||
|
||||
return outputStream.ToString();
|
||||
return Result<string>.Ok(outputStream.ToString());
|
||||
}
|
||||
|
||||
private static void EncodeLength(BinaryWriter stream, int length)
|
||||
|
@ -83,15 +82,15 @@ public static class Cryptography
|
|||
default:
|
||||
{
|
||||
// Long form
|
||||
var temp = length;
|
||||
var bytesRequired = 0;
|
||||
int temp = length;
|
||||
int bytesRequired = 0;
|
||||
while (temp > 0)
|
||||
{
|
||||
temp >>= 8;
|
||||
bytesRequired++;
|
||||
}
|
||||
stream.Write((byte)(bytesRequired | 0x80));
|
||||
for (var i = bytesRequired - 1; i >= 0; i--)
|
||||
for (int i = bytesRequired - 1; i >= 0; i--)
|
||||
{
|
||||
stream.Write((byte)(length >> (8 * i) & 0xff));
|
||||
}
|
||||
|
@ -103,7 +102,7 @@ public static class Cryptography
|
|||
private static void EncodeIntegerBigEndian(BinaryWriter stream, byte[] value, bool forceUnsigned = true)
|
||||
{
|
||||
stream.Write((byte)0x02); // INTEGER
|
||||
var prefixZeros = value.TakeWhile(t => t == 0).Count();
|
||||
int prefixZeros = value.TakeWhile(t => t == 0).Count();
|
||||
if (value.Length - prefixZeros == 0)
|
||||
{
|
||||
EncodeLength(stream, 1);
|
||||
|
@ -121,7 +120,7 @@ public static class Cryptography
|
|||
{
|
||||
EncodeLength(stream, value.Length - prefixZeros);
|
||||
}
|
||||
for (var i = prefixZeros; i < value.Length; i++)
|
||||
for (int i = prefixZeros; i < value.Length; i++)
|
||||
{
|
||||
stream.Write(value[i]);
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user