Implemented new permission and identity system

This commit is contained in:
Marcel Baumgartner
2023-07-17 00:48:27 +02:00
parent 74d4ee729d
commit 0a86aa8aa4
86 changed files with 2372 additions and 2107 deletions

View File

@@ -24,7 +24,7 @@ public class BillingController : Controller
[HttpGet("cancel")]
public async Task<ActionResult> Cancel()
{
var user = await IdentityService.Get();
var user = IdentityService.User;
if (user == null)
return Redirect("/login");
@@ -35,7 +35,7 @@ public class BillingController : Controller
[HttpGet("success")]
public async Task<ActionResult> Success()
{
var user = await IdentityService.Get();
var user = IdentityService.User;
if (user == null)
return Redirect("/login");

View File

@@ -25,7 +25,7 @@ public class RegisterController : Controller
[HttpGet]
public async Task<ActionResult<TokenRegister>> Register()
{
var user = await IdentityService.Get();
var user = IdentityService.User;
if (user == null)
return NotFound();

View File

@@ -54,7 +54,7 @@ public class OAuth2Controller : Controller
{
try
{
var currentUser = await IdentityService.Get();
var currentUser = IdentityService.User;
if (currentUser != null)
{

View File

@@ -5,106 +5,379 @@ public static class Permissions
public static Permission AdminDashboard = new()
{
Index = 0,
Name = "Admin dashboard",
Description = "See basic information about growth and status of the moonlight instance"
Name = "Admin Dashboard",
Description = "Access the main admin dashboard page"
};
public static Permission SystemDashboard = new()
public static Permission AdminStatistics = new()
{
Index = 1,
Name = "System information",
Description = "See information about the moonlight instance like the uptime and memory usage"
Name = "Admin Statistics",
Description = "View statistical information about the moonlight instance"
};
public static Permission SystemSentry = new()
{
Index = 2,
Name = "Settings for Sentry",
Description = "See information about the sentry status"
};
public static Permission SystemMalware = new()
{
Index = 3,
Name = "Server malware scanner",
Description = "Scan running servers for malware"
};
public static Permission SystemSecurity = new()
public static Permission AdminDomains = new()
{
Index = 4,
Name = "System security settings",
Description = "Ban ip addresses and view the security logs"
Name = "Admin Domains",
Description = "Manage domains in the admin area"
};
public static Permission SystemResources = new()
public static Permission AdminNewDomain = new()
{
Index = 5,
Name = "Resources",
Description = "Read and write moonlight resources like configuration files"
Name = "Admin New Domain",
Description = "Create a new domain in the admin area"
};
public static Permission DiscordBot = new()
public static Permission AdminSharedDomains = new()
{
Index = 6,
Name = "Discord bot actions",
Description = "Setup and remote control the discord bot if enabled"
Name = "Admin Shared Domains",
Description = "Manage shared domains in the admin area"
};
public static Permission NewsMessages = new()
public static Permission AdminNewSharedDomain = new()
{
Index = 7,
Name = "News messages",
Description = "Edit, view and delete messages for the user dashboard"
Name = "Admin New Shared Domain",
Description = "Create a new shared domain in the admin area"
};
public static Permission SystemConfiguration = new()
public static Permission AdminNodeDdos = new()
{
Index = 8,
Name = "System configuration",
Description = "Modify the moonlight configuration though the visual editor"
Name = "Admin Node DDoS",
Description = "Manage DDoS protection for nodes in the admin area"
};
public static Permission SystemMail = new()
public static Permission AdminNodeEdit = new()
{
Index = 9,
Name = "System mail settings",
Description = "Modify the mail templates and send test mails"
Name = "Admin Node Edit",
Description = "Edit node settings in the admin area"
};
public static Permission ServersOverview = new()
public static Permission AdminNodes = new()
{
Index = 10,
Name = "Servers overview",
Description = "View all servers and their owners"
Name = "Admin Node",
Description = "Access the node management page in the admin area"
};
public static Permission ServerAdminEdit = new()
public static Permission AdminNewNode = new()
{
Index = 11,
Name = "Edit servers",
Description = "View all servers and their owners"
Name = "Admin New Node",
Description = "Create a new node in the admin area"
};
public static Permission ServerManager = new()
public static Permission AdminNodeSetup = new()
{
Index = 12,
Name = "Server manager",
Description = "View all servers are currently running and stop/kill all running servers"
Name = "Admin Node Setup",
Description = "Set up a node in the admin area"
};
public static Permission ServerCleanup = new()
public static Permission AdminNodeView = new()
{
Index = 13,
Name = "Server cleanup",
Description = "View the stats about the cleanup system"
Name = "Admin Node View",
Description = "View node details in the admin area"
};
public static Permission Nodes = new()
public static Permission AdminNotificationDebugging = new()
{
Index = 14,
Name = "Nodes",
Description = "View stats about the nodes"
Name = "Admin Notification Debugging",
Description = "Manage debugging notifications in the admin area"
};
public static Permission AdminServerCleanup = new()
{
Index = 15,
Name = "Admin Server Cleanup",
Description = "Perform server cleanup tasks in the admin area"
};
public static Permission AdminServerEdit = new()
{
Index = 16,
Name = "Admin Server Edit",
Description = "Edit server settings in the admin area"
};
public static Permission AdminServers = new()
{
Index = 17,
Name = "Admin Server",
Description = "Access the server management page in the admin area"
};
public static Permission AdminServerManager = new()
{
Index = 18,
Name = "Admin Server Manager",
Description = "Manage servers in the admin area"
};
public static Permission AdminNewServer = new()
{
Index = 19,
Name = "Admin New Server",
Description = "Create a new server in the admin area"
};
public static Permission AdminServerImageEdit = new()
{
Index = 20,
Name = "Admin Server Image Edit",
Description = "Edit server image settings in the admin area"
};
public static Permission AdminServerImageIndex = new()
{
Index = 21,
Name = "Admin Server Image",
Description = "Access the server image management page in the admin area"
};
public static Permission AdminServerImageNew = new()
{
Index = 22,
Name = "Admin Server Image New",
Description = "Create a new server image in the admin area"
};
public static Permission AdminServerViewAllocations = new()
{
Index = 23,
Name = "Admin Server View Allocations",
Description = "View server allocations in the admin area"
};
public static Permission AdminServerViewArchive = new()
{
Index = 24,
Name = "Admin Server View Archive",
Description = "View server archive in the admin area"
};
public static Permission AdminServerViewDebug = new()
{
Index = 25,
Name = "Admin Server View Debug",
Description = "View server debugging information in the admin area"
};
public static Permission AdminServerViewImage = new()
{
Index = 26,
Name = "Admin Server View Image",
Description = "View server image details in the admin area"
};
public static Permission AdminServerViewIndex = new()
{
Index = 27,
Name = "Admin Server View",
Description = "Access the server view page in the admin area"
};
public static Permission AdminServerViewOverview = new()
{
Index = 28,
Name = "Admin Server View Overview",
Description = "View server overview in the admin area"
};
public static Permission AdminServerViewResources = new()
{
Index = 29,
Name = "Admin Server View Resources",
Description = "View server resources in the admin area"
};
public static Permission AdminSubscriptionEdit = new()
{
Index = 30,
Name = "Admin Subscription Edit",
Description = "Edit subscription settings in the admin area"
};
public static Permission AdminSubscriptions = new()
{
Index = 31,
Name = "Admin Subscriptions",
Description = "Access the subscription management page in the admin area"
};
public static Permission AdminNewSubscription = new()
{
Index = 32,
Name = "Admin New Subscription",
Description = "Create a new subscription in the admin area"
};
public static Permission AdminSupport = new()
{
Index = 33,
Name = "Admin Support",
Description = "Access the support page in the admin area"
};
public static Permission AdminSupportView = new()
{
Index = 34,
Name = "Admin Support View",
Description = "View support details in the admin area"
};
public static Permission AdminSysConfiguration = new()
{
Index = 35,
Name = "Admin system Configuration",
Description = "Access system configuration settings in the admin area"
};
public static Permission AdminSysDiscordBot = new()
{
Index = 36,
Name = "Admin system Discord Bot",
Description = "Manage Discord bot settings in the admin area"
};
public static Permission AdminSystem = new()
{
Index = 37,
Name = "Admin system",
Description = "Access the system management page in the admin area"
};
public static Permission AdminSysMail = new()
{
Index = 38,
Name = "Admin system Mail",
Description = "Manage mail settings in the admin area"
};
public static Permission AdminSysMalware = new()
{
Index = 39,
Name = "Admin system Malware",
Description = "Manage malware settings in the admin area"
};
public static Permission AdminSysResources = new()
{
Index = 40,
Name = "Admin system Resources",
Description = "View system resources in the admin area"
};
public static Permission AdminSysSecurity = new()
{
Index = 41,
Name = "Admin system Security",
Description = "Manage security settings in the admin area"
};
public static Permission AdminSysSentry = new()
{
Index = 42,
Name = "Admin system Sentry",
Description = "Manage Sentry settings in the admin area"
};
public static Permission AdminSysNewsEdit = new()
{
Index = 43,
Name = "Admin system News Edit",
Description = "Edit system news in the admin area"
};
public static Permission AdminSysNews = new()
{
Index = 44,
Name = "Admin system News",
Description = "Access the system news management page in the admin area"
};
public static Permission AdminSysNewsNew = new()
{
Index = 45,
Name = "Admin system News New",
Description = "Create new system news in the admin area"
};
public static Permission AdminUserEdit = new()
{
Index = 46,
Name = "Admin User Edit",
Description = "Edit user settings in the admin area"
};
public static Permission AdminUsers = new()
{
Index = 47,
Name = "Admin Users",
Description = "Access the user management page in the admin area"
};
public static Permission AdminNewUser = new()
{
Index = 48,
Name = "Admin New User",
Description = "Create a new user in the admin area"
};
public static Permission AdminUserSessions = new()
{
Index = 49,
Name = "Admin User Sessions",
Description = "View user sessions in the admin area"
};
public static Permission AdminUserView = new()
{
Index = 50,
Name = "Admin User View",
Description = "View user details in the admin area"
};
public static Permission AdminWebspaces = new()
{
Index = 51,
Name = "Admin Webspaces",
Description = "Access the webspaces management page in the admin area"
};
public static Permission AdminNewWebspace = new()
{
Index = 52,
Name = "Admin New Webspace",
Description = "Create a new webspace in the admin area"
};
public static Permission AdminWebspacesServerEdit = new()
{
Index = 53,
Name = "Admin Webspaces Server Edit",
Description = "Edit webspace server settings in the admin area"
};
public static Permission AdminWebspacesServers = new()
{
Index = 54,
Name = "Admin Webspaces Servers",
Description = "Access the webspace server management page in the admin area"
};
public static Permission AdminWebspacesServerNew = new()
{
Index = 55,
Name = "Admin Webspaces Server New",
Description = "Create a new webspace server in the admin area"
};
public static Permission? FromString(string name)

View File

@@ -39,7 +39,7 @@ public class RatingService
if (!Enabled)
return false;
var user = await IdentityService.Get();
var user = IdentityService.User;
if (user == null)
return false;
@@ -62,7 +62,7 @@ public class RatingService
public async Task<bool> Rate(int rate)
{
var user = await IdentityService.Get();
var user = IdentityService.User;
// Double check states:

View File

@@ -5,7 +5,6 @@ using JWT.Exceptions;
using Microsoft.EntityFrameworkCore;
using Moonlight.App.Database.Entities;
using Moonlight.App.Helpers;
using Moonlight.App.Models.Misc;
using Moonlight.App.Perms;
using Moonlight.App.Repositories;
using UAParser;
@@ -19,8 +18,9 @@ public class IdentityService
private readonly IHttpContextAccessor HttpContextAccessor;
private readonly string Secret;
private User? UserCache;
public User User { get; private set; }
public string Ip { get; private set; } = "N/A";
public string Device { get; private set; } = "N/A";
public PermissionStorage Permissions { get; private set; }
public PermissionStorage UserPermissions { get; private set; }
public PermissionStorage GroupPermissions { get; private set; }
@@ -40,15 +40,17 @@ public class IdentityService
.Moonlight.Security.Token;
}
public async Task<User?> Get()
public async Task Load()
{
await LoadIp();
await LoadDevice();
await LoadUser();
}
private async Task LoadUser()
{
try
{
if (UserCache != null)
return UserCache;
ConstructPermissions();
var token = "none";
// Load token via http context if available
@@ -68,13 +70,13 @@ public class IdentityService
if (token == "none")
{
return null;
return;
}
if (string.IsNullOrEmpty(token))
return null;
return;
var json = "";
string json;
try
{
@@ -85,18 +87,18 @@ public class IdentityService
}
catch (TokenExpiredException)
{
return null;
return;
}
catch (SignatureVerificationException)
{
Logger.Warn($"Detected a manipulated JWT: {token}", "security");
return null;
return;
}
catch (Exception e)
{
Logger.Error("Error reading jwt");
Logger.Error(e);
return null;
return;
}
// To make it easier to use the json data
@@ -111,7 +113,7 @@ public class IdentityService
{
Logger.Warn(
$"Cannot find user with the id '{userid}' in the database. Maybe the user has been deleted or a token has been successfully faked by a hacker");
return null;
return;
}
var iat = data.GetValue<long>("iat", -1);
@@ -119,48 +121,54 @@ public class IdentityService
if (iat == -1)
{
Logger.Debug("Legacy token found (without the time the token has been issued at)");
return null;
return;
}
var iatD = DateTimeOffset.FromUnixTimeSeconds(iat).ToUniversalTime().DateTime;
if (iatD < user.TokenValidTime)
return null;
return;
UserCache = user;
User = user;
ConstructPermissions();
user.LastIp = GetIp();
UserRepository.Update(user);
return UserCache;
User.LastIp = Ip;
UserRepository.Update(User);
}
catch (Exception e)
{
Logger.Error("Unexpected error while processing token");
Logger.Error(e);
return null;
return;
}
}
public string GetIp()
private Task LoadIp()
{
if (HttpContextAccessor.HttpContext == null)
return "N/A";
{
Ip = "N/A";
return Task.CompletedTask;
}
if (HttpContextAccessor.HttpContext.Request.Headers.ContainsKey("X-Real-IP"))
{
return HttpContextAccessor.HttpContext.Request.Headers["X-Real-IP"]!;
Ip = HttpContextAccessor.HttpContext.Request.Headers["X-Real-IP"]!;
return Task.CompletedTask;
}
return HttpContextAccessor.HttpContext.Connection.RemoteIpAddress!.ToString();
Ip = HttpContextAccessor.HttpContext.Connection.RemoteIpAddress!.ToString();
return Task.CompletedTask;
}
public string GetDevice()
private Task LoadDevice()
{
if (HttpContextAccessor.HttpContext == null)
return "N/A";
{
Device = "N/A";
return Task.CompletedTask;
}
try
{
@@ -170,26 +178,29 @@ public class IdentityService
{
var version = userAgent.Remove(0, "Moonlight.App/".Length).Split(' ').FirstOrDefault();
return "Moonlight App " + version;
Device = "Moonlight App " + version;
return Task.CompletedTask;
}
var uaParser = Parser.GetDefault();
var info = uaParser.Parse(userAgent);
return $"{info.OS} - {info.Device}";
Device = $"{info.OS} - {info.Device}";
return Task.CompletedTask;
}
catch (Exception e)
{
return "UserAgent not present";
Device = "UserAgent not present";
return Task.CompletedTask;
}
}
public Task SavePermissions()
{
if (UserCache != null)
if (User != null)
{
UserCache.Permissions = UserPermissions.Data;
UserRepository.Update(UserCache);
User.Permissions = UserPermissions.Data;
UserRepository.Update(User);
ConstructPermissions();
}
@@ -198,7 +209,7 @@ public class IdentityService
private void ConstructPermissions()
{
if (UserCache == null)
if (User == null)
{
UserPermissions = new(Array.Empty<byte>());
GroupPermissions = new(Array.Empty<byte>(), true);
@@ -210,7 +221,7 @@ public class IdentityService
var user = UserRepository
.Get()
.Include(x => x.PermissionGroup)
.First(x => x.Id == UserCache.Id);
.First(x => x.Id == User.Id);
UserPermissions = new PermissionStorage(user.Permissions);
@@ -219,7 +230,18 @@ public class IdentityService
else
GroupPermissions = new PermissionStorage(user.PermissionGroup.Permissions, true);
Logger.Debug($"{UserPermissions[Perms.Permissions.AdminDashboard]} {GroupPermissions[Perms.Permissions.AdminDashboard]}");
if (user.Admin)
{
Permissions = new PermissionStorage(Array.Empty<byte>());
foreach (var permission in Perms.Permissions.GetAllPermissions())
{
Permissions[permission] = true;
}
Permissions.IsReadyOnly = true;
return;
}
Permissions = new PermissionStorage(BitHelper.OverwriteByteArrays(
UserPermissions.Data,

View File

@@ -19,7 +19,7 @@ public class IpBanService
public Task<bool> IsBanned()
{
var ip = IdentityService.GetIp();
var ip = IdentityService.Ip;
return Task.FromResult(
IpBanRepository

View File

@@ -15,7 +15,7 @@ public class IpLocateService
public async Task<string> GetLocation()
{
var ip = IdentityService.GetIp();
var ip = IdentityService.Ip;
var location = "N/A";
if (ip != "N/A")

View File

@@ -40,9 +40,9 @@ public class SessionClientService
public async Task Start()
{
User = await IdentityService.Get();
Ip = IdentityService.GetIp();
Device = IdentityService.GetDevice();
User = IdentityService.User;
Ip = IdentityService.Ip;
Device = IdentityService.Device;
if (User != null) // Track users last visit
{

View File

@@ -34,7 +34,7 @@ public class SupportChatAdminService : IDisposable
public async Task Start(User recipient)
{
User = await IdentityService.Get();
User = IdentityService.User;
Recipient = recipient;
if (User != null)

View File

@@ -33,7 +33,7 @@ public class SupportChatClientService : IDisposable
public async Task Start()
{
User = await IdentityService.Get();
User = IdentityService.User;
if (User != null)
{

View File

@@ -25,32 +25,30 @@ public class TotpService
return Task.FromResult(codeserver == code);
}
public async Task<bool> GetEnabled()
public Task<bool> GetEnabled()
{
var user = await IdentityService.Get();
return user!.TotpEnabled;
return Task.FromResult(IdentityService.User.TotpEnabled);
}
public async Task<string> GetSecret()
public Task<string> GetSecret()
{
var user = await IdentityService.Get();
return user!.TotpSecret;
return Task.FromResult(IdentityService.User.TotpSecret);
}
public async Task GenerateSecret()
public Task GenerateSecret()
{
var user = (await IdentityService.Get())!;
var user = IdentityService.User;
user.TotpSecret = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(20));;
UserRepository.Update(user);
return Task.CompletedTask;
}
public async Task Enable(string code)
{
var user = (await IdentityService.Get())!;
var user = IdentityService.User;
if (!await Verify(user.TotpSecret, code))
{
@@ -61,9 +59,9 @@ public class TotpService
UserRepository.Update(user);
}
public async Task Disable()
public Task Disable()
{
var user = (await IdentityService.Get())!;
var user = IdentityService.User;
user.TotpEnabled = false;
user.TotpSecret = "";
@@ -71,5 +69,7 @@ public class TotpService
UserRepository.Update(user);
//TODO: AuditLog
return Task.CompletedTask;
}
}

View File

@@ -85,8 +85,8 @@ public class UserService
TotpSecret = "",
UpdatedAt = DateTimeService.GetCurrent(),
TokenValidTime = DateTimeService.GetCurrent().AddDays(-5),
LastIp = IdentityService.GetIp(),
RegisterIp = IdentityService.GetIp()
LastIp = IdentityService.Ip,
RegisterIp = IdentityService.Ip
});
await MailService.SendMail(user!, "register", values => {});
@@ -174,8 +174,8 @@ public class UserService
await MailService.SendMail(user!, "passwordChange", values =>
{
values.Add("Ip", IdentityService.GetIp());
values.Add("Device", IdentityService.GetDevice());
values.Add("Ip", IdentityService.Ip);
values.Add("Device", IdentityService.Device);
values.Add("Location", location);
});
@@ -212,8 +212,8 @@ public class UserService
{
await MailService.SendMail(user!, "login", values =>
{
values.Add("Ip", IdentityService.GetIp());
values.Add("Device", IdentityService.GetDevice());
values.Add("Ip", IdentityService.Ip);
values.Add("Device", IdentityService.Device);
values.Add("Location", location);
});
}
@@ -249,8 +249,8 @@ public class UserService
await MailService.SendMail(user, "passwordReset", values =>
{
values.Add("Ip", IdentityService.GetIp());
values.Add("Device", IdentityService.GetDevice());
values.Add("Ip", IdentityService.Ip);
values.Add("Device", IdentityService.Device);
values.Add("Location", location);
values.Add("Password", newPassword);
});