Implemented basic ui for server sharing. Extracted server authorization. Refactoring and small improvements
This commit is contained in:
@@ -3,6 +3,7 @@ using MoonCore.Extended.SingleDb;
|
||||
using Moonlight.ApiServer.Configuration;
|
||||
using MoonlightServers.ApiServer.Database.Entities;
|
||||
using MoonlightServers.ApiServer.Models;
|
||||
using MoonlightServers.Shared.Models;
|
||||
|
||||
namespace MoonlightServers.ApiServer.Database;
|
||||
|
||||
|
||||
@@ -170,7 +170,12 @@ public class FilesController : Controller
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -74,7 +74,12 @@ public class PowerController : Controller
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ using MoonlightServers.ApiServer.Services;
|
||||
using MoonlightServers.Shared.Enums;
|
||||
using MoonlightServers.Shared.Http.Responses.Client.Servers;
|
||||
using MoonlightServers.Shared.Http.Responses.Client.Servers.Allocations;
|
||||
using MoonlightServers.Shared.Models;
|
||||
|
||||
namespace MoonlightServers.ApiServer.Http.Controllers.Client;
|
||||
|
||||
@@ -24,6 +25,7 @@ public class ServersController : Controller
|
||||
private readonly ServerService ServerService;
|
||||
private readonly DatabaseRepository<Server> ServerRepository;
|
||||
private readonly DatabaseRepository<ServerShare> ShareRepository;
|
||||
private readonly DatabaseRepository<User> UserRepository;
|
||||
private readonly NodeService NodeService;
|
||||
private readonly ServerAuthorizeService AuthorizeService;
|
||||
|
||||
@@ -32,7 +34,8 @@ public class ServersController : Controller
|
||||
NodeService nodeService,
|
||||
ServerService serverService,
|
||||
ServerAuthorizeService authorizeService,
|
||||
DatabaseRepository<ServerShare> shareRepository
|
||||
DatabaseRepository<ServerShare> shareRepository,
|
||||
DatabaseRepository<User> userRepository
|
||||
)
|
||||
{
|
||||
ServerRepository = serverRepository;
|
||||
@@ -40,6 +43,7 @@ public class ServersController : Controller
|
||||
ServerService = serverService;
|
||||
AuthorizeService = authorizeService;
|
||||
ShareRepository = shareRepository;
|
||||
UserRepository = userRepository;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
@@ -102,27 +106,46 @@ public class ServersController : Controller
|
||||
var query = ShareRepository
|
||||
.Get()
|
||||
.Include(x => x.Server)
|
||||
.Where(x => x.UserId == userId)
|
||||
.Select(x => x.Server);
|
||||
.ThenInclude(x => x.Node)
|
||||
.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 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()
|
||||
{
|
||||
Id = x.Id,
|
||||
Name = x.Name,
|
||||
NodeName = x.Node.Name,
|
||||
StarName = x.Star.Name,
|
||||
Cpu = x.Cpu,
|
||||
Memory = x.Memory,
|
||||
Disk = x.Disk,
|
||||
Allocations = x.Allocations.Select(y => new AllocationDetailResponse()
|
||||
Id = x.Server.Id,
|
||||
Name = x.Server.Name,
|
||||
NodeName = x.Server.Node.Name,
|
||||
StarName = x.Server.Star.Name,
|
||||
Cpu = x.Server.Cpu,
|
||||
Memory = x.Server.Memory,
|
||||
Disk = x.Server.Disk,
|
||||
Allocations = x.Server.Allocations.Select(y => new AllocationDetailResponse()
|
||||
{
|
||||
Id = y.Id,
|
||||
Port = y.Port,
|
||||
IpAddress = y.IpAddress
|
||||
}).ToArray()
|
||||
}).ToArray(),
|
||||
Share = new()
|
||||
{
|
||||
SharedBy = owners.First(y => y.Id == x.Server.OwnerId).Username,
|
||||
Permissions = x.Content.Permissions.ToArray()
|
||||
}
|
||||
}).ToArray();
|
||||
|
||||
return new PagedData<ServerDetailResponse>()
|
||||
@@ -149,11 +172,17 @@ public class ServersController : Controller
|
||||
throw new HttpApiException("No server with this id found", 404);
|
||||
|
||||
var authorizationResult = await AuthorizeService.Authorize(User, server);
|
||||
|
||||
if (!authorizationResult.Succeeded)
|
||||
throw new HttpApiException("No server with this id found", 404);
|
||||
|
||||
return new ServerDetailResponse()
|
||||
if (!authorizationResult.Succeeded)
|
||||
{
|
||||
throw new HttpApiException(
|
||||
authorizationResult.Message ?? "No server with this id found",
|
||||
404
|
||||
);
|
||||
}
|
||||
|
||||
// Create mapped response
|
||||
var response = new ServerDetailResponse()
|
||||
{
|
||||
Id = server.Id,
|
||||
Name = server.Name,
|
||||
@@ -169,6 +198,22 @@ public class ServersController : Controller
|
||||
IpAddress = y.IpAddress
|
||||
}).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")]
|
||||
@@ -261,7 +306,12 @@ public class ServersController : Controller
|
||||
var authorizeResult = await AuthorizeService.Authorize(User, server, filter);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -53,7 +53,12 @@ public class SettingsController : Controller
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
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;
|
||||
|
||||
@@ -8,5 +19,214 @@ namespace MoonlightServers.ApiServer.Http.Controllers.Client;
|
||||
[Route("api/client/servers")]
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -138,7 +138,12 @@ public class VariablesController : Controller
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using MoonlightServers.Shared.Models;
|
||||
|
||||
namespace MoonlightServers.ApiServer.Models;
|
||||
|
||||
public class ServerShareContent
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
using MoonlightServers.Shared.Enums;
|
||||
|
||||
namespace MoonlightServers.ApiServer.Models;
|
||||
|
||||
public class ServerSharePermission
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public ServerPermissionType Type { get; set; }
|
||||
}
|
||||
@@ -29,8 +29,6 @@
|
||||
<ItemGroup>
|
||||
<Folder Include="Database\Migrations\"/>
|
||||
<Folder Include="Http\Middleware\"/>
|
||||
<Folder Include="Implementations\"/>
|
||||
<Folder Include="Interfaces\"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Label="Build instruction for nuget package building">
|
||||
|
||||
@@ -1,103 +1,38 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
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.Enums;
|
||||
using MoonlightServers.Shared.Models;
|
||||
|
||||
namespace MoonlightServers.ApiServer.Services;
|
||||
|
||||
[Scoped]
|
||||
public class ServerAuthorizeService
|
||||
{
|
||||
private readonly IAuthorizationService AuthorizationService;
|
||||
private readonly DatabaseRepository<ServerShare> ShareRepository;
|
||||
private readonly IEnumerable<IServerAuthorizationFilter> AuthorizationFilters;
|
||||
|
||||
public ServerAuthorizeService(
|
||||
IAuthorizationService authorizationService,
|
||||
DatabaseRepository<ServerShare> shareRepository
|
||||
IEnumerable<IServerAuthorizationFilter> authorizationFilters
|
||||
)
|
||||
{
|
||||
AuthorizationService = authorizationService;
|
||||
ShareRepository = shareRepository;
|
||||
AuthorizationFilters = authorizationFilters;
|
||||
}
|
||||
|
||||
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");
|
||||
|
||||
// User specific authorization
|
||||
if (userIdClaim != null)
|
||||
foreach (var authorizationFilter in AuthorizationFilters)
|
||||
{
|
||||
var result = await AuthorizeViaUser(userIdClaim, server, filter);
|
||||
var result = await authorizationFilter.Process(user, server, filter);
|
||||
|
||||
if (result.Succeeded)
|
||||
if (result != null)
|
||||
return result;
|
||||
}
|
||||
|
||||
// Permission specific authorization
|
||||
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();
|
||||
return ServerAuthorizationResult.Failed();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MoonCore.Attributes;
|
||||
using MoonCore.Extended.Abstractions;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MoonCore.Attributes;
|
||||
using MoonCore.Exceptions;
|
||||
|
||||
@@ -4,6 +4,8 @@ using Moonlight.ApiServer.Models;
|
||||
using Moonlight.ApiServer.Plugins;
|
||||
using MoonlightServers.ApiServer.Database;
|
||||
using MoonlightServers.ApiServer.Helpers;
|
||||
using MoonlightServers.ApiServer.Implementations.ServerAuthFilters;
|
||||
using MoonlightServers.ApiServer.Interfaces;
|
||||
|
||||
namespace MoonlightServers.ApiServer.Startup;
|
||||
|
||||
@@ -37,6 +39,11 @@ public class PluginStartup : IPluginStartup
|
||||
Styles = ["css/XtermBlazor.min.css"]
|
||||
});
|
||||
}
|
||||
|
||||
// Add server auth filters
|
||||
builder.Services.AddSingleton<IServerAuthorizationFilter, OwnerAuthFilter>();
|
||||
builder.Services.AddScoped<IServerAuthorizationFilter, AdminAuthFilter>();
|
||||
builder.Services.AddScoped<IServerAuthorizationFilter, ShareAuthFilter>();
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user