Implemented basic ui for server sharing. Extracted server authorization. Refactoring and small improvements

This commit is contained in:
2025-06-11 21:59:49 +02:00
parent cfed1aefde
commit b53140e633
35 changed files with 1098 additions and 213 deletions

View File

@@ -3,6 +3,7 @@ using MoonCore.Extended.SingleDb;
using Moonlight.ApiServer.Configuration; using Moonlight.ApiServer.Configuration;
using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Models; using MoonlightServers.ApiServer.Models;
using MoonlightServers.Shared.Models;
namespace MoonlightServers.ApiServer.Database; namespace MoonlightServers.ApiServer.Database;

View File

@@ -170,7 +170,12 @@ public class FilesController : Controller
); );
if (!authorizeResult.Succeeded) if (!authorizeResult.Succeeded)
throw new HttpApiException("No permission for the requested resource", 403); {
throw new HttpApiException(
authorizeResult.Message ?? "No permission for the requested resource",
403
);
}
return server; return server;
} }

View File

@@ -74,7 +74,12 @@ public class PowerController : Controller
); );
if (!authorizeResult.Succeeded) if (!authorizeResult.Succeeded)
throw new HttpApiException("No permission for the requested resource", 403); {
throw new HttpApiException(
authorizeResult.Message ?? "No permission for the requested resource",
403
);
}
return server; return server;
} }

View File

@@ -13,6 +13,7 @@ using MoonlightServers.ApiServer.Services;
using MoonlightServers.Shared.Enums; using MoonlightServers.Shared.Enums;
using MoonlightServers.Shared.Http.Responses.Client.Servers; using MoonlightServers.Shared.Http.Responses.Client.Servers;
using MoonlightServers.Shared.Http.Responses.Client.Servers.Allocations; using MoonlightServers.Shared.Http.Responses.Client.Servers.Allocations;
using MoonlightServers.Shared.Models;
namespace MoonlightServers.ApiServer.Http.Controllers.Client; namespace MoonlightServers.ApiServer.Http.Controllers.Client;
@@ -24,6 +25,7 @@ public class ServersController : Controller
private readonly ServerService ServerService; private readonly ServerService ServerService;
private readonly DatabaseRepository<Server> ServerRepository; private readonly DatabaseRepository<Server> ServerRepository;
private readonly DatabaseRepository<ServerShare> ShareRepository; private readonly DatabaseRepository<ServerShare> ShareRepository;
private readonly DatabaseRepository<User> UserRepository;
private readonly NodeService NodeService; private readonly NodeService NodeService;
private readonly ServerAuthorizeService AuthorizeService; private readonly ServerAuthorizeService AuthorizeService;
@@ -32,7 +34,8 @@ public class ServersController : Controller
NodeService nodeService, NodeService nodeService,
ServerService serverService, ServerService serverService,
ServerAuthorizeService authorizeService, ServerAuthorizeService authorizeService,
DatabaseRepository<ServerShare> shareRepository DatabaseRepository<ServerShare> shareRepository,
DatabaseRepository<User> userRepository
) )
{ {
ServerRepository = serverRepository; ServerRepository = serverRepository;
@@ -40,6 +43,7 @@ public class ServersController : Controller
ServerService = serverService; ServerService = serverService;
AuthorizeService = authorizeService; AuthorizeService = authorizeService;
ShareRepository = shareRepository; ShareRepository = shareRepository;
UserRepository = userRepository;
} }
[HttpGet] [HttpGet]
@@ -102,27 +106,46 @@ public class ServersController : Controller
var query = ShareRepository var query = ShareRepository
.Get() .Get()
.Include(x => x.Server) .Include(x => x.Server)
.Where(x => x.UserId == userId) .ThenInclude(x => x.Node)
.Select(x => x.Server); .Include(x => x.Server)
.ThenInclude(x => x.Star)
.Include(x => x.Server)
.ThenInclude(x => x.Allocations)
.Where(x => x.UserId == userId);
var count = await query.CountAsync(); var count = await query.CountAsync();
var items = await query.Skip(page * pageSize).Take(pageSize).ToArrayAsync(); var items = await query.Skip(page * pageSize).Take(pageSize).ToArrayAsync();
var ownerIds = items
.Select(x => x.Server.OwnerId)
.Distinct()
.ToArray();
var owners = await UserRepository
.Get()
.Where(x => ownerIds.Contains(x.Id))
.ToArrayAsync();
var mappedItems = items.Select(x => new ServerDetailResponse() var mappedItems = items.Select(x => new ServerDetailResponse()
{ {
Id = x.Id, Id = x.Server.Id,
Name = x.Name, Name = x.Server.Name,
NodeName = x.Node.Name, NodeName = x.Server.Node.Name,
StarName = x.Star.Name, StarName = x.Server.Star.Name,
Cpu = x.Cpu, Cpu = x.Server.Cpu,
Memory = x.Memory, Memory = x.Server.Memory,
Disk = x.Disk, Disk = x.Server.Disk,
Allocations = x.Allocations.Select(y => new AllocationDetailResponse() Allocations = x.Server.Allocations.Select(y => new AllocationDetailResponse()
{ {
Id = y.Id, Id = y.Id,
Port = y.Port, Port = y.Port,
IpAddress = y.IpAddress IpAddress = y.IpAddress
}).ToArray() }).ToArray(),
Share = new()
{
SharedBy = owners.First(y => y.Id == x.Server.OwnerId).Username,
Permissions = x.Content.Permissions.ToArray()
}
}).ToArray(); }).ToArray();
return new PagedData<ServerDetailResponse>() return new PagedData<ServerDetailResponse>()
@@ -151,9 +174,15 @@ public class ServersController : Controller
var authorizationResult = await AuthorizeService.Authorize(User, server); var authorizationResult = await AuthorizeService.Authorize(User, server);
if (!authorizationResult.Succeeded) if (!authorizationResult.Succeeded)
throw new HttpApiException("No server with this id found", 404); {
throw new HttpApiException(
authorizationResult.Message ?? "No server with this id found",
404
);
}
return new ServerDetailResponse() // Create mapped response
var response = new ServerDetailResponse()
{ {
Id = server.Id, Id = server.Id,
Name = server.Name, Name = server.Name,
@@ -169,6 +198,22 @@ public class ServersController : Controller
IpAddress = y.IpAddress IpAddress = y.IpAddress
}).ToArray() }).ToArray()
}; };
// Handle requests on shared servers
if (authorizationResult.Share != null)
{
var owner = await UserRepository
.Get()
.FirstAsync(x => x.Id == server.OwnerId);
response.Share = new()
{
SharedBy = owner.Username,
Permissions = authorizationResult.Share.Content.Permissions.ToArray()
};
}
return response;
} }
[HttpGet("{serverId:int}/status")] [HttpGet("{serverId:int}/status")]
@@ -261,7 +306,12 @@ public class ServersController : Controller
var authorizeResult = await AuthorizeService.Authorize(User, server, filter); var authorizeResult = await AuthorizeService.Authorize(User, server, filter);
if (!authorizeResult.Succeeded) if (!authorizeResult.Succeeded)
throw new HttpApiException("No permission for the requested resource", 403); {
throw new HttpApiException(
authorizeResult.Message ?? "No permission for the requested resource",
403
);
}
return server; return server;
} }

