Skip to content

Commit

Permalink
initial permissions based webfront access implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
RaidMax committed Apr 5, 2022
1 parent bab3995 commit 91a0534
Show file tree
Hide file tree
Showing 8 changed files with 125 additions and 41 deletions.
9 changes: 7 additions & 2 deletions SharedLibraryCore/BaseController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public class BaseController : Controller
private static string SocialTitle;
protected readonly DatabaseContext Context;
protected List<Page> Pages;
protected List<string> PermissionsSet;

public BaseController(IManager manager)
{
Expand All @@ -43,7 +44,6 @@ public BaseController(IManager manager)
SocialTitle = AppConfig.SocialLinkTitle;
}


Pages = Manager.GetPageList().Pages
.Select(page => new Page
{
Expand Down Expand Up @@ -135,6 +135,11 @@ public override void OnActionExecuting(ActionExecutingContext context)
var claimsIdentity = new ClaimsIdentity(claims, "login");
SignInAsync(new ClaimsPrincipal(claimsIdentity)).Wait();
}

if (AppConfig.PermissionSets.ContainsKey(Client.Level.ToString()))
{
PermissionsSet = AppConfig.PermissionSets[Client.Level.ToString()];
}

var communityName = AppConfig.CommunityInformation?.Name;
var shouldUseCommunityName = !string.IsNullOrWhiteSpace(communityName)
Expand All @@ -160,4 +165,4 @@ public override void OnActionExecuting(ActionExecutingContext context)
base.OnActionExecuting(context);
}
}
}
}
12 changes: 11 additions & 1 deletion SharedLibraryCore/Configuration/ApplicationConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public class ApplicationConfiguration : IBaseConfiguration

[LocalizedDisplayName("WEBFRONT_CONFIGURATION_ENABLE_COLOR_CODES")]
public bool EnableColorCodes { get; set; }

[ConfigurationIgnore] public string IngameAccentColorKey { get; set; } = "Cyan";

[LocalizedDisplayName("WEBFRONT_CONFIGURATION_AUTOMESSAGE_PERIOD")]
Expand Down Expand Up @@ -144,6 +144,16 @@ public class ApplicationConfiguration : IBaseConfiguration
TimeSpan.FromDays(30)
};

public Dictionary<string, List<string>> PermissionSets { get; set; } = new()
{
{ Permission.Trusted.ToString(), new List<string> { "*" } },
{ Permission.Moderator.ToString(), new List<string> { "*" } },
{ Permission.Administrator.ToString(), new List<string> { "*" } },
{ Permission.SeniorAdmin.ToString(), new List<string> { "*" } },
{ Permission.Owner.ToString(), new List<string> { "*" } },
{ Permission.Console.ToString(), new List<string> { "*" } }
};

[ConfigurationIgnore]
[LocalizedDisplayName("WEBFRONT_CONFIGURATION_PRESET_BAN_REASONS")]
public Dictionary<string, string> PresetPenaltyReasons { get; set; } = new Dictionary<string, string>
Expand Down
39 changes: 39 additions & 0 deletions SharedLibraryCore/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,45 @@ public static TimeSpan ParseTimespan(this string input)
return new TimeSpan(1, 0, 0);
}

public static bool HasPermission<TEntity, TPermission>(this IEnumerable<string> permissionsSet, TEntity entity,
TPermission permission) where TEntity : Enum where TPermission : Enum
{
return permissionsSet?.Any(raw =>
{
if (raw == "*")
{
return true;
}

var split = raw.Split(".");

if (split.Length != 2)
{
return false;
}

if (!Enum.TryParse(typeof(TEntity), split[0], out var e))
{
return false;
}

if (!Enum.TryParse(typeof(TPermission), split[1], out var p))
{
return false;
}

return (e?.Equals(entity) ?? false) && (p?.Equals(permission) ?? false);
}) ?? false;
}

public static bool HasPermission<TEntity, TPermission>(this ApplicationConfiguration appConfig,
Permission permissionLevel, TEntity entity,
TPermission permission) where TEntity : Enum where TPermission : Enum
{
return appConfig.PermissionSets.ContainsKey(permissionLevel.ToString()) &&
HasPermission(appConfig.PermissionSets[permissionLevel.ToString()], entity, permission);
}

