Updated to latest mooncore version. Cleaned up some crud controllers and replaced DataTable with the new DataGrid component

This commit is contained in:
2025-09-16 12:09:20 +00:00
parent 8e242dc8da
commit 86bec7f2ee
21 changed files with 492 additions and 848 deletions

View File

@@ -1,12 +1,10 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Models;
using MoonCore.Models;
using Moonlight.ApiServer.Database.Entities;
using Moonlight.ApiServer.Mappers;
using Moonlight.ApiServer.Services;
using Moonlight.Shared.Http.Requests.Admin.ApiKeys;
using Moonlight.Shared.Http.Responses.Admin.ApiKeys;
@@ -28,69 +26,82 @@ public class ApiKeysController : Controller
[HttpGet]
[Authorize(Policy = "permissions:admin.apikeys.get")]
public async Task<IPagedData<ApiKeyResponse>> Get([FromQuery] PagedOptions options)
public async Task<ActionResult<ICountedData<ApiKeyResponse>>> Get(
[FromQuery] int startIndex,
[FromQuery] int count,
[FromQuery] string? orderBy,
[FromQuery] string? filter,
[FromQuery] string orderByDir = "asc"
)
{
var count = await ApiKeyRepository.Get().CountAsync();
if (count > 100)
return Problem("You cannot fetch more items than 100 at a time", statusCode: 400);
IQueryable<ApiKey> query = ApiKeyRepository.Get();
var apiKeys = await ApiKeyRepository
.Get()
.OrderBy(x => x.Id)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
query = orderBy switch
{
nameof(ApiKey.Id) => orderByDir == "desc"
? query.OrderByDescending(x => x.Id)
: query.OrderBy(x => x.Id),
nameof(ApiKey.ExpiresAt) => orderByDir == "desc"
? query.OrderByDescending(x => x.ExpiresAt)
: query.OrderBy(x => x.ExpiresAt),
nameof(ApiKey.CreatedAt) => orderByDir == "desc"
? query.OrderByDescending(x => x.CreatedAt)
: query.OrderBy(x => x.CreatedAt),
_ => query.OrderBy(x => x.Id)
};
if (!string.IsNullOrEmpty(filter))
{
query = query.Where(x =>
EF.Functions.ILike(x.Description, $"%{filter}%")
);
}
var totalCount = await query.CountAsync();
var items = await query
.Skip(startIndex)
.Take(count)
.AsNoTracking()
.ProjectToResponse()
.ToArrayAsync();
var mappedApiKey = apiKeys
.Select(x => new ApiKeyResponse()
{
Id = x.Id,
Permissions = x.Permissions,
Description = x.Description,
ExpiresAt = x.ExpiresAt
})
.ToArray();
return new PagedData<ApiKeyResponse>()
return new CountedData<ApiKeyResponse>()
{
CurrentPage = options.Page,
Items = mappedApiKey,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : (count - 1) / options.PageSize
Items = items,
TotalCount = totalCount
};
}
[HttpGet("{id}")]
[HttpGet("{id:int}")]
[Authorize(Policy = "permissions:admin.apikeys.get")]
public async Task<ApiKeyResponse> GetSingle(int id)
public async Task<ActionResult<ApiKeyResponse>> GetSingle(int id)
{
var apiKey = await ApiKeyRepository
.Get()
.AsNoTracking()
.ProjectToResponse()
.FirstOrDefaultAsync(x => x.Id == id);
if (apiKey == null)
throw new HttpApiException("No api key with that id found", 404);
return Problem("No api key with that id found", statusCode: 404);
return new ApiKeyResponse()
{
Id = apiKey.Id,
Permissions = apiKey.Permissions,
Description = apiKey.Description,
ExpiresAt = apiKey.ExpiresAt
};
return apiKey;
}
[HttpPost]
[Authorize(Policy = "permissions:admin.apikeys.create")]
public async Task<CreateApiKeyResponse> Create([FromBody] CreateApiKeyRequest request)
{
var apiKey = new ApiKey()
{
Description = request.Description,
Permissions = request.Permissions,
ExpiresAt = request.ExpiresAt
};
var finalApiKey = await ApiKeyRepository.Add(apiKey);
var apiKey = ApiKeyMapper.ToApiKey(request);
var finalApiKey = await ApiKeyRepository.AddAsync(apiKey);
var response = new CreateApiKeyResponse
{
@@ -104,41 +115,36 @@ public class ApiKeysController : Controller
return response;
}
[HttpPatch("{id}")]
[HttpPatch("{id:int}")]
[Authorize(Policy = "permissions:admin.apikeys.update")]
public async Task<ApiKeyResponse> Update([FromRoute] int id, [FromBody] UpdateApiKeyRequest request)
public async Task<ActionResult<ApiKeyResponse>> Update([FromRoute] int id, [FromBody] UpdateApiKeyRequest request)
{
var apiKey = await ApiKeyRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id);
if (apiKey == null)
throw new HttpApiException("No api key with that id found", 404);
return Problem("No api key with that id found", statusCode: 404);
apiKey.Description = request.Description;
ApiKeyMapper.Merge(apiKey, request);
await ApiKeyRepository.Update(apiKey);
await ApiKeyRepository.UpdateAsync(apiKey);
return new ApiKeyResponse()
{
Id = apiKey.Id,
Description = apiKey.Description,
Permissions = apiKey.Permissions,
ExpiresAt = apiKey.ExpiresAt
};
return ApiKeyMapper.ToResponse(apiKey);
}
[HttpDelete("{id}")]
[HttpDelete("{id:int}")]
[Authorize(Policy = "permissions:admin.apikeys.delete")]
public async Task Delete([FromRoute] int id)
public async Task<ActionResult> Delete([FromRoute] int id)
{
var apiKey = await ApiKeyRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id);
if (apiKey == null)
throw new HttpApiException("No api key with that id found", 404);
return Problem("No api key with that id found", statusCode: 404);
await ApiKeyRepository.Remove(apiKey);
await ApiKeyRepository.RemoveAsync(apiKey);
return NoContent();
}
}