View File

@@ -53,7 +53,12 @@ public class SettingsController : Controller
); );
if (!authorizeResult.Succeeded) if (!authorizeResult.Succeeded)
throw new HttpApiException("No permission for the requested resource", 403); {
throw new HttpApiException(
authorizeResult.Message ?? "No permission for the requested resource",
403
);
}
return server; return server;
} }

View File

@@ -1,5 +1,16 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MoonCore.Exceptions;
using MoonCore.Extended.Abstractions;
using MoonCore.Models;
using Moonlight.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Services;
using MoonlightServers.Shared.Enums;
using MoonlightServers.Shared.Http.Requests.Client.Servers.Shares;
using MoonlightServers.Shared.Http.Responses.Client.Servers.Shares;
namespace MoonlightServers.ApiServer.Http.Controllers.Client; namespace MoonlightServers.ApiServer.Http.Controllers.Client;
@@ -8,5 +19,214 @@ namespace MoonlightServers.ApiServer.Http.Controllers.Client;
[Route("api/client/servers")] [Route("api/client/servers")]
public class SharesController : Controller public class SharesController : Controller
{ {
private readonly DatabaseRepository<Server> ServerRepository;
private readonly DatabaseRepository<ServerShare> ShareRepository;
private readonly DatabaseRepository<User> UserRepository;
private readonly ServerAuthorizeService AuthorizeService;
public SharesController(
DatabaseRepository<Server> serverRepository,
DatabaseRepository<ServerShare> shareRepository,
DatabaseRepository<User> userRepository,
ServerAuthorizeService authorizeService
)
{
ServerRepository = serverRepository;
ShareRepository = shareRepository;
UserRepository = userRepository;
AuthorizeService = authorizeService;
}
[HttpGet("{serverId:int}/shares")]
public async Task<PagedData<ServerShareResponse>> GetAll(
[FromRoute] int serverId,
[FromQuery] [Range(0, int.MaxValue)] int page,
[FromQuery] [Range(1, 100)] int pageSize
)
{
var server = await GetServerById(serverId);
var query = ShareRepository
.Get()
.Where(x => x.Server.Id == server.Id);
var count = await query.CountAsync();
var items = await query.Skip(page * pageSize).Take(pageSize).ToArrayAsync();
var userIds = items
.Select(x => x.UserId)
.Distinct()
.ToArray();
var users = await UserRepository
.Get()
.Where(x => userIds.Contains(x.Id))
.ToArrayAsync();
var mappedItems = items.Select(x => new ServerShareResponse()
{
Id = x.Id,
Username = users.First(y => y.Id == x.UserId).Username,
Permissions = x.Content.Permissions.ToArray()
}).ToArray();
return new PagedData<ServerShareResponse>()
{
Items = mappedItems,
CurrentPage = page,
PageSize = pageSize,
TotalItems = count,
TotalPages = count == 0 ? 0 : count / pageSize
};
}
[HttpGet("{serverId:int}/shares/{id:int}")]
public async Task<ServerShareResponse> Get(
[FromRoute] int serverId,
[FromRoute] int id
)
{
var server = await GetServerById(serverId);
var share = await ShareRepository
.Get()
.FirstOrDefaultAsync(x => x.Server.Id == server.Id && x.Id == id);
if (share == null)
throw new HttpApiException("A share with that id cannot be found", 404);
var user = await UserRepository
.Get()
.FirstAsync(x => x.Id == share.UserId);
var mappedItem = new ServerShareResponse()
{
Id = share.Id,
Username = user.Username,
Permissions = share.Content.Permissions.ToArray()
};
return mappedItem;
}
[HttpPost("{serverId:int}/shares")]
public async Task<ServerShareResponse> Create(
[FromRoute] int serverId,
[FromBody] CreateShareRequest request
)
{
var server = await GetServerById(serverId);
var user = await UserRepository
.Get()
.FirstOrDefaultAsync(x => x.Username == request.Username);
if (user == null)
throw new HttpApiException("A user with that username could not be found", 400);
var share = new ServerShare()
{
Server = server,
Content = new()
{
Permissions = request.Permissions
},
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow,
UserId = user.Id
};
var finalShare = await ShareRepository.Add(share);
var mappedItem = new ServerShareResponse()
{
Id = finalShare.Id,
Username = user.Username,
Permissions = finalShare.Content.Permissions.ToArray()
};
return mappedItem;
}
[HttpPatch("{serverId:int}/shares/{id:int}")]
public async Task<ServerShareResponse> Update(
[FromRoute] int serverId,
[FromRoute] int id,
[FromBody] UpdateShareRequest request
)
{
var server = await GetServerById(serverId);
var share = await ShareRepository
.Get()
.FirstOrDefaultAsync(x => x.Server.Id == server.Id && x.Id == id);
if (share == null)
throw new HttpApiException("A share with that id cannot be found", 404);
share.Content.Permissions = request.Permissions;
share.UpdatedAt = DateTime.UtcNow;
await ShareRepository.Update(share);
var user = await UserRepository
.Get()
.FirstOrDefaultAsync(x => x.Id == share.UserId);
if (user == null)
throw new HttpApiException("A user with that id could not be found", 400);
var mappedItem = new ServerShareResponse()
{
Id = share.Id,
Username = user.Username,
Permissions = share.Content.Permissions.ToArray()
};
return mappedItem;
}
[HttpDelete("{serverId:int}/shares/{id:int}")]
public async Task Delete(
[FromRoute] int serverId,
[FromRoute] int id
)
{
var server = await GetServerById(serverId);
var share = await ShareRepository
.Get()
.FirstOrDefaultAsync(x => x.Server.Id == server.Id && x.Id == id);
if (share == null)
throw new HttpApiException("A share with that id cannot be found", 404);
await ShareRepository.Remove(share);
}
private async Task<Server> GetServerById(int serverId)
{
var server = await ServerRepository
.Get()
.Include(x => x.Node)
.FirstOrDefaultAsync(x => x.Id == serverId);
if (server == null)
throw new HttpApiException("No server with this id found", 404);
var authorizeResult = await AuthorizeService.Authorize(
User, server,
permission => permission is { Name: "shares", Type: >= ServerPermissionType.ReadWrite }
);
if (!authorizeResult.Succeeded)
{
throw new HttpApiException(
authorizeResult.Message ?? "No permission for the requested resource",
403
);
}
return server;
}
} }

