Implemented user logout and deletion service. Added Auth, Deletion and Logout hook. Restructed controllers
This commit is contained in:
61
Moonlight.Api/Services/UserDeletionService.cs
Normal file
61
Moonlight.Api/Services/UserDeletionService.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Moonlight.Api.Database;
|
||||
using Moonlight.Api.Database.Entities;
|
||||
using Moonlight.Api.Interfaces;
|
||||
|
||||
namespace Moonlight.Api.Services;
|
||||
|
||||
public class UserDeletionService
|
||||
{
|
||||
private readonly DatabaseRepository<User> Repository;
|
||||
private readonly IEnumerable<IUserDeletionHook> Hooks;
|
||||
private readonly IMemoryCache Cache;
|
||||
|
||||
public UserDeletionService(DatabaseRepository<User> repository, IEnumerable<IUserDeletionHook> hooks, IMemoryCache cache)
|
||||
{
|
||||
Repository = repository;
|
||||
Hooks = hooks;
|
||||
Cache = cache;
|
||||
}
|
||||
|
||||
public async Task<UserDeletionValidationResult> ValidateAsync(int userId)
|
||||
{
|
||||
var user = await Repository
|
||||
.Query()
|
||||
.FirstOrDefaultAsync(x => x.Id == userId);
|
||||
|
||||
if(user == null)
|
||||
throw new AggregateException($"User with id {userId} not found");
|
||||
|
||||
var errorMessages = new List<string>();
|
||||
|
||||
foreach (var hook in Hooks)
|
||||
{
|
||||
if (await hook.ValidateAsync(user, errorMessages))
|
||||
continue;
|
||||
|
||||
return new UserDeletionValidationResult(false, errorMessages);
|
||||
}
|
||||
|
||||
return new UserDeletionValidationResult(true, []);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(int userId)
|
||||
{
|
||||
var user = await Repository
|
||||
.Query()
|
||||
.FirstOrDefaultAsync(x => x.Id == userId);
|
||||
|
||||
if(user == null)
|
||||
throw new AggregateException($"User with id {userId} not found");
|
||||
|
||||
foreach (var hook in Hooks)
|
||||
await hook.ExecuteAsync(user);
|
||||
|
||||
await Repository.RemoveAsync(user);
|
||||
Cache.Remove(string.Format(UserAuthService.CacheKeyPattern, userId));
|
||||
}
|
||||
}
|
||||
|
||||
public record UserDeletionValidationResult(bool IsValid, IEnumerable<string> ErrorMessages);
|
||||
Reference in New Issue
Block a user