Adds media consumption rules and centralizes authorization role names

This commit is contained in:
BinaryAlley committed 2026-10-23 20:58:52 +03:00
1 parent 3e32068573
commit 8a5cb9116e
56 files changed
+767 -80

No files matched your search

@@ -0,0 +1,12 @@
namespace Lumina.Application.Common.Infrastructure.Authorization;
/// <summary>
/// Class for the names of the authorization roles.
/// </summary>
public static class AuthorizationRoles
{
/// <summary>
/// The role that grants administrative access.
/// </summary>
public const string ADMIN = "Admin";
}
@@ -57,7 +57,7 @@ public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, Res
Guid userId = currentUserId.Value;
// Only admins can see the list of authorization permissions.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
Result<PaginatedResultDto<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -1,8 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -10,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -65,7 +64,7 @@ public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand, Result<Role
Guid userId = currentUserId.Value;
// Only admins can create authorization roles.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
@@ -58,8 +58,8 @@ public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, Resul
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can delete authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
// Only admins can delete authorization roles.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
@@ -69,7 +69,7 @@ public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, Resul
return getExistingRoleResult.Errors;
else if (getExistingRoleResult.Value is null)
return Errors.Authorization.RoleNotFound;
else if (getExistingRoleResult.Value.RoleName == "Admin")
else if (getExistingRoleResult.Value.RoleName == AuthorizationRoles.ADMIN)
return Errors.Authorization.AdminRoleCannotBeDeleted;
// Delete the role and its permissions.
@@ -64,7 +64,7 @@ public class UpdateRoleCommandHandler : ICommandHandler<UpdateRoleCommand, Resul
Guid userId = currentUserId.Value;
// Only admins can update authorization roles.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
@@ -64,7 +64,7 @@ public class GetRolePermissionsQueryHandler : IQueryHandler<GetRolePermissionsQu
Guid userId = currentUserId.Value;
// Only admins can see the list of authorization roles.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
@@ -58,7 +58,7 @@ public class GetRolesQueryHandler : IQueryHandler<GetRolesQuery, Result<IEnumera
Guid userId = currentUserId.Value;
// Only admins can see the list of authorization roles.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
@@ -96,7 +96,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
Guid userId = currentUserId.Value;
// Only admins or users with the permission to manage media libraries can create them.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false) &&
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false) &&
!await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
@@ -72,7 +72,7 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
// Filter the library scans to process.
List<LibraryScanEntity> authorizedLibraryScans = [];
// Admins can see all library scans.
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value);
else // For regular users, only take the library scans that belong to them.
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == userId));
@@ -76,7 +76,7 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
IEnumerable<Result<Library>> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities();
// If the current user is not an admin, they can only scan the libraries that belong to them.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == userId);
List<MediaLibraryScanResponse> responses = [];
@@ -53,23 +53,23 @@ public class GetEnabledLibrariesQueryHandler : IQueryHandler<GetEnabledLibraries
/// </returns>
public async Task<Result<LibraryResponse[]>> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// get the enabled libraries from the repository
// Get the enabled libraries from the repository.
Result<IEnumerable<LibraryEntity>> getEnabledLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false);
if (getEnabledLibrariesResult.IsFailure)
return getEnabledLibrariesResult.Errors;
// admins can see all libraries
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
// Admins can see all libraries.
if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return Result.From(getEnabledLibrariesResult.Value.Select(library => library.ToResponse()).ToArray());
else
{
// for regular users, only take the libraries that belong to them
// For regular users, only take the libraries that belong to them.
LibraryResponse[] userEnabledLibraries = [.. getEnabledLibrariesResult.Value
.Where(library => library.UserId == userId)
.Select(library => library.ToResponse())];
@@ -67,7 +67,7 @@ public class GetLibrariesQueryHandler : IQueryHandler<GetLibrariesQuery, Result<
return getLibrariesResult.Errors;
// Admins can see all libraries.
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return Result.From(getLibrariesResult.Value.Data.Select(library => library.ToResponse()).ToArray());
else
{
@@ -1,14 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
@@ -60,26 +59,25 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler<GetRunningLibrar
/// </returns>
public async Task<Result<IEnumerable<MediaLibraryScanProgressResponse>>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// get the ongoing library scans from the repository
// Get the ongoing library scans from the repository.
Result<IEnumerable<LibraryScanEntity>> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
if (getRunningScansResult.IsFailure)
return getRunningScansResult.Errors;
// filter the library scans by what the user is allowed to see: admins see all libraries, regular users only their own
// Filter the library scans by what the user is allowed to see: admins see all libraries, regular users only their own.
LibraryScanEntity[] userRunningRepositoryLibraryScans = [];
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value];
else
userRunningRepositoryLibraryScans = getRunningScansResult.Value
.Where(libraryScan => libraryScan.UserId == userId).ToArray();
userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)];
// for each of the filtered library scans, get their progress
// For each of the filtered library scans, get their progress.
List<MediaLibraryScanProgressResponse> libraryScanProgresses = [];
IEnumerable<Result<LibraryScan>> userRunningDomainLibraryScans = userRunningRepositoryLibraryScans.ToDomainEntities();
foreach (Result<LibraryScan> userRunningDomainLibraryScan in userRunningDomainLibraryScans)
@@ -62,8 +62,8 @@ public class InstallPluginCommandHandler : ICommandHandler<InstallPluginCommand,
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can install plugins
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
// Only admins can install plugins.
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
Result<Success> installResult = await _pluginInstaller.InstallAsync(command.Archive!, command.FileName!, cancellationToken).ConfigureAwait(false);
@@ -78,7 +78,7 @@ public class AddScheduledJobCommandHandler : ICommandHandler<AddScheduledJobComm
Guid userId = currentUserId.Value;
// Only administrators can schedule jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Create the schedule of the scheduled job, based on its type.
@@ -75,7 +75,7 @@ public class FireScheduledJobCommandHandler : ICommandHandler<FireScheduledJobCo
Guid userId = currentUserId.Value;
// Only administrators can fire scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the scheduled job from the storage medium.
@@ -79,7 +79,7 @@ public class RemoveScheduledJobCommandHandler : ICommandHandler<RemoveScheduledJ
Guid userId = currentUserId.Value;
// Only administrators can remove scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the scheduled job from the storage medium.
@@ -11,7 +11,6 @@ using Lumina.Contracts.Responses.Scheduling;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -76,7 +75,7 @@ public class StartScheduledJobCommandHandler : ICommandHandler<StartScheduledJob
Guid userId = currentUserId.Value;
// Only administrators can start scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the scheduled job from the storage medium.
@@ -80,7 +80,7 @@ public class StopScheduledJobCommandHandler : ICommandHandler<StopScheduledJobCo
Guid userId = currentUserId.Value;
// Only administrators can stop scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the scheduled job from the storage medium.
@@ -61,7 +61,7 @@ public class UpdateSchedulerDisplayPreferencesCommandHandler : ICommandHandler<U
Guid userId = currentUserId.Value;
// Only administrators can use the scheduler page.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Upsert the display preferences of the scheduler page of the current user.
@@ -59,7 +59,7 @@ public class GetScheduledJobHistoryQueryHandler : IQueryHandler<GetScheduledJobH
Guid userId = currentUserId.Value;
// Only administrators can get the history of scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// The lower bound defaults to one day before the upper bound, which defaults to now.
@@ -61,7 +61,7 @@ public class GetScheduledJobsQueryHandler : IQueryHandler<GetScheduledJobsQuery,
Guid userId = currentUserId.Value;
// Only administrators can get the list of scheduled jobs.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the scheduled jobs from the storage medium.
@@ -55,7 +55,7 @@ public class GetSchedulerDisplayPreferencesQueryHandler : IQueryHandler<GetSched
Guid userId = currentUserId.Value;
// Only administrators can view the scheduler page.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// Get the display preferences of the scheduler page of the current user from the repository.
@@ -74,7 +74,7 @@ public class DeleteThemeCommandHandler : ICommandHandler<DeleteThemeCommand, Res
Guid userId = currentUserId.Value;
// Only admins can delete themes.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false);
@@ -1,8 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
@@ -16,8 +16,6 @@ using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.Themes.Management.Commands.InstallTheme;
@@ -71,12 +69,12 @@ public class InstallThemeCommandHandler : ICommandHandler<InstallThemeCommand, R
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// Only admins can install themes.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return Errors.Authorization.NotAuthorized;
// Store the theme pack files on the server, replacing the files of an existing theme with the same manifest id.
Result<ThemeManifestDto> installResult = await _themeService.InstallAsync(command.Archive!, cancellationToken).ConfigureAwait(false);
@@ -71,7 +71,7 @@ public class RestoreThemeCommandHandler : ICommandHandler<RestoreThemeCommand, R
Guid userId = currentUserId.Value;
// Only admins can restore themes.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false);
@@ -67,7 +67,7 @@ public class SetCurrentThemeCommandHandler : ICommandHandler<SetCurrentThemeComm
Guid userId = currentUserId.Value;
// Only admins can change the active theme.
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
if (!await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
Result<ThemeEntity?> getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(command.ThemeId!, cancellationToken).ConfigureAwait(false);
@@ -1,8 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
@@ -12,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Application.Common.Mapping.UsersManagement.Users;
using Lumina.Contracts.Responses.UsersManagement.Users;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -59,7 +58,7 @@ public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, Result<IEnumera
Guid userId = currentUserId.Value;
// Only admins can see the list of users.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
Result<PaginatedResultDto<UserEntity>> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -1,10 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
@@ -12,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -69,7 +67,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
Guid userId = currentUserId.Value;
// Only admins can update user authorizations.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return ApplicationErrors.Authorization.NotAuthorized;
@@ -88,14 +86,14 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
newRole = getRoleResult.Value;
// Check if changing the role of an admin would leave the application without any admin.
if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && newRole.RoleName != "Admin")
if (getUserResult.Value.UserRole?.Role.RoleName == AuthorizationRoles.ADMIN && newRole.RoleName != AuthorizationRoles.ADMIN)
{
// Count how many admins exist, so the last one is never demoted.
Result<PaginatedResultDto<UserEntity>> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync<BaseFilterDto>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (getAllUsersResult.IsFailure)
return getAllUsersResult.Errors;
int adminCount = getAllUsersResult.Value.Data.Count(user => user.UserRole?.Role.RoleName == "Admin");
int adminCount = getAllUsersResult.Value.Data.Count(user => user.UserRole?.Role.RoleName == AuthorizationRoles.ADMIN);
if (adminCount <= 1)
return ApplicationErrors.Authorization.CannotRemoveLastAdmin;
}
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.Errors;
@@ -8,9 +7,9 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -53,21 +52,21 @@ public class GetAuthorizationQueryHandler : IQueryHandler<GetAuthorizationQuery,
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
// An authenticated request must always carry a user identity.
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// first, check if the Id of the user for whom to get the permission list is different from the Id currently making the request
// First, check if the Id of the user for whom to get the permission list is different from the Id currently making the request.
if (userId != query.UserId)
{
// if it is, get the role of the current user, and see if they are Admin
// If it is, get the role of the current user, and see if they are Admin.
Result<UserAuthorizationEntity> getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(userId, cancellationToken).ConfigureAwait(false);
if (getCurrentUserPermissionResult.IsFailure)
return getCurrentUserPermissionResult.Errors;
// if the current user is not an Admin, and the account for whom they request the permissions list is not theirs, deny the request
if (getCurrentUserPermissionResult.Value.Role != "Admin")
// If the current user is not an Admin, and the account for whom they request the permissions list is not theirs, deny the request.
if (getCurrentUserPermissionResult.Value.Role != AuthorizationRoles.ADMIN)
return Errors.Authorization.NotAuthorized;
}
Result<UserAuthorizationEntity> getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false);
@@ -1,8 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -10,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -65,7 +64,7 @@ public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQu
Guid userId = currentUserId.Value;
// Only admins can see the list of authorization permissions.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
@@ -1,8 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
@@ -10,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -64,7 +63,7 @@ public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<Ro
Guid userId = currentUserId.Value;
// Only admins can see the authorization role.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
@@ -7,12 +7,12 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -77,7 +77,7 @@ public class DataSeedService : IDataSeedService
// Create the default authorization roles and add them to the repository.
RoleEntity[] defaultRoles =
[
new() { RoleName = "Admin", CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow }
new() { RoleName = AuthorizationRoles.ADMIN, CreatedBy = userId, CreatedOnUtc = _dateTimeProvider.UtcNow }
];
foreach (RoleEntity role in defaultRoles)
{
@@ -100,7 +100,7 @@ public class DataSeedService : IDataSeedService
public async Task<Result<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken)
{
// Get the admin role.
Result<RoleEntity?> getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false);
Result<RoleEntity?> getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (getAdminRoleResult.IsFailure)
return getAdminRoleResult.Errors;
@@ -143,7 +143,7 @@ public class DataSeedService : IDataSeedService
public async Task<Result<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken)
{
// Get the admin role.
Result<RoleEntity?> getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync("Admin", cancellationToken).ConfigureAwait(false);
Result<RoleEntity?> getAdminRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (getAdminRoleResult.IsFailure)
return getAdminRoleResult.Errors;
@@ -0,0 +1,22 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
/// <summary>
/// Enumeration for the states of a media consumption session.
/// </summary>
public enum ConsumptionStatus
{
/// <summary>
/// The consumption session started and has not ended yet.
/// </summary>
InProgress,
/// <summary>
/// The consumption session reached its explicit completion or the completion threshold of its library.
/// </summary>
Completed,
/// <summary>
/// The consumption session ended before it completed.
/// </summary>
Stopped
}
@@ -0,0 +1,17 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
/// <summary>
/// Enumeration for the kinds of position that a media consumption session can report.
/// </summary>
public enum MediaPositionKind
{
/// <summary>
/// The position is a time offset within the media item.
/// </summary>
TimeOffset,
/// <summary>
/// The position is an opaque locator within the media item, such as a reading location of a book.
/// </summary>
Location
}
@@ -0,0 +1,52 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
/// <summary>
/// Enumeration for the kinds of media items.
/// </summary>
public enum MediaKind
{
/// <summary>
/// No media kind. Used as the default value; it is not a valid kind for a media item.
/// </summary>
None = 0,
/// <summary>
/// A track of a music library.
/// </summary>
MusicTrack,
/// <summary>
/// An episode of a podcast.
/// </summary>
PodcastEpisode,
/// <summary>
/// An audiobook.
/// </summary>
Audiobook,
/// <summary>
/// A movie.
/// </summary>
Movie,
/// <summary>
/// An episode of a TV show.
/// </summary>
TvEpisode,
/// <summary>
/// A book of a written content library.
/// </summary>
Book,
/// <summary>
/// A photo.
/// </summary>
Photo,
/// <summary>
/// A video file.
/// </summary>
Video
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a kind of media whose sessions count when they are completed or reach a minimum consumed duration. I.e.: movies.
/// </summary>
public abstract class DurationThresholdConsumptionRule : MediaConsumptionRule
{
/// <summary>
/// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed.
/// </summary>
public abstract TimeSpan MinimumCountedDuration { get; }
/// <summary>
/// Determines whether a consumption session of this kind of media counts towards statistics.
/// </summary>
/// <param name="status">The status of the consumption session.</param>
/// <param name="consumedDuration">The active duration consumed by the consumption session.</param>
/// <param name="consecutivePagesRead">The number of consecutive pages read in the consumption session. It is ignored, because this kind of media is counted by duration.</param>
/// <returns><see langword="true"/> if the consumption session counts towards statistics, <see langword="false"/> otherwise.</returns>
public override bool Counts(ConsumptionStatus status, TimeSpan consumedDuration, int consecutivePagesRead)
{
return status == ConsumptionStatus.Completed || consumedDuration >= MinimumCountedDuration;
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a kind of media whose sessions count every time, regardless of their duration or progress. I.e.: photos.
/// </summary>
public abstract class EverySessionConsumptionRule : MediaConsumptionRule
{
/// <summary>
/// Determines whether a consumption session of this kind of media counts towards statistics.
/// </summary>
/// <param name="status">The status of the consumption session. It is ignored, because every session of this kind of media counts.</param>
/// <param name="consumedDuration">The active duration consumed by the consumption session. It is ignored, because every session of this kind of media counts.</param>
/// <param name="consecutivePagesRead">The number of consecutive pages read in the consumption session. It is ignored, because every session of this kind of media counts.</param>
/// <returns><see langword="true"/>, because every session of this kind of media counts towards statistics.</returns>
public override bool Counts(ConsumptionStatus status, TimeSpan consumedDuration, int consecutivePagesRead)
{
return true;
}
}
@@ -0,0 +1,83 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a kind of media.
/// </summary>
/// <remarks>
/// The rules are shared by the consumption record aggregate, the resume point aggregate and the statistics read model, so they live in the common
/// folder of the bounded context. Each concrete rule describes the counting behavior and the resumability of one media kind, and the factory returns
/// the rule for a kind so that callers never switch on the media kind themselves.
/// </remarks>
public abstract class MediaConsumptionRule : ValueObject
{
/// <summary>
/// Gets the kind of media that this rule applies to.
/// </summary>
public abstract MediaKind MediaKind { get; }
/// <summary>
/// Gets a value indicating whether the current catalogues support this kind of media.
/// </summary>
public abstract bool IsSupportedByCurrentCatalogues { get; }
/// <summary>
/// Gets the kind of position used to resume this kind of media, if the kind can be resumed.
/// </summary>
public abstract Optional<MediaPositionKind> PositionKind { get; }
/// <summary>
/// Gets a value indicating whether a consumption session of this kind of media can be resumed.
/// </summary>
public bool CanResume => PositionKind.HasValue;
/// <summary>
/// Determines whether a consumption session of this kind of media counts towards statistics.
/// </summary>
/// <param name="status">The status of the consumption session.</param>
/// <param name="consumedDuration">The active duration consumed by the consumption session.</param>
/// <param name="consecutivePagesRead">The number of consecutive pages read in the consumption session.</param>
/// <returns><see langword="true"/> if the consumption session counts towards statistics, <see langword="false"/> otherwise.</returns>
public abstract bool Counts(ConsumptionStatus status, TimeSpan consumedDuration, int consecutivePagesRead);
/// <summary>
/// Gets the consumption rule for <paramref name="mediaKind"/>.
/// </summary>
/// <param name="mediaKind">The kind of media for which to get the consumption rule.</param>
/// <returns>
/// An <see cref="Optional{TValue}"/> containing the consumption rule for <paramref name="mediaKind"/>, or no value when the kind has no rule.
/// </returns>
public static Optional<MediaConsumptionRule> For(MediaKind mediaKind)
{
return mediaKind switch
{
MediaKind.MusicTrack => Optional<MediaConsumptionRule>.Some(new MusicTrackConsumptionRule()),
MediaKind.PodcastEpisode => Optional<MediaConsumptionRule>.Some(new PodcastEpisodeConsumptionRule()),
MediaKind.Audiobook => Optional<MediaConsumptionRule>.Some(new AudiobookConsumptionRule()),
MediaKind.Movie => Optional<MediaConsumptionRule>.Some(new MovieConsumptionRule()),
MediaKind.TvEpisode => Optional<MediaConsumptionRule>.Some(new TvEpisodeConsumptionRule()),
MediaKind.Book => Optional<MediaConsumptionRule>.Some(new BookConsumptionRule()),
MediaKind.Photo => Optional<MediaConsumptionRule>.Some(new PhotoConsumptionRule()),
MediaKind.Video => Optional<MediaConsumptionRule>.Some(new VideoConsumptionRule()),
_ => Optional<MediaConsumptionRule>.None()
};
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object?> GetEqualityComponents()
{
yield return MediaKind;
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a kind of media whose sessions count when they are completed or reach a minimum number of consecutive pages read. I.e.: books.
/// </summary>
public abstract class PageThresholdConsumptionRule : MediaConsumptionRule
{
/// <summary>
/// Gets the minimum number of consecutive pages that a session of this kind of media must read to be counted, when it is not completed.
/// </summary>
public abstract int MinimumConsecutivePages { get; }
/// <summary>
/// Determines whether a consumption session of this kind of media counts towards statistics.
/// </summary>
/// <param name="status">The status of the consumption session.</param>
/// <param name="consumedDuration">The active duration consumed by the consumption session. It is ignored, because this kind of media is counted by pages.</param>
/// <param name="consecutivePagesRead">The number of consecutive pages read in the consumption session.</param>
/// <returns><see langword="true"/> if the consumption session counts towards statistics, <see langword="false"/> otherwise.</returns>
public override bool Counts(ConsumptionStatus status, TimeSpan consumedDuration, int consecutivePagesRead)
{
return status == ConsumptionStatus.Completed || consecutivePagesRead > MinimumConsecutivePages;
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
/// <summary>
/// Value Object for the Id of a media library, duplicated from the LibraryManagement bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class LibraryId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="LibraryId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private LibraryId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryId"/> class.
/// </summary>
/// <returns>The created <see cref="LibraryId"/> instance.</returns>
public static LibraryId CreateUnique()
{
return new LibraryId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="LibraryId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="LibraryId"/> instance.</param>
/// <returns>The created <see cref="LibraryId"/> instance.</returns>
public static LibraryId Create(Guid value)
{
return new LibraryId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
/// <summary>
/// Value Object for the Id of a media item, duplicated from the media library bounded contexts to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class MediaItemId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="MediaItemId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private MediaItemId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="MediaItemId"/> class.
/// </summary>
/// <returns>The created <see cref="MediaItemId"/> instance.</returns>
public static MediaItemId CreateUnique()
{
return new MediaItemId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="MediaItemId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="MediaItemId"/> instance.</param>
/// <returns>The created <see cref="MediaItemId"/> instance.</returns>
public static MediaItemId Create(Guid value)
{
return new MediaItemId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Models.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
/// <summary>
/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled.
/// </summary>
[DebuggerDisplay("{Value}")]
public sealed class UserId : EntityId<Guid>
{
/// <summary>
/// Initializes a new instance of the <see cref="UserId"/> class.
/// </summary>
/// <param name="value">The value representing this object.</param>
private UserId(Guid value) : base(value)
{
}
/// <summary>
/// Creates a new instance of the <see cref="UserId"/> class.
/// </summary>
/// <returns>The created <see cref="UserId"/> instance.</returns>
public static UserId CreateUnique()
{
return new UserId(Guid.NewGuid());
}
/// <summary>
/// Creates a new instance of the <see cref="UserId"/> class, from a pre-existing <paramref name="value"/>.
/// </summary>
/// <param name="value">The value used to create the <see cref="UserId"/> instance.</param>
/// <returns>The created <see cref="UserId"/> instance.</returns>
public static UserId Create(Guid value)
{
return new UserId(value);
}
/// <summary>
/// Gets the list of items that define equality of the object.
/// </summary>
/// <returns>A list of items defining the equality.</returns>
public override IEnumerable<object> GetEqualityComponents()
{
yield return Value;
}
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of an audiobook.
/// </summary>
public sealed class AudiobookConsumptionRule : DurationThresholdConsumptionRule
{
/// <summary>
/// Gets the kind of media that this rule applies to.
/// </summary>
public override MediaKind MediaKind { get; } = MediaKind.Audiobook;
/// <summary>
/// Gets a value indicating whether the current catalogues support this kind of media.
/// </summary>
public override bool IsSupportedByCurrentCatalogues { get; } = false;
/// <summary>
/// Gets the kind of position used to resume this kind of media, if the kind can be resumed.
/// </summary>
public override Optional<MediaPositionKind> PositionKind { get; } = MediaPositionKind.TimeOffset;
/// <summary>
/// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed.
/// </summary>
public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromSeconds(60);
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a book.
/// </summary>
public sealed class BookConsumptionRule : PageThresholdConsumptionRule
{
/// <summary>
/// Gets the kind of media that this rule applies to.
/// </summary>
public override MediaKind MediaKind { get; } = MediaKind.Book;
/// <summary>
/// Gets a value indicating whether the current catalogues support this kind of media.
/// </summary>
public override bool IsSupportedByCurrentCatalogues { get; } = true;
/// <summary>
/// Gets the kind of position used to resume this kind of media, if the kind can be resumed.
/// </summary>
public override Optional<MediaPositionKind> PositionKind { get; } = MediaPositionKind.Location;
/// <summary>
/// Gets the minimum number of consecutive pages that a session of this kind of media must read to be counted, when it is not completed.
/// </summary>
public override int MinimumConsecutivePages { get; } = 5;
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a movie.
/// </summary>
public sealed class MovieConsumptionRule : DurationThresholdConsumptionRule
{
/// <summary>
/// Gets the kind of media that this rule applies to.
/// </summary>
public override MediaKind MediaKind { get; } = MediaKind.Movie;
/// <summary>
/// Gets a value indicating whether the current catalogues support this kind of media.
/// </summary>
public override bool IsSupportedByCurrentCatalogues { get; } = false;
/// <summary>
/// Gets the kind of position used to resume this kind of media, if the kind can be resumed.
/// </summary>
public override Optional<MediaPositionKind> PositionKind { get; } = MediaPositionKind.TimeOffset;
/// <summary>
/// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed.
/// </summary>
public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromMinutes(3);
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a music track.
/// </summary>
public sealed class MusicTrackConsumptionRule : DurationThresholdConsumptionRule
{
/// <summary>
/// Gets the kind of media that this rule applies to.
/// </summary>
public override MediaKind MediaKind { get; } = MediaKind.MusicTrack;
/// <summary>
/// Gets a value indicating whether the current catalogues support this kind of media.
/// </summary>
public override bool IsSupportedByCurrentCatalogues { get; } = true;
/// <summary>
/// Gets the kind of position used to resume this kind of media, if the kind can be resumed.
/// </summary>
public override Optional<MediaPositionKind> PositionKind { get; } = MediaPositionKind.TimeOffset;
/// <summary>
/// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed.
/// </summary>
public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromSeconds(30);
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a photo.
/// </summary>
public sealed class PhotoConsumptionRule : EverySessionConsumptionRule
{
/// <summary>
/// Gets the kind of media that this rule applies to.
/// </summary>
public override MediaKind MediaKind { get; } = MediaKind.Photo;
/// <summary>
/// Gets a value indicating whether the current catalogues support this kind of media.
/// </summary>
public override bool IsSupportedByCurrentCatalogues { get; } = false;
/// <summary>
/// Gets the kind of position used to resume this kind of media. A photo cannot be resumed, so it has no position kind.
/// </summary>
public override Optional<MediaPositionKind> PositionKind { get; } = Optional<MediaPositionKind>.None();
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a podcast episode.
/// </summary>
public sealed class PodcastEpisodeConsumptionRule : DurationThresholdConsumptionRule
{
/// <summary>
/// Gets the kind of media that this rule applies to.
/// </summary>
public override MediaKind MediaKind { get; } = MediaKind.PodcastEpisode;
/// <summary>
/// Gets a value indicating whether the current catalogues support this kind of media.
/// </summary>
public override bool IsSupportedByCurrentCatalogues { get; } = false;
/// <summary>
/// Gets the kind of position used to resume this kind of media, if the kind can be resumed.
/// </summary>
public override Optional<MediaPositionKind> PositionKind { get; } = MediaPositionKind.TimeOffset;
/// <summary>
/// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed.
/// </summary>
public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromSeconds(30);
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a TV show episode.
/// </summary>
public sealed class TvEpisodeConsumptionRule : DurationThresholdConsumptionRule
{
/// <summary>
/// Gets the kind of media that this rule applies to.
/// </summary>
public override MediaKind MediaKind { get; } = MediaKind.TvEpisode;
/// <summary>
/// Gets a value indicating whether the current catalogues support this kind of media.
/// </summary>
public override bool IsSupportedByCurrentCatalogues { get; } = false;
/// <summary>
/// Gets the kind of position used to resume this kind of media, if the kind can be resumed.
/// </summary>
public override Optional<MediaPositionKind> PositionKind { get; } = MediaPositionKind.TimeOffset;
/// <summary>
/// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed.
/// </summary>
public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromMinutes(3);
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
#endregion
namespace Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate.ValueObjects;
/// <summary>
/// Value Object for the consumption rules of a video.
/// </summary>
public sealed class VideoConsumptionRule : DurationThresholdConsumptionRule
{
/// <summary>
/// Gets the kind of media that this rule applies to.
/// </summary>
public override MediaKind MediaKind { get; } = MediaKind.Video;
/// <summary>
/// Gets a value indicating whether the current catalogues support this kind of media.
/// </summary>
public override bool IsSupportedByCurrentCatalogues { get; } = false;
/// <summary>
/// Gets the kind of position used to resume this kind of media, if the kind can be resumed.
/// </summary>
public override Optional<MediaPositionKind> PositionKind { get; } = MediaPositionKind.TimeOffset;
/// <summary>
/// Gets the minimum consumed duration that a session of this kind of media must reach to be counted, when it is not completed.
/// </summary>
public override TimeSpan MinimumCountedDuration { get; } = TimeSpan.FromMinutes(3);
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Domain.Common.Primitives;
@@ -57,7 +58,7 @@ public class LibraryOwnershipPolicy : ILibraryOwnershipPolicy
return false;
}
// Admins can access any media library.
_canAccessAllLibraries = getUserResult.Value.UserRole?.Role.RoleName == "Admin";
_canAccessAllLibraries = getUserResult.Value.UserRole?.Role.RoleName == AuthorizationRoles.ADMIN;
// The user graph already carries the libraries owned by this user, so answering the policy needs no second library read.
_ownedLibraryIds = [.. getUserResult.Value.Libraries.Select(library => library.Id)];
_loadedUserId = userId;
@@ -2,6 +2,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Lumina.Application.Common.Infrastructure.Authorization;
using System;
using System.Security.Claims;
using System.Threading;
@@ -60,6 +61,6 @@ public class ScheduledJobsHub : Hub<IScheduledJobsClient>
{
await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope();
ApplicationAuthorizationService authorizationService = scope.ServiceProvider.GetRequiredService<ApplicationAuthorizationService>();
return await authorizationService.IsInRoleAsync(userId, "Admin", CancellationToken.None).ConfigureAwait(false);
return await authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, CancellationToken.None).ConfigureAwait(false);
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Contracts.Responses.Authorization;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -23,7 +24,7 @@ public class GetRolesEndpointSummary : Summary<GetRolesEndpoint, EmptyRequest>
Response(200, "The authorization roles are returned.",
example: new[] {
new RoleResponse(Id: Guid.NewGuid(), "Admin")
new RoleResponse(Id: Guid.NewGuid(), AuthorizationRoles.ADMIN)
});
Response(401, "Authentication required.", "application/problem+json",
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -33,7 +34,7 @@ public class GetAuthorizationEndpointSummary : Summary<GetAuthorizationEndpoint,
Response(200, "The authorization role and permissions of the account are returned.",
example: new AuthorizationResponse(
UserId: Guid.NewGuid(),
Role: "Admin",
Role: AuthorizationRoles.ADMIN,
Permissions: new HashSet<AuthorizationPermission>() { AuthorizationPermission.CanRegisterUsers, AuthorizationPermission.CanDeleteUsers }
));
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Contracts.Requests.Authorization;
using Lumina.Contracts.Responses.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -33,7 +34,7 @@ public class GetUserRoleEndpointSummary : Summary<GetUserRoleEndpoint, GetUserRo
Response(200, "The authorization role of the user is returned.",
example: new RoleResponse(
Id: Guid.NewGuid(),
RoleName: "Admin"
RoleName: AuthorizationRoles.ADMIN
));
Response(401, "Authentication required.", "application/problem+json",