View File

@@ -138,7 +138,12 @@ public class VariablesController : Controller
); );
if (!authorizeResult.Succeeded) if (!authorizeResult.Succeeded)
throw new HttpApiException("No permission for the requested resource", 403); {
throw new HttpApiException(
authorizeResult.Message ?? "No permission for the requested resource",
403
);
}
return server; return server;
} }

View File

@@ -0,0 +1,33 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using MoonCore.Attributes;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Interfaces;
using MoonlightServers.ApiServer.Models;
using MoonlightServers.Shared.Models;
namespace MoonlightServers.ApiServer.Implementations.ServerAuthFilters;
public class AdminAuthFilter : IServerAuthorizationFilter
{
private readonly IAuthorizationService AuthorizationService;
public AdminAuthFilter(IAuthorizationService authorizationService)
{
AuthorizationService = authorizationService;
}
public async Task<ServerAuthorizationResult?> Process(
ClaimsPrincipal user,
Server server,
Func<ServerSharePermission, bool>? filter = null
)
{
var authResult = await AuthorizationService.AuthorizeAsync(
user,
"permissions:admin.servers.manage"
);
return authResult.Succeeded ? ServerAuthorizationResult.Success() : null;
}
}

View File

@@ -0,0 +1,28 @@
using System.Security.Claims;
using MoonCore.Attributes;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Interfaces;
using MoonlightServers.ApiServer.Models;
using MoonlightServers.Shared.Models;
namespace MoonlightServers.ApiServer.Implementations.ServerAuthFilters;
public class OwnerAuthFilter : IServerAuthorizationFilter
{
public Task<ServerAuthorizationResult?> Process(ClaimsPrincipal user, Server server, Func<ServerSharePermission, bool>? filter = null)
{
var userIdValue = user.FindFirstValue("userId");
if (string.IsNullOrEmpty(userIdValue)) // This is the case for api keys
return Task.FromResult<ServerAuthorizationResult?>(null);
var userId = int.Parse(userIdValue);
if(server.OwnerId != userId)
return Task.FromResult<ServerAuthorizationResult?>(null);
return Task.FromResult<ServerAuthorizationResult?>(
ServerAuthorizationResult.Success()
);
}
}

View File

@@ -0,0 +1,49 @@
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using MoonCore.Attributes;
using MoonCore.Extended.Abstractions;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Interfaces;
using MoonlightServers.ApiServer.Models;
using MoonlightServers.Shared.Models;
namespace MoonlightServers.ApiServer.Implementations.ServerAuthFilters;
public class ShareAuthFilter : IServerAuthorizationFilter
{
private readonly DatabaseRepository<ServerShare> ShareRepository;
public ShareAuthFilter(DatabaseRepository<ServerShare> shareRepository)
{
ShareRepository = shareRepository;
}
public async Task<ServerAuthorizationResult?> Process(
ClaimsPrincipal user,
Server server,
Func<ServerSharePermission, bool>? filter = null
)
{
var userIdValue = user.FindFirstValue("userId");
if (string.IsNullOrEmpty(userIdValue))
return null;
var userId = int.Parse(userIdValue);
var share = await ShareRepository
.Get()
.FirstOrDefaultAsync(x => x.Server.Id == server.Id && x.UserId == userId);
if (share == null)
return null;
if(filter == null)
return ServerAuthorizationResult.Success(share);
if(share.Content.Permissions.Any(filter))
return ServerAuthorizationResult.Success(share);
return null;
}
}

View File

@@ -0,0 +1,17 @@
using System.Security.Claims;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Models;
using MoonlightServers.Shared.Models;
namespace MoonlightServers.ApiServer.Interfaces;
public interface IServerAuthorizationFilter
{
// Return null => skip to next filter / handler
// Return any value, instant return
public Task<ServerAuthorizationResult?> Process(
ClaimsPrincipal user,
Server server,
Func<ServerSharePermission, bool>? filter = null
);
}

View File

@@ -0,0 +1,28 @@
using MoonlightServers.ApiServer.Database.Entities;
namespace MoonlightServers.ApiServer.Models;
public record ServerAuthorizationResult
{
public bool Succeeded { get; set; }
public ServerShare? Share { get; set; }
public string? Message { get; set; }
public static ServerAuthorizationResult Success(ServerShare? share = null)
{
return new()
{
Succeeded = true,
Share = share
};
}
public static ServerAuthorizationResult Failed(string? message = null)
{
return new()
{
Succeeded = false,
Message = message
};
}
}

View File

@@ -1,3 +1,5 @@
using MoonlightServers.Shared.Models;
namespace MoonlightServers.ApiServer.Models; namespace MoonlightServers.ApiServer.Models;
public class ServerShareContent public class ServerShareContent

View File

@@ -29,8 +29,6 @@
<ItemGroup> <ItemGroup>
<Folder Include="Database\Migrations\"/> <Folder Include="Database\Migrations\"/>
<Folder Include="Http\Middleware\"/> <Folder Include="Http\Middleware\"/>
<Folder Include="Implementations\"/>
<Folder Include="Interfaces\"/>
</ItemGroup> </ItemGroup>
<ItemGroup Label="Build instruction for nuget package building"> <ItemGroup Label="Build instruction for nuget package building">

View File