/// <summary>
/// returns a list of penalty types that should be shown across all profiles
/// </summary>
Expand Down
11 changes: 10 additions & 1 deletion WebfrontCore/Controllers/ActionController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using SharedLibraryCore.Commands;
using SharedLibraryCore.Configuration;
using SharedLibraryCore.Interfaces;
using WebfrontCore.Permissions;
using WebfrontCore.ViewModels;

namespace WebfrontCore.Controllers
Expand Down Expand Up @@ -314,6 +315,14 @@ public async Task<IActionResult> ChatAsync(long id, string message)
public async Task<IActionResult> RecentClientsForm()
{
var clients = await Manager.GetClientService().GetRecentClients();
foreach (var client in clients)
{
client.IPAddress =
_appConfig.HasPermission(Client.Level, WebfrontEntity.IPAddress, WebfrontPermission.Read)
? client.IPAddress
: null;
}

return View("~/Views/Shared/Components/Client/_RecentClients.cshtml", clients);
}

Expand Down Expand Up @@ -453,4 +462,4 @@ private Dictionary<string, string> GetPresetPenaltyReasons() => _appConfig.Prese
})
.ToDictionary(item => item.Value, item => item.Value);
}
}
}
25 changes: 14 additions & 11 deletions WebfrontCore/Controllers/Client/ClientController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
using SharedLibraryCore.QueryHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Data.Models;
using Stats.Config;
using WebfrontCore.Permissions;
using WebfrontCore.ViewComponents;

namespace WebfrontCore.Controllers
Expand Down Expand Up @@ -79,7 +81,7 @@ public async Task<IActionResult> ProfileAsync(int id, MetaType? metaFilterType,
Level = displayLevel,
LevelInt = displayLevelInt,
ClientId = client.ClientId,
IPAddress = client.IPAddressString,
IPAddress = PermissionsSet.HasPermission(WebfrontEntity.IPAddress, WebfrontPermission.Read) ? client.IPAddressString : null,
NetworkId = client.NetworkId,
Meta = new List<InformationResponse>(),
Aliases = client.AliasLink.Children
Expand All @@ -90,13 +92,13 @@ public async Task<IActionResult> ProfileAsync(int id, MetaType? metaFilterType,
.Distinct()
.OrderBy(a => a)
.ToList(),
IPs = client.AliasLink.Children
IPs = PermissionsSet.HasPermission(WebfrontEntity.IPAddress, WebfrontPermission.Read) ? client.AliasLink.Children
.Where(i => i.IPAddress != null)
.OrderByDescending(i => i.DateAdded)
.Select(i => i.IPAddress.ConvertIPtoString())
.Prepend(client.CurrentAlias.IPAddress.ConvertIPtoString())
.Distinct()
.ToList(),
.ToList() : new List<string>(),
HasActivePenalty = activePenalties.Any(_penalty => _penalty.Type != EFPenalty.PenaltyType.Flag),
Online = Manager.GetActiveClients().FirstOrDefault(c => c.ClientId == client.ClientId) != null,
TimeOnline = (DateTime.UtcNow - client.LastConnection).HumanizeForCurrentCulture(),
Expand Down Expand Up @@ -191,7 +193,7 @@ public async Task<IActionResult> FindAsync(string clientName)
return View("Find/Index", clientsDto);
}

public async Task<IActionResult> Meta(int id, int count, int offset, long? startAt, MetaType? metaFilterType, CancellationToken token)
public IActionResult Meta(int id, int count, int offset, long? startAt, MetaType? metaFilterType, CancellationToken token)
{
var request = new ClientPaginationRequest
{
Expand All @@ -201,14 +203,15 @@ public async Task<IActionResult> Meta(int id, int count, int offset, long? start
Before = DateTime.FromFileTimeUtc(startAt ?? DateTime.UtcNow.ToFileTimeUtc())
};

var meta = await ProfileMetaListViewComponent.GetClientMeta(_metaService, metaFilterType, Client.Level, request, token);

if (!meta.Any())
return ViewComponent(typeof(ProfileMetaListViewComponent), new
{
return Ok();
}

return View("Components/ProfileMetaList/_List", meta);
clientId = request.ClientId,
count = request.Count,
offset = request.Offset,
startAt = request.Before,
metaType = metaFilterType,
token
});
}
}
}
15 changes: 15 additions & 0 deletions WebfrontCore/Permissions/WebfrontEntity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace WebfrontCore.Permissions;

public enum WebfrontEntity
{
IPAddress,
MetaAliasUpdate
}