View File

@@ -26,65 +26,96 @@ public class ThemesController : Controller
[HttpGet]
[Authorize(Policy = "permissions:admin.system.customisation.themes.read")]
public async Task<PagedData<ThemeResponse>> Get([FromQuery] PagedOptions options)
public async Task<ActionResult<ICountedData<ThemeResponse>>> Get(
[FromQuery] int startIndex,
[FromQuery] int count,
[FromQuery] string? orderBy,
[FromQuery] string? filter,
[FromQuery] string orderByDir = "asc"
)
{
var count = await ThemeRepository.Get().CountAsync();
if (count > 100)
return Problem("You cannot fetch more items than 100 at a time", statusCode: 400);
var items = await ThemeRepository
.Get()
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
.ToArrayAsync();
var mappedItems = items
.Select(ThemeMapper.ToResponse)
.ToArray();
return new PagedData<ThemeResponse>()
IQueryable<Theme> query = ThemeRepository.Get();
query = orderBy switch
{
CurrentPage = options.Page,
Items = mappedItems,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : (count - 1) / options.PageSize
nameof(Theme.Id) => orderByDir == "desc"
? query.OrderByDescending(x => x.Id)
: query.OrderBy(x => x.Id),
nameof(Theme.Name) => orderByDir == "desc"
? query.OrderByDescending(x => x.Name)
: query.OrderBy(x => x.Name),
nameof(Theme.Version) => orderByDir == "desc"
? query.OrderByDescending(x => x.Version)
: query.OrderBy(x => x.Version),
_ => query.OrderBy(x => x.Id)
};
if (!string.IsNullOrEmpty(filter))
{
query = query.Where(x =>
EF.Functions.ILike(x.Name, $"%{filter}%")
);
}
var totalCount = await query.CountAsync();
var items = await query
.Skip(startIndex)
.Take(count)
.AsNoTracking()
.ProjectToResponse()
.ToArrayAsync();
return new CountedData<ThemeResponse>()
{
Items = items,
TotalCount = totalCount
};
}
[HttpGet("{id:int}")]
[Authorize(Policy = "permissions:admin.system.customisation.themes.read")]
public async Task<ThemeResponse> GetSingle([FromRoute] int id)
public async Task<ActionResult<ThemeResponse>> GetSingle([FromRoute] int id)
{
var theme = await ThemeRepository
.Get()
.AsNoTracking()
.ProjectToResponse()
.FirstOrDefaultAsync(t => t.Id == id);
if (theme == null)
throw new HttpApiException("Theme with this id not found", 404);
return ThemeMapper.ToResponse(theme);
return Problem("Theme with this id not found", statusCode: 404);
return theme;
}
[HttpPost]
[Authorize(Policy = "permissions:admin.system.customisation.themes.write")]
public async Task<ThemeResponse> Create([FromBody] CreateThemeRequest request)
public async Task<ActionResult<ThemeResponse>> Create([FromBody] CreateThemeRequest request)
{
var theme = ThemeMapper.ToTheme(request);
var finalTheme = await ThemeRepository.Add(theme);
var finalTheme = await ThemeRepository.AddAsync(theme);
return ThemeMapper.ToResponse(finalTheme);
}
[HttpPatch("{id:int}")]
[Authorize(Policy = "permissions:admin.system.customisation.themes.write")]
public async Task<ThemeResponse> Update([FromRoute] int id, [FromBody] UpdateThemeRequest request)
public async Task<ActionResult<ThemeResponse>> Update([FromRoute] int id, [FromBody] UpdateThemeRequest request)
{
var theme = await ThemeRepository
.Get()
.FirstOrDefaultAsync(t => t.Id == id);
if (theme == null)
throw new HttpApiException("Theme with this id not found", 404);
return Problem("Theme with this id not found", statusCode: 404);
// Disable all other enabled themes if we are enabling the current theme.
// This ensures only one theme is enabled at the time
@@ -98,29 +129,28 @@ public class ThemesController : Controller
foreach (var otherTheme in otherThemes)
otherTheme.IsEnabled = false;
await ThemeRepository.RunTransaction(set =>
{
set.UpdateRange(otherThemes);
});
await ThemeRepository.RunTransactionAsync(set => { set.UpdateRange(otherThemes); });
}
ThemeMapper.Merge(theme, request);
await ThemeRepository.Update(theme);
await ThemeRepository.UpdateAsync(theme);
return ThemeMapper.ToResponse(theme);
}
[HttpDelete("{id:int}")]
[Authorize(Policy = "permissions:admin.system.customisation.themes.write")]
public async Task Delete([FromRoute] int id)
public async Task<ActionResult> Delete([FromRoute] int id)
{
var theme = await ThemeRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id);
if (theme == null)
throw new HttpApiException("Theme with this id not found", 404);
await ThemeRepository.Remove(theme);
return Problem("Theme with this id not found", statusCode: 404);
await ThemeRepository.RemoveAsync(theme);
return NoContent();
}
}