@@ -1,103 +1,38 @@
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using MoonCore.Attributes; using MoonCore.Attributes;
using MoonCore.Extended.Abstractions;
using MoonlightServers.ApiServer.Database.Entities; using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.ApiServer.Interfaces;
using MoonlightServers.ApiServer.Models; using MoonlightServers.ApiServer.Models;
using MoonlightServers.Shared.Enums; using MoonlightServers.Shared.Models;
namespace MoonlightServers.ApiServer.Services; namespace MoonlightServers.ApiServer.Services;
[Scoped] [Scoped]
public class ServerAuthorizeService public class ServerAuthorizeService
{ {
private readonly IAuthorizationService AuthorizationService; private readonly IEnumerable<IServerAuthorizationFilter> AuthorizationFilters;
private readonly DatabaseRepository<ServerShare> ShareRepository;
public ServerAuthorizeService( public ServerAuthorizeService(
IAuthorizationService authorizationService, IEnumerable<IServerAuthorizationFilter> authorizationFilters
DatabaseRepository<ServerShare> shareRepository
) )
{ {
AuthorizationService = authorizationService; AuthorizationFilters = authorizationFilters;
ShareRepository = shareRepository;
} }
public async Task<AuthorizationResult> Authorize(ClaimsPrincipal user, Server server, Func<ServerSharePermission, bool>? filter = null) public async Task<ServerAuthorizationResult> Authorize(
ClaimsPrincipal user,
Server server,
Func<ServerSharePermission, bool>? filter = null
)
{ {
var userIdClaim = user.FindFirst("userId"); foreach (var authorizationFilter in AuthorizationFilters)
// User specific authorization
if (userIdClaim != null)
{ {
var result = await AuthorizeViaUser(userIdClaim, server, filter); var result = await authorizationFilter.Process(user, server, filter);
if (result.Succeeded) if (result != null)
return result; return result;
} }
// Permission specific authorization return ServerAuthorizationResult.Failed();
return await AuthorizeViaPermission(user);
}
private async Task<AuthorizationResult> AuthorizeViaUser(Claim userIdClaim, Server server, Func<ServerSharePermission, bool>? filter = null)
{
var userId = int.Parse(userIdClaim.Value);
if (server.OwnerId == userId)
return AuthorizationResult.Success();
var possibleShare = await ShareRepository
.Get()
.FirstOrDefaultAsync(x => x.Server.Id == server.Id && x.UserId == userId);
if (possibleShare == null)
return AuthorizationResult.Failed();
// If no filter has been specified every server share is valid
// no matter which permission the share actually has
if (filter == null)
return AuthorizationResult.Success();
if(possibleShare.Content.Permissions.Any(filter))
return AuthorizationResult.Success();
return AuthorizationResult.Failed();
}
private async Task<AuthorizationResult> AuthorizeViaPermission(ClaimsPrincipal user)
{
return await AuthorizationService.AuthorizeAsync(
user,
"permissions:admin.servers.get"
);
}
private ServerSharePermission[] ParsePermissions(string permissionsString)
{
var result = new List<ServerSharePermission>();
var permissions = permissionsString.Split(';', StringSplitOptions.RemoveEmptyEntries);
foreach (var permission in permissions)
{
var permissionParts = permission.Split(':', StringSplitOptions.RemoveEmptyEntries);
// Skipped malformed permission parts
if(permissionParts.Length != 2)
continue;
if(!Enum.TryParse(permissionParts[1], true, out ServerPermissionType permissionType))
continue;
result.Add(new()
{
Name = permissionParts[0],
Type = permissionType
});
}
return result.ToArray();
} }
} }

View File

@@ -1,4 +1,3 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MoonCore.Attributes; using MoonCore.Attributes;
using MoonCore.Extended.Abstractions; using MoonCore.Extended.Abstractions;

View File

@@ -1,5 +1,4 @@
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MoonCore.Attributes; using MoonCore.Attributes;
using MoonCore.Exceptions; using MoonCore.Exceptions;

View File

@@ -4,6 +4,8 @@ using Moonlight.ApiServer.Models;
using Moonlight.ApiServer.Plugins; using Moonlight.ApiServer.Plugins;
using MoonlightServers.ApiServer.Database; using MoonlightServers.ApiServer.Database;
using MoonlightServers.ApiServer.Helpers; using MoonlightServers.ApiServer.Helpers;
using MoonlightServers.ApiServer.Implementations.ServerAuthFilters;
using MoonlightServers.ApiServer.Interfaces;
namespace MoonlightServers.ApiServer.Startup; namespace MoonlightServers.ApiServer.Startup;
@@ -38,6 +40,11 @@ public class PluginStartup : IPluginStartup
}); });
} }
// Add server auth filters
builder.Services.AddSingleton<IServerAuthorizationFilter, OwnerAuthFilter>();
builder.Services.AddScoped<IServerAuthorizationFilter, AdminAuthFilter>();
builder.Services.AddScoped<IServerAuthorizationFilter, ShareAuthFilter>();
return Task.CompletedTask; return Task.CompletedTask;
} }

View File