public enum WebfrontPermission
{
Read,
Create,
Update,
Delete
}
54 changes: 29 additions & 25 deletions WebfrontCore/ViewComponents/ProfileMetaListViewComponent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,21 @@
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using SharedLibraryCore;
using SharedLibraryCore.Configuration;
using WebfrontCore.Permissions;

namespace WebfrontCore.ViewComponents
{
public class ProfileMetaListViewComponent : ViewComponent
{
private readonly IMetaServiceV2 _metaService;
private readonly ApplicationConfiguration _appConfig;

public ProfileMetaListViewComponent(IMetaServiceV2 metaService)
public ProfileMetaListViewComponent(IMetaServiceV2 metaService, ApplicationConfiguration appConfig)
{
_metaService = metaService;
_appConfig = appConfig;
}

public async Task<IViewComponentResult> InvokeAsync(int clientId, int count, int offset, DateTime? startAt, MetaType? metaType, CancellationToken token)
Expand All @@ -39,42 +44,41 @@ public async Task<IViewComponentResult> InvokeAsync(int clientId, int count, int
return View("_List", meta);
}

public static async Task<IEnumerable<IClientMeta>> GetClientMeta(IMetaServiceV2 metaService, MetaType? metaType,
private async Task<IEnumerable<IClientMeta>> GetClientMeta(IMetaServiceV2 metaService, MetaType? metaType,
EFClient.Permission level, ClientPaginationRequest request, CancellationToken token)
{
IEnumerable<IClientMeta> meta = null;

if (!_appConfig.PermissionSets.TryGetValue(level.ToString(), out var permissionSet))
{
permissionSet = new List<string>();
}

if (metaType is null or MetaType.All)
{
meta = await metaService.GetRuntimeMeta(request, token);
}

else
{
switch (metaType)
meta = metaType switch
{
case MetaType.Information:
meta = await metaService.GetRuntimeMeta<InformationResponse>(request, metaType.Value, token);
break;
case MetaType.AliasUpdate:
meta = await metaService.GetRuntimeMeta<UpdatedAliasResponse>(request, metaType.Value, token);
break;
case MetaType.ChatMessage:
meta = await metaService.GetRuntimeMeta<MessageResponse>(request, metaType.Value, token);
break;
case MetaType.Penalized:
meta = await metaService.GetRuntimeMeta<AdministeredPenaltyResponse>(request, metaType.Value, token);
break;
case MetaType.ReceivedPenalty:
meta = await metaService.GetRuntimeMeta<ReceivedPenaltyResponse>(request, metaType.Value, token);
break;
case MetaType.ConnectionHistory:
meta = await metaService.GetRuntimeMeta<ConnectionHistoryResponse>(request, metaType.Value, token);
break;
case MetaType.PermissionLevel:
meta = await metaService.GetRuntimeMeta<PermissionLevelChangedResponse>(request, metaType.Value, token);
break;
}
MetaType.Information => await metaService.GetRuntimeMeta<InformationResponse>(request,
metaType.Value, token),
MetaType.AliasUpdate => permissionSet.HasPermission(WebfrontEntity.MetaAliasUpdate, WebfrontPermission.Read) ? await metaService.GetRuntimeMeta<UpdatedAliasResponse>(request,
metaType.Value, token) : new List<IClientMeta>(),
MetaType.ChatMessage => await metaService.GetRuntimeMeta<MessageResponse>(request, metaType.Value,
token),
MetaType.Penalized => await metaService.GetRuntimeMeta<AdministeredPenaltyResponse>(request,
metaType.Value, token),
MetaType.ReceivedPenalty => await metaService.GetRuntimeMeta<ReceivedPenaltyResponse>(request,
metaType.Value, token),
MetaType.ConnectionHistory => await metaService.GetRuntimeMeta<ConnectionHistoryResponse>(request,
metaType.Value, token),
MetaType.PermissionLevel => await metaService.GetRuntimeMeta<PermissionLevelChangedResponse>(
request, metaType.Value, token),
_ => meta
};
}

if (level < EFClient.Permission.Trusted)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
@using SharedLibraryCore.Dtos.Meta.Responses
@using SharedLibraryCore
@model UpdatedAliasResponse

@foreach (var token in Utilities.SplitTranslationTokens("WEBFRONT_PROFILE_META_CONNECT_ALIAS"))
Expand Down

0 comments on commit 91a0534

Please sign in to comment.