View File

@@ -1,4 +1,3 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
@@ -6,10 +5,10 @@ using Microsoft.Extensions.DependencyInjection;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Extended.Helpers;
using MoonCore.Extended.Models;
using MoonCore.Models;
using Moonlight.ApiServer.Database.Entities;
using Moonlight.ApiServer.Services;
using Moonlight.ApiServer.Mappers;
using Moonlight.Shared.Http.Requests.Admin.Users;
using Moonlight.Shared.Http.Responses.Admin.Users;
@@ -28,60 +27,78 @@ public class UsersController : Controller
[HttpGet]
[Authorize(Policy = "permissions:admin.users.get")]
public async Task<IPagedData<UserResponse>> Get([FromQuery] PagedOptions options)
public async Task<ActionResult<ICountedData<UserResponse>>> Get(
[FromQuery] int startIndex,
[FromQuery] int count,
[FromQuery] string? orderBy,
[FromQuery] string? filter,
[FromQuery] string orderByDir = "asc"
)
{
var count = await UserRepository.Get().CountAsync();
if (count > 100)
return Problem("You cannot fetch more items than 100 at a time", statusCode: 400);
IQueryable<User> query = UserRepository.Get();
var users = await UserRepository
.Get()
.OrderBy(x => x.Id)
.Skip(options.Page * options.PageSize)
.Take(options.PageSize)
query = orderBy switch
{
nameof(Database.Entities.User.Id) => orderByDir == "desc"
? query.OrderByDescending(x => x.Id)
: query.OrderBy(x => x.Id),
nameof(Database.Entities.User.Username) => orderByDir == "desc"
? query.OrderByDescending(x => x.Username)
: query.OrderBy(x => x.Username),
nameof(Database.Entities.User.Email) => orderByDir == "desc"
? query.OrderByDescending(x => x.Email)
: query.OrderBy(x => x.Email),
_ => query.OrderBy(x => x.Id)
};
if (!string.IsNullOrEmpty(filter))
{
query = query.Where(x =>
EF.Functions.ILike(x.Username, $"%{filter}%") ||
EF.Functions.ILike(x.Email, $"%{filter}%")
);
}
var totalCount = await query.CountAsync();
var items = await query
.Skip(startIndex)
.Take(count)
.AsNoTracking()
.ProjectToResponse()
.ToArrayAsync();
var mappedUsers = users
.Select(x => new UserResponse()
{
Id = x.Id,
Email = x.Email,
Username = x.Username,
Permissions = x.Permissions
})
.ToArray();
return new PagedData<UserResponse>()
return new CountedData<UserResponse>()
{
CurrentPage = options.Page,
Items = mappedUsers,
PageSize = options.PageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : (count - 1) / options.PageSize
Items = items,
TotalCount = totalCount
};
}
[HttpGet("{id}")]
[Authorize(Policy = "permissions:admin.users.get")]
public async Task<UserResponse> GetSingle(int id)
public async Task<ActionResult<UserResponse>> GetSingle(int id)
{
var user = await UserRepository
.Get()
.ProjectToResponse()
.FirstOrDefaultAsync(x => x.Id == id);
if (user == null)
throw new HttpApiException("No user with that id found", 404);
return Problem("No user with that id found", statusCode: 404);
return new UserResponse()
{
Id = user.Id,
Email = user.Email,
Username = user.Username,
Permissions = user.Permissions
};
return user;
}
[HttpPost]
[Authorize(Policy = "permissions:admin.users.create")]
public async Task<UserResponse> Create([FromBody] CreateUserRequest request)
public async Task<ActionResult<UserResponse>> Create([FromBody] CreateUserRequest request)
{
// Reformat values
request.Username = request.Username.ToLower().Trim();
@@ -89,10 +106,10 @@ public class UsersController : Controller
// Check for users with the same values
if (UserRepository.Get().Any(x => x.Username == request.Username))
throw new HttpApiException("A user with that username already exists", 400);
return Problem("A user with that username already exists", statusCode: 400);
if (UserRepository.Get().Any(x => x.Email == request.Email))
throw new HttpApiException("A user with that email address already exists", 400);
return Problem("A user with that email address already exists", statusCode: 400);
var hashedPassword = HashHelper.Hash(request.Password);
@@ -104,27 +121,21 @@ public class UsersController : Controller
Permissions = request.Permissions
};
var finalUser = await UserRepository.Add(user);
var finalUser = await UserRepository.AddAsync(user);
return new UserResponse()
{
Id = finalUser.Id,
Email = finalUser.Email,
Username = finalUser.Username,
Permissions = finalUser.Permissions
};
return UserMapper.ToResponse(finalUser);
}
[HttpPatch("{id}")]
[Authorize(Policy = "permissions:admin.users.update")]
public async Task<UserResponse> Update([FromRoute] int id, [FromBody] UpdateUserRequest request)
public async Task<ActionResult<UserResponse>> Update([FromRoute] int id, [FromBody] UpdateUserRequest request)
{
var user = await UserRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id);
if (user == null)
throw new HttpApiException("No user with that id found", 404);
return Problem("No user with that id found", statusCode: 404);
// Reformat values
request.Username = request.Username.ToLower().Trim();
@@ -132,10 +143,10 @@ public class UsersController : Controller
// Check for users with the same values
if (UserRepository.Get().Any(x => x.Username == request.Username && x.Id != user.Id))
throw new HttpApiException("A user with that username already exists", 400);
return Problem("Another user with that username already exists", statusCode: 400);
if (UserRepository.Get().Any(x => x.Email == request.Email && x.Id != user.Id))
throw new HttpApiException("A user with that email address already exists", 400);
return Problem("Another user with that email address already exists", statusCode: 400);
// Perform hashing the password if required
if (!string.IsNullOrEmpty(request.Password))
@@ -153,27 +164,21 @@ public class UsersController : Controller
user.Email = request.Email;
user.Username = request.Username;
await UserRepository.Update(user);
await UserRepository.UpdateAsync(user);
return new UserResponse()
{
Id = user.Id,
Email = user.Email,
Username = user.Username,
Permissions = user.Permissions
};
return UserMapper.ToResponse(user);
}
[HttpDelete("{id}")]
[Authorize(Policy = "permissions:admin.users.delete")]
public async Task Delete([FromRoute] int id, [FromQuery] bool force = false)
public async Task<ActionResult> Delete([FromRoute] int id, [FromQuery] bool force = false)
{
var user = await UserRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == id);
if (user == null)
throw new HttpApiException("No user with that id found", 404);
return Problem("No user with that id found", statusCode: 404);
var deletionService = HttpContext.RequestServices.GetRequiredService<UserDeletionService>();
@@ -182,9 +187,10 @@ public class UsersController : Controller
var validationResult = await deletionService.Validate(user);
if (!validationResult.IsAllowed)
throw new HttpApiException($"Unable to delete user", 400, validationResult.Reason);
return Problem("Unable to delete user", statusCode: 400, title: validationResult.Reason);
}
await deletionService.Delete(user, force);
return NoContent();
}
}