@@ -11,10 +11,11 @@ public class DefaultServerTabProvider : IServerTabProvider
{ {
ServerTab[] tabs = ServerTab[] tabs =
[ [
ServerTab.CreateFromComponent<ConsoleTab>("Console", "console", 0), ServerTab.CreateFromComponent<ConsoleTab>("Console", "console", 0, permission => permission.Name == "console"),
ServerTab.CreateFromComponent<FilesTab>("Files", "files", 1), ServerTab.CreateFromComponent<FilesTab>("Files", "files", 1, permission => permission.Name == "files"),
ServerTab.CreateFromComponent<VariablesTab>("Variables", "variables", 2), ServerTab.CreateFromComponent<SharesTab>("Shares", "shares", 2, permission => permission.Name == "shares"),
ServerTab.CreateFromComponent<SettingsTab>("Settings", "settings", 10), ServerTab.CreateFromComponent<VariablesTab>("Variables", "variables", 9, permission => permission.Name == "variables"),
ServerTab.CreateFromComponent<SettingsTab>("Settings", "settings", 10, permission => permission.Name == "settings"),
]; ];
return Task.FromResult(tabs); return Task.FromResult(tabs);

View File

@@ -1,22 +1,29 @@
using MoonlightServers.Frontend.UI.Components.Servers.ServerTabs; using MoonlightServers.Frontend.UI.Components.Servers.ServerTabs;
using MoonlightServers.Shared.Models;
namespace MoonlightServers.Frontend.Models; namespace MoonlightServers.Frontend.Models;
public class ServerTab public record ServerTab
{ {
public string Name { get; private set; } public string Name { get; private set; }
public string Path { get; private set; } public string Path { get; private set; }
public int Priority { get; set; } public Func<ServerSharePermission, bool>? PermissionFilter { get; private set; }
public int Priority { get; private set; }
public Type ComponentType { get; private set; } public Type ComponentType { get; private set; }
public static ServerTab CreateFromComponent<T>(string name, string path, int priority) where T : BaseServerTab public static ServerTab CreateFromComponent<T>(
string name,
string path,
int priority,
Func<ServerSharePermission, bool>? filter = null) where T : BaseServerTab
{ {
return new() return new()
{ {
Name = name, Name = name,
Path = path, Path = path,
Priority = priority, Priority = priority,
ComponentType = typeof(T) ComponentType = typeof(T),
PermissionFilter = filter
}; };
} }
} }

View File

@@ -24,6 +24,13 @@ public class ServerService
); );
} }
public async Task<PagedData<ServerDetailResponse>> GetSharedServers(int page, int perPage)
{
return await HttpApiClient.GetJson<PagedData<ServerDetailResponse>>(
$"api/client/servers/shared?page={page}&pageSize={perPage}"
);
}
public async Task<ServerDetailResponse> GetServer(int serverId) public async Task<ServerDetailResponse> GetServer(int serverId)
{ {
return await HttpApiClient.GetJson<ServerDetailResponse>( return await HttpApiClient.GetJson<ServerDetailResponse>(

View File

@@ -0,0 +1,34 @@
using MoonCore.Attributes;
using MoonCore.Helpers;
using MoonCore.Models;
using MoonlightServers.Shared.Http.Requests.Client.Servers.Shares;
using MoonlightServers.Shared.Http.Responses.Client.Servers.Shares;
namespace MoonlightServers.Frontend.Services;
[Scoped]
public class ServerShareService
{
private readonly HttpApiClient ApiClient;
public ServerShareService(HttpApiClient apiClient)
{
ApiClient = apiClient;
}
public async Task<PagedData<ServerShareResponse>> Get(int id, int page, int pageSize)
=> await ApiClient.GetJson<PagedData<ServerShareResponse>>(
$"api/client/servers/{id}/shares?page={page}&pageSize={pageSize}");
public async Task<ServerShareResponse> Get(int id, int shareId)
=> await ApiClient.GetJson<ServerShareResponse>($"api/client/servers/{id}/shares/{shareId}");
public async Task<ServerShareResponse> Create(int id, CreateShareRequest request)
=> await ApiClient.PostJson<ServerShareResponse>($"api/client/servers/{id}/shares", request);
public async Task<ServerShareResponse> Update(int id, int shareId, UpdateShareRequest request)
=> await ApiClient.PatchJson<ServerShareResponse>($"api/client/servers/{id}/shares/{shareId}", request);
public async Task Delete(int id, int shareId)
=> await ApiClient.Delete($"api/client/servers/{id}/shares/{shareId}");
}

View File

@@ -0,0 +1,105 @@
@using MoonCore.Blazor.Tailwind.Components
@using MoonlightServers.Shared.Enums
@using MoonlightServers.Shared.Http.Requests.Client.Servers.Shares
@using MoonlightServers.Shared.Models
@inherits MoonCore.Blazor.Tailwind.Modals.Components.BaseModal
<div class="text-lg font-semibold mb-5">
Create a new share
</div>
<HandleForm @ref="HandleForm" Model="Request" OnValidSubmit="OnValidSubmit">
<div class="mb-8">
<label class="block text-sm font-medium leading-6 text-white">Username</label>
<input @bind="Request.Username" type="text" class="form-input w-full"/>
</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-y-5 lg:gap-y-3">
@foreach (var name in Names)
{
var i = Permissions.TryGetValue(name, out var permission) ? (int)permission : -1;
<div class="col-span-1 flex flex-row items-center justify-center lg:justify-start">
@name
</div>
<div class="col-span-1 flex flex-row items-center justify-center lg:justify-end">
<div class="tabs">
<button @onclick="() => Reset(name)"
class="tabs-segment @(i == -1 ? "tabs-segment-active" : "")">
None
</button>
<button @onclick="() => Set(name, ServerPermissionType.Read)"
class="tabs-segment @(i == 0 ? "tabs-segment-active" : "")">
Read
</button>
<button @onclick="() => Set(name, ServerPermissionType.ReadWrite)"
class="tabs-segment @(i == 1 ? "tabs-segment-active" : "")">
Read & Write
</button>
</div>
</div>
}
</div>
</HandleForm>
<div class="mt-8 flex space-x-2">
<WButton OnClick="_ => Hide()" CssClasses="btn btn-secondary grow">Cancel</WButton>
<WButton OnClick="_ => Submit()" CssClasses="btn btn-primary grow">Create</WButton>
</div>
@code
{
[Parameter] public string Username { get; set; }
[Parameter] public Func<CreateShareRequest, Task> OnSubmit { get; set; }
private HandleForm HandleForm;
private CreateShareRequest Request;
private Dictionary<string, ServerPermissionType> Permissions = new();
private string[] Names =
[
"console",
"power",
"shares",
"files",
"variables",
"settings"
];
protected override void OnInitialized()
{
Request = new()
{
Username = Username
};
}
private async Task Set(string name, ServerPermissionType type)
{
Permissions[name] = type;
await InvokeAsync(StateHasChanged);
}
private async Task Reset(string name)
{
Permissions.Remove(name);
await InvokeAsync(StateHasChanged);
}
private async Task Submit()
=> await HandleForm.Submit();
private async Task OnValidSubmit()
{
Request.Permissions = Permissions.Select(x => new ServerSharePermission()
{
Name = x.Key,
Type = x.Value
}).ToList();
await OnSubmit.Invoke(Request);
await Hide();
}
}

View File

@@ -124,21 +124,34 @@
<div class="hidden 2xl:flex items-center justify-end gap-x-3 2xl:col-span-2"> <div class="hidden 2xl:flex items-center justify-end gap-x-3 2xl:col-span-2">
<div class="bg-gray-900 bg-opacity-45 py-1 px-2 rounded-lg flex flex-row"> @if (Server.Share != null)
<div> {
<i class="icon-sparkles"></i> <div class="bg-gray-900 bg-opacity-45 py-1 px-2 rounded-lg flex flex-row col-span-2">
<div>
<i class="icon-share-2"></i>
</div>
<div class="ms-3">Shared by <span class="text-primary">@Server.Share.SharedBy</span></div>
</div>
}
else
{
<div class="bg-gray-900 bg-opacity-45 py-1 px-2 rounded-lg flex flex-row">
<div>
<i class="icon-sparkles"></i>
</div>
<div class="ms-3">@Server.StarName</div>
</div> </div>
<div class="ms-3">@Server.StarName</div> <div class="bg-gray-900 bg-opacity-45 py-1 px-2 rounded-lg flex flex-row">
</div> <div>
<i class="icon-database"></i>
</div>
<div class="bg-gray-900 bg-opacity-45 py-1 px-2 rounded-lg flex flex-row"> <div class="ms-3">@Server.NodeName</div>
<div>
<i class="icon-database"></i>
</div> </div>
}
<div class="ms-3">@Server.NodeName</div>
</div>
</div> </div>
</div> </div>
</a> </a>

View File

@@ -8,6 +8,6 @@
[Parameter] public ServerDetailResponse Server { get; set; } [Parameter] public ServerDetailResponse Server { get; set; }
[Parameter] public ServerState State { get; set; } [Parameter] public ServerState State { get; set; }
[Parameter] public string InitialConsoleMessage { get; set; } [Parameter] public string InitialConsoleMessage { get; set; }
[Parameter] public HubConnection HubConnection { get; set; } [Parameter] public HubConnection? HubConnection { get; set; }
[Parameter] public Manage Parent { get; set; } [Parameter] public Manage Parent { get; set; }
} }

View File

@@ -0,0 +1,121 @@
@using MoonCore.Blazor.Tailwind.Alerts
@using MoonCore.Blazor.Tailwind.Components
@using MoonCore.Blazor.Tailwind.Modals
@using MoonCore.Blazor.Tailwind.Toasts
@using MoonCore.Models
@using MoonlightServers.Frontend.Services
@using MoonlightServers.Shared.Http.Requests.Client.Servers.Shares
@using MoonlightServers.Shared.Http.Responses.Client.Servers.Shares
@inherits BaseServerTab
@inject ServerShareService ShareService
@inject ModalService ModalService
@inject ToastService ToastService
@inject AlertService AlertService
<div class="flex flex-row mb-5">
<input @bind="UsernameInput" class="form-input grow placeholder-gray-500 me-1.5" autocomplete="none" placeholder="Enter a username"/>
<button @onclick="OpenCreateModal" class="btn btn-primary">
<i class="icon-send me-1"></i>
<span>Invite</span>
</button>
</div>
<LazyLoader @ref="LazyLoader" Load="Load">
@if (Shares.Length == 0)
{
<IconAlert Title="No shares found" Color="text-primary" Icon="icon-search">
Enter a username and press invite to share this server to another user
</IconAlert>
}
else
{
<div class="grid grid-col-1 gap-y-3">
@foreach (var share in Shares)
{
<div class="col-span-1 card card-body px-5 py-3 flex flex-row items-center justify-between">
<div class="flex justify-start font-semibold">
<i class="icon-user-round me-2"></i>
<span>@share.Username</span>
</div>
<div class="flex justify-end">
<WButton OnClick="_ => OpenUpdateModal(share)" CssClasses="btn btn-primary me-1.5">
<i class="icon-settings-2 me-1"></i>
<span>Edit</span>
</WButton>
<WButton OnClick="_ => Delete(share)" CssClasses="btn btn-danger">
<i class="icon-trash-2 me-1"></i>
<span>Delete</span>
</WButton>
</div>
</div>
}
</div>
}
</LazyLoader>
@code
{
private ServerShareResponse[] Shares;
private string UsernameInput = "";
private LazyLoader LazyLoader;
private async Task Load(LazyLoader _)
{
Shares = await PagedData<ServerShareResponse>.All(async (page, pageSize)
=> await ShareService.Get(Server.Id, page, pageSize)
);
}
private async Task OpenCreateModal()
{
await ModalService.Launch<CreateShareModal>(parameters =>
{
parameters["Username"] = UsernameInput;
parameters["OnSubmit"] = SubmitCreate;
}, size: "max-w-2xl");
}
private async Task SubmitCreate(CreateShareRequest request)
{
await ShareService.Create(Server.Id, request);
await ToastService.Success("Share successfully created");
await LazyLoader.Reload();
}
private async Task OpenUpdateModal(ServerShareResponse share)
{
await ModalService.Launch<UpdateShareModal>(parameters =>
{
parameters["Share"] = share;
parameters["OnSubmit"] = (UpdateShareRequest request) => SubmitUpdate(share.Id, request);
}, size: "max-w-2xl");
}
private async Task SubmitUpdate(int shareId, UpdateShareRequest request)
{
await ShareService.Update(Server.Id, shareId, request);
await ToastService.Success("Share successfully updated");
await LazyLoader.Reload();
}
private async Task Delete(ServerShareResponse share)
{
await AlertService.ConfirmDanger(
"Share deletion",
$"Do you really want to delete the share for the user '{share.Username}'? This cannot be undone",
async () =>
{
await ShareService.Delete(Server.Id, share.Id);
await ToastService.Success("Successfully deleted share");
await LazyLoader.Reload();
}
);
}
}

View File

@@ -0,0 +1,101 @@
@using MoonCore.Blazor.Tailwind.Components
@using MoonlightServers.Shared.Enums
@using MoonlightServers.Shared.Http.Requests.Client.Servers.Shares
@using MoonlightServers.Shared.Http.Responses.Client.Servers.Shares
@using MoonlightServers.Shared.Models
@inherits MoonCore.Blazor.Tailwind.Modals.Components.BaseModal
<div class="text-lg font-semibold mb-5">
Update share for @Share.Username
</div>
<HandleForm @ref="HandleForm" Model="Request" OnValidSubmit="OnValidSubmit">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-y-5 lg:gap-y-3">
@foreach (var name in Names)
{
var i = Permissions.TryGetValue(name, out var permission) ? (int)permission : -1;
<div class="col-span-1 flex flex-row items-center justify-center lg:justify-start">
@name
</div>
<div class="col-span-1 flex flex-row items-center justify-center lg:justify-end">
<div class="tabs">
<button @onclick="() => Reset(name)"
class="tabs-segment @(i == -1 ? "tabs-segment-active" : "")">
None
</button>
<button @onclick="() => Set(name, ServerPermissionType.Read)"
class="tabs-segment @(i == 0 ? "tabs-segment-active" : "")">
Read
</button>
<button @onclick="() => Set(name, ServerPermissionType.ReadWrite)"
class="tabs-segment @(i == 1 ? "tabs-segment-active" : "")">
Read & Write
</button>
</div>
</div>
}
</div>
</HandleForm>
<div class="mt-8 flex space-x-2">
<WButton OnClick="_ => Hide()" CssClasses="btn btn-secondary grow">Cancel</WButton>
<WButton OnClick="_ => Submit()" CssClasses="btn btn-primary grow">Update</WButton>
</div>
@code
{
[Parameter] public ServerShareResponse Share { get; set; }
[Parameter] public Func<UpdateShareRequest, Task> OnSubmit { get; set; }
private HandleForm HandleForm;
private UpdateShareRequest Request;
private Dictionary<string, ServerPermissionType> Permissions = new();
private string[] Names =
[
"console",
"power",
"shares",
"files",
"variables",
"settings"
];
protected override void OnInitialized()
{
Request = new();
Permissions = Share.Permissions.ToDictionary(x => x.Name, x => x.Type);
}
private async Task Set(string name, ServerPermissionType type)
{
Permissions[name] = type;
await InvokeAsync(StateHasChanged);
}
private async Task Reset(string name)
{
Permissions.Remove(name);
await InvokeAsync(StateHasChanged);
}
private async Task Submit()
=> await HandleForm.Submit();
private async Task OnValidSubmit()
{
Request.Permissions = Permissions.Select(x => new ServerSharePermission()
{
Name = x.Key,
Type = x.Value
}).ToList();
await OnSubmit.Invoke(Request);
await Hide();
}
}

View File

@@ -8,17 +8,19 @@
@inject ServerService ServerService @inject ServerService ServerService
<LazyLoader Load="Load"> <Tabs>
@if (Servers.Length == 0) <Tab Name="Your servers">
{ <LazyLoader Load="LoadOwnServers">
<IconAlert Title="No servers found" Color="text-primary" Icon="icon-search"> @if (OwnServers.Length == 0)
There are no servers linked to your account {
</IconAlert> <IconAlert Title="No servers found" Color="text-primary" Icon="icon-search">
} There are no servers linked to your account
else </IconAlert>
{ }
<div class="flex flex-col gap-y-5"> else
@* Folder design idea {
<div class="flex flex-col gap-y-5">
@* Folder design idea
<div class="w-full bg-gray-800 px-5 py-3.5 rounded-xl"> <div class="w-full bg-gray-800 px-5 py-3.5 rounded-xl">
<div class="flex items-center"> <div class="flex items-center">
<div class="bg-gray-900 bg-opacity-45 py-1 px-2 rounded-lg flex items-center"> <div class="bg-gray-900 bg-opacity-45 py-1 px-2 rounded-lg flex items-center">
@@ -36,22 +38,51 @@
</div> </div>
</div> </div>
*@ *@
@foreach (var server in Servers) @foreach (var server in OwnServers)
{ {
<ServerCard Server="server"/> <ServerCard Server="server"/>
}
</div>
} }
</div> </LazyLoader>
} </Tab>
</LazyLoader> <Tab Name="Shared servers">
<LazyLoader Load="LoadSharedServers">
@if (SharedServers.Length == 0)
{
<IconAlert Title="No shared servers found" Color="text-primary" Icon="icon-share-2">
There are no shared servers linked to your account
</IconAlert>
}
else
{
<div class="flex flex-col gap-y-5">
@foreach (var server in SharedServers)
{
<ServerCard Server="server"/>
}
</div>
}
</LazyLoader>
</Tab>
</Tabs>
@code @code
{ {
private ServerDetailResponse[] Servers; private ServerDetailResponse[] OwnServers;
private ServerDetailResponse[] SharedServers;
private async Task Load(LazyLoader lazyLoader) private async Task LoadOwnServers(LazyLoader lazyLoader)
{ {
Servers = await PagedData<ServerDetailResponse>.All(async (page, pageSize) => OwnServers = await PagedData<ServerDetailResponse>.All(async (page, pageSize) =>
await ServerService.GetServers(page, pageSize) await ServerService.GetServers(page, pageSize)
); );
} }
private async Task LoadSharedServers(LazyLoader lazyLoader)
{
SharedServers = await PagedData<ServerDetailResponse>.All(async (page, pageSize) =>
await ServerService.GetSharedServers(page, pageSize)
);
}
} }

View File

@@ -1,7 +1,6 @@
@page "/servers/{ServerId:int}" @page "/servers/{ServerId:int}"
@page "/servers/{ServerId:int}/{TabPath:alpha}" @page "/servers/{ServerId:int}/{TabPath:alpha}"
@using Microsoft.AspNetCore.Http.Connections
@using Microsoft.AspNetCore.SignalR.Client @using Microsoft.AspNetCore.SignalR.Client
@using MoonCore.Blazor.Tailwind.Components @using MoonCore.Blazor.Tailwind.Components
@using MoonCore.Exceptions @using MoonCore.Exceptions
@@ -66,12 +65,62 @@
</div> </div>
<div class="flex flex-row items-center"> <div class="flex flex-row items-center">
<div class="flex gap-x-1.5"> <div class="flex gap-x-1.5">
@if (State == ServerState.Offline) @if (HasPermissionTo("power", ServerPermissionType.ReadWrite))
{ {
<WButton CssClasses="btn btn-success" OnClick="_ => Start()"> @if (State == ServerState.Offline)
<i class="icon-play me-1 align-middle"></i> {
<span class="align-middle">Start</span> <WButton CssClasses="btn btn-success" OnClick="_ => Start()">
</WButton> <i class="icon-play me-1 align-middle"></i>
<span class="align-middle">Start</span>
</WButton>
}
else
{
<button type="button" class="btn btn-success" disabled="disabled">
<i class="icon-play me-1 align-middle"></i>
<span class="align-middle">Start</span>
</button>
}
@if (State == ServerState.Online)
{
<button type="button" class="btn btn-primary">
<i class="icon-rotate-ccw me-1 align-middle"></i>
<span class="align-middle">Restart</span>
</button>
}
else
{
<button type="button" class="btn btn-primary" disabled="disabled">
<i class="icon-rotate-ccw me-1 align-middle"></i>
<span class="align-middle">Restart</span>
</button>
}
@if (State == ServerState.Starting || State == ServerState.Online || State == ServerState.Stopping)
{
if (State == ServerState.Stopping)
{
<WButton CssClasses="btn btn-danger" OnClick="_ => Kill()">
<i class="icon-bomb me-1 align-middle"></i>
<span class="align-middle">Kill</span>
</WButton>
}
else
{
<WButton CssClasses="btn btn-danger" OnClick="_ => Stop()">
<i class="icon-squircle me-1 align-middle"></i>
<span class="align-middle">Stop</span>
</WButton>
}
}
else
{
<button type="button" class="btn btn-danger" disabled="disabled">
<i class="icon-squircle me-1 align-middle"></i>
<span class="align-middle">Stop</span>
</button>
}
} }
else else
{ {
@@ -79,42 +128,12 @@
<i class="icon-play me-1 align-middle"></i> <i class="icon-play me-1 align-middle"></i>
<span class="align-middle">Start</span> <span class="align-middle">Start</span>
</button> </button>
}
@if (State == ServerState.Online)
{
<button type="button" class="btn btn-primary">
<i class="icon-rotate-ccw me-1 align-middle"></i>
<span class="align-middle">Restart</span>
</button>
}
else
{
<button type="button" class="btn btn-primary" disabled="disabled"> <button type="button" class="btn btn-primary" disabled="disabled">
<i class="icon-rotate-ccw me-1 align-middle"></i> <i class="icon-rotate-ccw me-1 align-middle"></i>
<span class="align-middle">Restart</span> <span class="align-middle">Restart</span>
</button> </button>
}
@if (State == ServerState.Starting || State == ServerState.Online || State == ServerState.Stopping)
{
if (State == ServerState.Stopping)
{
<WButton CssClasses="btn btn-danger" OnClick="_ => Kill()">
<i class="icon-bomb me-1 align-middle"></i>
<span class="align-middle">Kill</span>
</WButton>
}
else
{
<WButton CssClasses="btn btn-danger" OnClick="_ => Stop()">
<i class="icon-squircle me-1 align-middle"></i>
<span class="align-middle">Stop</span>
</WButton>
}
}
else
{
<button type="button" class="btn btn-danger" disabled="disabled"> <button type="button" class="btn btn-danger" disabled="disabled">
<i class="icon-squircle me-1 align-middle"></i> <i class="icon-squircle me-1 align-middle"></i>
<span class="align-middle">Stop</span> <span class="align-middle">Stop</span>
@@ -148,19 +167,26 @@
} }
</ul> </ul>
@{
var rf = ComponentHelper.FromType(CurrentTab!.ComponentType, parameters =>
{
parameters.Add("Server", Server);
parameters.Add("State", State);
parameters.Add("InitialConsoleMessage", InitialConsoleMessage);
parameters.Add("HubConnection", HubConnection);
parameters.Add("Parent", this);
});
}
<div class="mt-5"> <div class="mt-5">
@rf @if (CurrentTab == null)
{
<IconAlert Title="No tabs found" Color="text-primary" Icon="icon-app-window">
Seems like you are missing access to all tabs or no tabs for this server could be found
</IconAlert>
}
else
{
var rf = ComponentHelper.FromType(CurrentTab!.ComponentType, parameters =>
{
parameters.Add("Server", Server);
parameters.Add("State", State);
parameters.Add("InitialConsoleMessage", InitialConsoleMessage);
parameters.Add("HubConnection", HubConnection!);
parameters.Add("Parent", this);
});
@rf
}
</div> </div>
</div> </div>
} }
@@ -177,9 +203,9 @@
private ServerDetailResponse Server; private ServerDetailResponse Server;
private bool NotFound = false; private bool NotFound = false;
private ServerState State; private ServerState State;
private string InitialConsoleMessage; private string InitialConsoleMessage = "";
private HubConnection HubConnection; private HubConnection? HubConnection;
private async Task Load(LazyLoader _) private async Task Load(LazyLoader _)
{ {
@@ -194,24 +220,39 @@
foreach (var serverTabProvider in TabProviders) foreach (var serverTabProvider in TabProviders)
tmpTabs.AddRange(await serverTabProvider.GetTabs(Server)); tmpTabs.AddRange(await serverTabProvider.GetTabs(Server));
// If we are accessing a shared server, we need to handle permissions
if (Server.Share != null)
{
// This removes all tabs where the permission filter is not set
tmpTabs.RemoveAll(tab =>
{
if (tab.PermissionFilter == null)
return false;
return !Server.Share.Permissions.Any(tab.PermissionFilter);
});
}
Tabs = tmpTabs.OrderBy(x => x.Priority).ToArray(); Tabs = tmpTabs.OrderBy(x => x.Priority).ToArray();
// Find current tab // Find current tab
if (!string.IsNullOrEmpty(TabPath)) if (!string.IsNullOrEmpty(TabPath))
{ {
CurrentTab = Tabs.FirstOrDefault( CurrentTab = Tabs.FirstOrDefault(x => TabPath.Equals(x.Path, StringComparison.InvariantCultureIgnoreCase)
x => TabPath.Equals(x.Path, StringComparison.InvariantCultureIgnoreCase)
); );
} }
if (CurrentTab == null) if (CurrentTab == null)
CurrentTab = Tabs.First(); CurrentTab = Tabs.FirstOrDefault();
// Load initial status for first render // Load initial status for first render
var status = await ServerService.GetStatus(ServerId); var status = await ServerService.GetStatus(ServerId);
State = status.State; State = status.State;
if (!HasPermissionTo("console", ServerPermissionType.Read))
return; // Exit early if we don't have permissions to load the console
// Load initial messages // Load initial messages
var initialLogs = await ServerService.GetLogs(ServerId); var initialLogs = await ServerService.GetLogs(ServerId);
@@ -265,6 +306,15 @@
} }
} }
private bool HasPermissionTo(string name, ServerPermissionType type)
{
// All non shares have permissions
if (Server.Share == null)
return true;
return Server.Share.Permissions.Any(x => x.Name == name && x.Type >= type);
}
private async Task SwitchTab(ServerTab tab) private async Task SwitchTab(ServerTab tab)
{ {
CurrentTab = tab; CurrentTab = tab;
@@ -284,9 +334,12 @@
public async ValueTask DisposeAsync() public async ValueTask DisposeAsync()
{ {
if (HubConnection.State == HubConnectionState.Connected) if (HubConnection != null)
await HubConnection.StopAsync(); {
if (HubConnection.State == HubConnectionState.Connected)
await HubConnection.StopAsync();
await HubConnection.DisposeAsync(); await HubConnection.DisposeAsync();
}
} }
} }

