mirror of
https://github.com/hmaxnl/DotBased.git
synced 2025-04-19 20:18:13 +02:00
[REFACTOR] Refactored UserRepository to use new monads
This commit is contained in:
parent
21fe08c04f
commit
ba0de46068
|
@ -77,11 +77,8 @@ public class RoleRepository(IDbContextFactory<AuthorityContext> contextFactory,
|
||||||
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rl => roleIds.Contains(rl.RoleId)));
|
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rl => roleIds.Contains(rl.RoleId)));
|
||||||
|
|
||||||
var removedRoles = await context.SaveChangesAsync(cancellationToken);
|
var removedRoles = await context.SaveChangesAsync(cancellationToken);
|
||||||
if (removedRoles == roles.Count)
|
if (removedRoles != 0) return true;
|
||||||
{
|
logger.LogError("Failed to remove roles");
|
||||||
return true;
|
|
||||||
}
|
|
||||||
logger.LogError("Failed to remove all roles, {removedRoles}/{totalRoles} roles removed!", removedRoles, roles.Count);
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -116,12 +113,8 @@ public class RoleRepository(IDbContextFactory<AuthorityContext> contextFactory,
|
||||||
var roleIds = roles.Select(r => r.Id).ToList();
|
var roleIds = roles.Select(r => r.Id).ToList();
|
||||||
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rg => rg.LinkId == linkId && roleIds.Contains(rg.RoleId)));
|
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rg => rg.LinkId == linkId && roleIds.Contains(rg.RoleId)));
|
||||||
var unlinkedRoles = await context.SaveChangesAsync(cancellationToken);
|
var unlinkedRoles = await context.SaveChangesAsync(cancellationToken);
|
||||||
if (unlinkedRoles == roles.Count)
|
if (unlinkedRoles != 0) return true;
|
||||||
{
|
logger.LogError("Failed to remove linked roles");
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.LogError("Failed to remove all linked roles, {unlinkedRoles}/{totalRoles} roles unlinked!", unlinkedRoles, roles.Count);
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,14 +1,14 @@
|
||||||
|
using DotBased.AspNet.Authority.Models;
|
||||||
using DotBased.AspNet.Authority.Models.Authority;
|
using DotBased.AspNet.Authority.Models.Authority;
|
||||||
using DotBased.AspNet.Authority.Repositories;
|
using DotBased.AspNet.Authority.Repositories;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace DotBased.AspNet.Authority.EFCore.Repositories;
|
namespace DotBased.AspNet.Authority.EFCore.Repositories;
|
||||||
|
|
||||||
public class UserRepository(IDbContextFactory<AuthorityContext> contextFactory) : RepositoryBase, IUserRepository
|
public class UserRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<UserRepository> logger) : RepositoryBase, IUserRepository
|
||||||
{
|
{
|
||||||
public async Task<ListResultOld<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
public async Task<QueryItems<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
var query = context.Users.AsQueryable();
|
var query = context.Users.AsQueryable();
|
||||||
|
@ -26,191 +26,122 @@ public class UserRepository(IDbContextFactory<AuthorityContext> contextFactory)
|
||||||
EmailAddress = u.EmailAddress,
|
EmailAddress = u.EmailAddress,
|
||||||
PhoneNumber = u.PhoneNumber
|
PhoneNumber = u.PhoneNumber
|
||||||
}).ToListAsync(cancellationToken: cancellationToken);
|
}).ToListAsync(cancellationToken: cancellationToken);
|
||||||
return ListResultOld<AuthorityUserItem>.Ok(selected, totalCount, limit, offset);
|
return QueryItems<AuthorityUserItem>.Create(selected, totalCount, limit, offset);
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return HandleExceptionListResult<AuthorityUserItem>("Failed to get users.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld<AuthorityUser>> GetAuthorityUserByIdAsync(string id, CancellationToken cancellationToken = default)
|
public async Task<AuthorityUser?> GetAuthorityUserByIdAsync(Guid id, CancellationToken cancellationToken = default)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
if (!Guid.TryParse(id, out var guid))
|
if (id == Guid.Empty)
|
||||||
{
|
{
|
||||||
return ResultOld<AuthorityUser>.Failed("Invalid id!");
|
throw new Exception("Id is required!");
|
||||||
}
|
}
|
||||||
|
|
||||||
var user = await context.Users.Where(u => u.Id == guid).Include(u => u.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
|
return await context.Users.Where(u => u.Id == id).Include(u => u.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
|
||||||
return ResultOld<AuthorityUser>.HandleResult(user, "User not found.");
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return HandleExceptionResult<AuthorityUser>("Failed to get user.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld<AuthorityUser>> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
public async Task<AuthorityUser?> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
if (user.Id == Guid.Empty)
|
if (user.Id == Guid.Empty)
|
||||||
{
|
{
|
||||||
return ResultOld<AuthorityUser>.Failed("Id cannot be empty!");
|
throw new Exception("User id is required!");
|
||||||
}
|
}
|
||||||
var entity = context.Users.Add(user);
|
var entity = context.Users.Add(user);
|
||||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||||
return saveResult <= 0 ? ResultOld<AuthorityUser>.Failed("Failed to create user!") : ResultOld<AuthorityUser>.Ok(entity.Entity);
|
return saveResult != 0 ? entity.Entity : null;
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return HandleExceptionResult<AuthorityUser>("Failed to create user.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld<AuthorityUser>> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
public async Task<AuthorityUser?> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken: cancellationToken);
|
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken: cancellationToken);
|
||||||
if (usr == null)
|
if (usr == null)
|
||||||
{
|
{
|
||||||
return ResultOld<AuthorityUser>.Failed("User not found!");
|
throw new Exception("User not found!");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (usr.Version != user.Version || usr.SecurityVersion != user.SecurityVersion)
|
if (usr.Version != user.Version || usr.SecurityVersion != user.SecurityVersion)
|
||||||
{
|
{
|
||||||
return ResultOld<AuthorityUser>.Failed("Version validation failed!");
|
throw new Exception("User does not have the correct security version!");
|
||||||
}
|
}
|
||||||
|
|
||||||
var entity = context.Users.Update(user);
|
var entity = context.Users.Update(user);
|
||||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||||
return saveResult <= 0 ? ResultOld<AuthorityUser>.Failed("Failed to save updated user!") : ResultOld<AuthorityUser>.Ok(entity.Entity);
|
return saveResult != 0 ? entity.Entity : null;
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return HandleExceptionResult<AuthorityUser>("Failed to update user!", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld> DeleteUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
public async Task<bool> DeleteUsersAsync(List<AuthorityUser> users, CancellationToken cancellationToken = default)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken: cancellationToken);
|
var usrIds = users.Select(u => u.Id);
|
||||||
if (usr == null)
|
|
||||||
{
|
context.Users.RemoveRange(users);
|
||||||
return ResultOld.Failed("User not found!");
|
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rl => usrIds.Contains(rl.LinkId)));
|
||||||
}
|
|
||||||
context.Users.Remove(usr);
|
var removedResult = await context.SaveChangesAsync(cancellationToken);
|
||||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
if (removedResult != 0) return true;
|
||||||
return saveResult <= 0 ? ResultOld.Failed("Failed to delete user!") : ResultOld.Ok();
|
logger.LogError("Failed to delete users");
|
||||||
}
|
return false;
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return HandleException("Failed to delete user!", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld<AuthorityUser>> GetUserByEmailAsync(string email, CancellationToken cancellationToken = default)
|
public async Task<AuthorityUser?> GetUserByEmailAsync(string email, CancellationToken cancellationToken = default)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
var usr = await context.Users.Where(u => u.EmailAddress == email).Include(u => u.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
|
return await context.Users.Where(u => u.EmailAddress == email).Include(u => u.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
|
||||||
return ResultOld<AuthorityUser>.HandleResult(usr, "User not found by given email address.");
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return HandleExceptionResult<AuthorityUser>("An error occured while getting the user.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld> SetVersionAsync(AuthorityUser user, long version, CancellationToken cancellationToken = default)
|
public async Task<bool> SetVersionAsync(AuthorityUser user, long version, CancellationToken cancellationToken = default)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken);
|
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken);
|
||||||
if (usr == null)
|
if (usr == null)
|
||||||
{
|
{
|
||||||
return ResultOld.Failed("Failed to find user with given id!");
|
throw new Exception("User not found!");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (usr.Version != user.Version)
|
if (usr.Version != user.Version)
|
||||||
{
|
{
|
||||||
return ResultOld.Failed("Stored user version doesn't match current user version!");
|
throw new Exception("User does not have the correct security version!");
|
||||||
}
|
}
|
||||||
|
|
||||||
usr.Version = version;
|
usr.Version = version;
|
||||||
context.Users.Update(usr);
|
context.Users.Update(usr);
|
||||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||||
return saveResult <= 0 ? ResultOld.Failed("Failed to update user!") : ResultOld.Ok();
|
return saveResult != 0;
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return HandleException("An error occured while updating the version.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld<long>> GetVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
public async Task<long> GetVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
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);
|
var usrVersion = await context.Users.Where(u => u.Id == user.Id).Select(u => u.Version).FirstOrDefaultAsync(cancellationToken);
|
||||||
return ResultOld<long>.HandleResult(usrVersion, "Failed to get user version!");
|
return usrVersion;
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return HandleExceptionResult<long>("An error occured while getting the user version.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld> SetSecurityVersionAsync(AuthorityUser user, long securityVersion, CancellationToken cancellationToken = default)
|
public async Task<bool> SetSecurityVersionAsync(AuthorityUser user, long securityVersion, CancellationToken cancellationToken = default)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||||
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken);
|
var usr = await context.Users.FirstOrDefaultAsync(u => u.Id == user.Id, cancellationToken);
|
||||||
if (usr == null)
|
if (usr == null)
|
||||||
{
|
{
|
||||||
return ResultOld.Failed("Failed to find user with given id!");
|
throw new Exception("User not found!");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (usr.SecurityVersion != user.SecurityVersion)
|
if (usr.SecurityVersion != user.SecurityVersion)
|
||||||
{
|
{
|
||||||
return ResultOld.Failed("Stored user version doesn't match current user version!");
|
throw new Exception("User does not have the correct security version!");
|
||||||
}
|
}
|
||||||
|
|
||||||
usr.SecurityVersion = securityVersion;
|
usr.SecurityVersion = securityVersion;
|
||||||
context.Users.Update(usr);
|
context.Users.Update(usr);
|
||||||
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
var saveResult = await context.SaveChangesAsync(cancellationToken);
|
||||||
return saveResult <= 0 ? ResultOld.Failed("Failed to update user!") : ResultOld.Ok();
|
return saveResult != 0;
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return HandleException("An error occured while updating the security version.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld<long>> GetSecurityVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
public async Task<long> GetSecurityVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
{
|
||||||
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
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);
|
var usrVersion = await context.Users.Where(u => u.Id == user.Id).Select(u => u.SecurityVersion).FirstOrDefaultAsync(cancellationToken);
|
||||||
return ResultOld<long>.HandleResult(usrVersion, "Failed to get user security version!");
|
return usrVersion;
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return HandleExceptionResult<long>("An error occured while getting the user security version.", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -44,9 +44,9 @@ public partial class AuthorityManager
|
||||||
public async Task<Result> AddRolesToUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
|
public async Task<Result> AddRolesToUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
||||||
if (!usrValidation.Success)
|
if (!usrValidation.IsSuccess)
|
||||||
{
|
{
|
||||||
return ResultError.Fail("Validation for user failed!");
|
return usrValidation;
|
||||||
}
|
}
|
||||||
|
|
||||||
var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(user.Id, roles, cancellationToken);
|
var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(user.Id, roles, cancellationToken);
|
||||||
|
@ -65,9 +65,9 @@ public partial class AuthorityManager
|
||||||
public async Task<Result> RemoveRolesFromUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
|
public async Task<Result> RemoveRolesFromUserAsync(List<AuthorityRole> roles, AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
||||||
if (!usrValidation.Success)
|
if (!usrValidation.IsSuccess)
|
||||||
{
|
{
|
||||||
return ResultError.Fail("Validation for user failed!");
|
return usrValidation;
|
||||||
}
|
}
|
||||||
|
|
||||||
var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(user.Id, roles, cancellationToken);
|
var linkedRoles = await RoleRepository.GetRolesFromLinkAsync(user.Id, roles, cancellationToken);
|
||||||
|
@ -96,19 +96,14 @@ public partial class AuthorityManager
|
||||||
return linkResult ? Result.Success() : ResultError.Fail("Failed to add roles.");
|
return linkResult ? Result.Success() : ResultError.Fail("Failed to add roles.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
public async Task<Result<List<AuthorityRole>>> GetAllUserRolesAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
/// 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<Result<List<AuthorityRole>>> GetUserRolesAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
var usrValidation = await IsValidUserAsync(user, cancellationToken);
|
||||||
if (!usrValidation.Success)
|
if (!usrValidation.IsSuccess)
|
||||||
{
|
{
|
||||||
return ResultError.Fail("Invalid user");
|
return usrValidation.Error ?? ResultError.Fail("User validation failed.");
|
||||||
}
|
}
|
||||||
|
|
||||||
var searchIds = new List<Guid> { user.Id };
|
var searchIds = new List<Guid> { user.Id };
|
||||||
|
|
|
@ -1,7 +1,8 @@
|
||||||
using DotBased.AspNet.Authority.Models;
|
using DotBased.AspNet.Authority.Models;
|
||||||
using DotBased.AspNet.Authority.Models.Authority;
|
using DotBased.AspNet.Authority.Models.Authority;
|
||||||
using DotBased.AspNet.Authority.Models.Validation;
|
using DotBased.AspNet.Authority.Models.Validation;
|
||||||
using ValidationResult = DotBased.AspNet.Authority.Monads.ValidationResult;
|
using DotBased.AspNet.Authority.Monads;
|
||||||
|
using DotBased.Monads;
|
||||||
|
|
||||||
namespace DotBased.AspNet.Authority.Managers;
|
namespace DotBased.AspNet.Authority.Managers;
|
||||||
|
|
||||||
|
@ -35,28 +36,33 @@ public partial class AuthorityManager
|
||||||
return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
|
return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ListResultOld<AuthorityUserItem>> SearchUsersAsync(string query, int maxResults = 20, int offset = 0, CancellationToken cancellationToken = default)
|
public async Task<Result<QueryItems<AuthorityUserItem>>> SearchUsersAsync(string query, int maxResults = 20, int offset = 0, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var result = await UserRepository.GetAuthorityUsersAsync(maxResults, offset, query, cancellationToken);
|
var result = await UserRepository.GetAuthorityUsersAsync(maxResults, offset, query, cancellationToken);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthorityResultOldOld<AuthorityUser>> UpdatePasswordAsync(AuthorityUser user, string password, CancellationToken cancellationToken = default)
|
public async Task<AuthorityResult<AuthorityUser>> UpdatePasswordAsync(AuthorityUser user, string password, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var passwordValidation = await ValidatePasswordAsync(user, password);
|
var passwordValidation = await ValidatePasswordAsync(user, password);
|
||||||
if (!passwordValidation.IsSuccess)
|
if (!passwordValidation.IsSuccess)
|
||||||
{
|
{
|
||||||
return AuthorityResultOldOld<AuthorityUser>.Failed(passwordValidation.ValidationErrors, ResultFailReason.Validation);
|
return passwordValidation.ValidationErrors.ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
user.PasswordHash = await PasswordHasher.HashPasswordAsync(password);
|
user.PasswordHash = await PasswordHasher.HashPasswordAsync(password);
|
||||||
user.SecurityVersion = GenerateVersion();
|
user.SecurityVersion = GenerateVersion();
|
||||||
|
|
||||||
var updateResult = await UserRepository.UpdateUserAsync(user, cancellationToken);
|
var updateResult = await UserRepository.UpdateUserAsync(user, cancellationToken);
|
||||||
return AuthorityResultOldOld<AuthorityUser>.FromResult(updateResult);
|
if (updateResult == null)
|
||||||
|
{
|
||||||
|
return ResultError.Fail("Failed to update user password.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<AuthorityResultOldOld<AuthorityUser>> CreateUserAsync(AuthorityUser userModel, string password, CancellationToken cancellationToken = default)
|
return updateResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AuthorityResult<AuthorityUser>> CreateUserAsync(AuthorityUser userModel, string password, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var userValidation = await ValidateUserAsync(userModel);
|
var userValidation = await ValidateUserAsync(userModel);
|
||||||
var passwordValidation = await ValidatePasswordAsync(userModel, password);
|
var passwordValidation = await ValidatePasswordAsync(userModel, password);
|
||||||
|
@ -65,7 +71,7 @@ public partial class AuthorityManager
|
||||||
List<ValidationError> errors = [];
|
List<ValidationError> errors = [];
|
||||||
errors.AddRange(userValidation.ValidationErrors);
|
errors.AddRange(userValidation.ValidationErrors);
|
||||||
errors.AddRange(passwordValidation.ValidationErrors);
|
errors.AddRange(passwordValidation.ValidationErrors);
|
||||||
return AuthorityResultOldOld<AuthorityUser>.Failed(errors, ResultFailReason.Validation);
|
return errors;
|
||||||
}
|
}
|
||||||
|
|
||||||
userModel.Version = GenerateVersion();
|
userModel.Version = GenerateVersion();
|
||||||
|
@ -74,25 +80,34 @@ public partial class AuthorityManager
|
||||||
userModel.PasswordHash = hashedPassword;
|
userModel.PasswordHash = hashedPassword;
|
||||||
|
|
||||||
var userCreationResult = await UserRepository.CreateUserAsync(userModel, cancellationToken);
|
var userCreationResult = await UserRepository.CreateUserAsync(userModel, cancellationToken);
|
||||||
|
if (userCreationResult == null)
|
||||||
return AuthorityResultOldOld<AuthorityUser>.FromResult(userCreationResult);
|
{
|
||||||
|
return ResultError.Fail("Failed to create user.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld<AuthorityUser>> UpdateUserAsync(AuthorityUser model, CancellationToken cancellationToken = default)
|
return userCreationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<Result<AuthorityUser>> UpdateUserAsync(AuthorityUser model, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var updateResult = await UserRepository.UpdateUserAsync(model, cancellationToken);
|
var updateResult = await UserRepository.UpdateUserAsync(model, cancellationToken);
|
||||||
|
if (updateResult == null)
|
||||||
|
{
|
||||||
|
return ResultError.Fail("Failed to update user.");
|
||||||
|
}
|
||||||
|
|
||||||
return updateResult;
|
return updateResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld> DeleteUserAsync(AuthorityUser model, CancellationToken cancellationToken = default)
|
public async Task<Result> DeleteUserAsync(AuthorityUser model, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var deleteResult = await UserRepository.DeleteUserAsync(model, cancellationToken);
|
var deleteResult = await UserRepository.DeleteUsersAsync([model], cancellationToken);
|
||||||
return deleteResult;
|
return deleteResult ? Result.Success() : ResultError.Fail("Failed to delete user.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<ResultOld> IsValidUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
public async Task<Result> IsValidUserAsync(AuthorityUser user, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var usrResult = await UserRepository.GetVersionAsync(user, cancellationToken);
|
var usrResult = await UserRepository.GetVersionAsync(user, cancellationToken);
|
||||||
return usrResult;
|
return usrResult == 0 ? ResultError.Fail("Invalid user version detected.") : Result.Success();
|
||||||
}
|
}
|
||||||
}
|
}
|
40
DotBased.AspNet.Authority/Monads/AuthorityResult.cs
Normal file
40
DotBased.AspNet.Authority/Monads/AuthorityResult.cs
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -32,10 +32,10 @@ public class ValidationResult : Result
|
||||||
|
|
||||||
public static ValidationResult FromResult(Result result)
|
public static ValidationResult FromResult(Result result)
|
||||||
{
|
{
|
||||||
var authorityResult = result.Match<ValidationResult>(
|
var validationResult = result.Match<ValidationResult>(
|
||||||
() => new ValidationResult(),
|
() => new ValidationResult(),
|
||||||
error => new ValidationResult(error));
|
error => new ValidationResult(error));
|
||||||
return authorityResult;
|
return validationResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
public new static ValidationResult Success() => new();
|
public new static ValidationResult Success() => new();
|
||||||
|
|
|
@ -1,17 +1,18 @@
|
||||||
|
using DotBased.AspNet.Authority.Models;
|
||||||
using DotBased.AspNet.Authority.Models.Authority;
|
using DotBased.AspNet.Authority.Models.Authority;
|
||||||
|
|
||||||
namespace DotBased.AspNet.Authority.Repositories;
|
namespace DotBased.AspNet.Authority.Repositories;
|
||||||
|
|
||||||
public interface IUserRepository
|
public interface IUserRepository
|
||||||
{
|
{
|
||||||
public Task<ListResultOld<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
public Task<QueryItems<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
|
||||||
public Task<ResultOld<AuthorityUser>> GetAuthorityUserByIdAsync(string id, CancellationToken cancellationToken = default);
|
public Task<AuthorityUser?> GetAuthorityUserByIdAsync(Guid id, CancellationToken cancellationToken = default);
|
||||||
public Task<ResultOld<AuthorityUser>> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
public Task<AuthorityUser?> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||||
public Task<ResultOld<AuthorityUser>> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
public Task<AuthorityUser?> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||||
public Task<ResultOld> DeleteUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
public Task<bool> DeleteUsersAsync(List<AuthorityUser> users, CancellationToken cancellationToken = default);
|
||||||
public Task<ResultOld<AuthorityUser>> GetUserByEmailAsync(string email, CancellationToken cancellationToken = default);
|
public Task<AuthorityUser?> GetUserByEmailAsync(string email, CancellationToken cancellationToken = default);
|
||||||
public Task<ResultOld> SetVersionAsync(AuthorityUser user, long version, CancellationToken cancellationToken = default);
|
public Task<bool> SetVersionAsync(AuthorityUser user, long version, CancellationToken cancellationToken = default);
|
||||||
public Task<ResultOld<long>> GetVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
public Task<long> GetVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||||
public Task<ResultOld> SetSecurityVersionAsync(AuthorityUser user, long securityVersion, CancellationToken cancellationToken = default);
|
public Task<bool> SetSecurityVersionAsync(AuthorityUser user, long securityVersion, CancellationToken cancellationToken = default);
|
||||||
public Task<ResultOld<long>> GetSecurityVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
public Task<long> GetSecurityVersionAsync(AuthorityUser user, CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user