View File

@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
using MoonlightServers.Shared.Models;
namespace MoonlightServers.Shared.Http.Requests.Client.Servers.Shares;
public record CreateShareRequest
{
[Required(ErrorMessage = "You need to provide a username")]
public string Username { get; set; }
public List<ServerSharePermission> Permissions { get; set; } = [];
}

View File

@@ -0,0 +1,8 @@
using MoonlightServers.Shared.Models;
namespace MoonlightServers.Shared.Http.Requests.Client.Servers.Shares;
public record UpdateShareRequest
{
public List<ServerSharePermission> Permissions { get; set; } = [];
}

View File

@@ -1,8 +1,9 @@
using MoonlightServers.Shared.Http.Responses.Client.Servers.Allocations; using MoonlightServers.Shared.Http.Responses.Client.Servers.Allocations;
using MoonlightServers.Shared.Models;
namespace MoonlightServers.Shared.Http.Responses.Client.Servers; namespace MoonlightServers.Shared.Http.Responses.Client.Servers;
public class ServerDetailResponse public record ServerDetailResponse
{ {
public int Id { get; set; } public int Id { get; set; }
@@ -16,4 +17,12 @@ public class ServerDetailResponse
public string StarName { get; set; } public string StarName { get; set; }
public AllocationDetailResponse[] Allocations { get; set; } public AllocationDetailResponse[] Allocations { get; set; }
public ShareData? Share { get; set; } = null;
public record ShareData
{
public string SharedBy { get; set; }
public ServerSharePermission[] Permissions { get; set; }
}
} }

View File

@@ -1,9 +1,10 @@
using MoonlightServers.Shared.Models;
namespace MoonlightServers.Shared.Http.Responses.Client.Servers.Shares; namespace MoonlightServers.Shared.Http.Responses.Client.Servers.Shares;
public class ServerShareResponse public class ServerShareResponse
{ {
public int Id { get; set; } public int Id { get; set; }
public string Username { get; set; }
public string Email { get; set; } public ServerSharePermission[] Permissions { get; set; }
public string Permissions { get; set; }
} }

View File

@@ -1,8 +1,8 @@
using MoonlightServers.Shared.Enums; using MoonlightServers.Shared.Enums;
namespace MoonlightServers.ApiServer.Models; namespace MoonlightServers.Shared.Models;
public class ServerSharePermission public record ServerSharePermission
{ {
public string Name { get; set; } public string Name { get; set; }
public ServerPermissionType Type { get; set; } public ServerPermissionType Type { get; set; }

View File

@@ -14,8 +14,4 @@
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Folder Include="Http\Responses\Users\Servers\" />
</ItemGroup>
</Project> </Project>