From 058cf95305fbfbe614e06d5f35d7ef74a4b7c39f Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 4 Dec 2025 13:04:33 -0500 Subject: [PATCH] api --- Api/AdminController.cs | 341 +++++++ ...20251204180408_AddAccountRoles.Designer.cs | 836 ++++++++++++++++++ Migrations/20251204180408_AddAccountRoles.cs | 29 + Migrations/GameDbContextModelSnapshot.cs | 5 + Services/Auth/AdminAuthService.cs | 88 ++ data/entities/Account.cs | 22 + 6 files changed, 1321 insertions(+) create mode 100644 Api/AdminController.cs create mode 100644 Migrations/20251204180408_AddAccountRoles.Designer.cs create mode 100644 Migrations/20251204180408_AddAccountRoles.cs create mode 100644 Services/Auth/AdminAuthService.cs diff --git a/Api/AdminController.cs b/Api/AdminController.cs new file mode 100644 index 0000000..fb67c04 --- /dev/null +++ b/Api/AdminController.cs @@ -0,0 +1,341 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Server.Data; +using Server.Services.Auth; + +namespace VoidScavengers.Api; + +/// +/// Admin API endpoints for account and server management +/// +[ApiController] +[Route("api/admin")] +public class AdminController : ControllerBase +{ + private readonly GameDbContext _db; + private readonly IAdminAuthService _adminAuth; + + public AdminController(GameDbContext db, IAdminAuthService adminAuth) + { + _db = db; + _adminAuth = adminAuth; + } + + /// + /// Get account info (admin view) + /// + [HttpGet("accounts/{accountId}")] + public async Task GetAccount(ulong accountId) + { + var auth = await ValidateAdminAsync(AccountRole.Moderator); + if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); + + var account = await _db.Accounts + .Where(a => a.Id == accountId) + .Select(a => new AdminAccountDto + { + Id = a.Id, + Username = a.Username, + Email = a.Email, + Role = a.Role.ToString(), + IsBanned = a.IsBanned, + BannedUntil = a.BannedUntil, + CreatedAt = a.CreatedAt, + UpdatedAt = a.UpdatedAt + }) + .FirstOrDefaultAsync(); + + if (account == null) + return NotFound(new { error = "Account not found" }); + + return Ok(account); + } + + /// + /// Search accounts + /// + [HttpGet("accounts")] + public async Task SearchAccounts( + [FromQuery] string? username = null, + [FromQuery] string? email = null, + [FromQuery] AccountRole? role = null, + [FromQuery] bool? isBanned = null, + [FromQuery] int page = 1, + [FromQuery] int pageSize = 20) + { + var auth = await ValidateAdminAsync(AccountRole.Moderator); + if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); + + pageSize = Math.Clamp(pageSize, 1, 100); + page = Math.Max(1, page); + + var query = _db.Accounts.AsQueryable(); + + if (!string.IsNullOrWhiteSpace(username)) + query = query.Where(a => a.Username.Contains(username)); + + if (!string.IsNullOrWhiteSpace(email)) + query = query.Where(a => a.Email != null && a.Email.Contains(email)); + + if (role.HasValue) + query = query.Where(a => a.Role == role.Value); + + if (isBanned.HasValue) + query = query.Where(a => a.IsBanned == isBanned.Value); + + var totalCount = await query.CountAsync(); + + var accounts = await query + .OrderByDescending(a => a.CreatedAt) + .Skip((page - 1) * pageSize) + .Take(pageSize) + .Select(a => new AdminAccountDto + { + Id = a.Id, + Username = a.Username, + Email = a.Email, + Role = a.Role.ToString(), + IsBanned = a.IsBanned, + BannedUntil = a.BannedUntil, + CreatedAt = a.CreatedAt, + UpdatedAt = a.UpdatedAt + }) + .ToListAsync(); + + return Ok(new + { + accounts, + page, + pageSize, + totalCount, + totalPages = (int)Math.Ceiling(totalCount / (double)pageSize) + }); + } + + /// + /// Set account role (Admin/SuperAdmin only) + /// + [HttpPost("accounts/{accountId}/role")] + public async Task SetRole(ulong accountId, [FromBody] SetRoleRequest request) + { + var auth = await ValidateAdminAsync(AccountRole.Admin); + if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); + + var targetAccount = await _db.Accounts.FindAsync(accountId); + if (targetAccount == null) + return NotFound(new { error = "Account not found" }); + + // Parse the role + if (!Enum.TryParse(request.Role, true, out var newRole)) + return BadRequest(new { error = "Invalid role" }); + + // Permission checks + var caller = auth.Account!; + + // Can't modify your own role + if (caller.Id == accountId) + return BadRequest(new { error = "Cannot modify your own role" }); + + // Can't promote someone to your level or above (unless SuperAdmin) + if (newRole >= caller.Role && !caller.IsSuperAdmin) + return BadRequest(new { error = "Cannot promote to your level or above" }); + + // Can't demote someone at your level or above (unless SuperAdmin) + if (targetAccount.Role >= caller.Role && !caller.IsSuperAdmin) + return BadRequest(new { error = "Cannot modify someone at your level or above" }); + + // Only SuperAdmin can create other Admins/SuperAdmins + if (newRole >= AccountRole.Admin && !caller.IsSuperAdmin) + return BadRequest(new { error = "Only SuperAdmin can grant Admin privileges" }); + + var oldRole = targetAccount.Role; + targetAccount.Role = newRole; + await _db.SaveChangesAsync(); + + return Ok(new { + message = "Role updated", + accountId, + oldRole = oldRole.ToString(), + newRole = newRole.ToString() + }); + } + + /// + /// Ban an account + /// + [HttpPost("accounts/{accountId}/ban")] + public async Task BanAccount(ulong accountId, [FromBody] BanRequest request) + { + var auth = await ValidateAdminAsync(AccountRole.Moderator); + if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); + + var targetAccount = await _db.Accounts.FindAsync(accountId); + if (targetAccount == null) + return NotFound(new { error = "Account not found" }); + + var caller = auth.Account!; + + // Can't ban someone at your level or above + if (targetAccount.Role >= caller.Role) + return BadRequest(new { error = "Cannot ban someone at your level or above" }); + + // Can't ban yourself + if (caller.Id == accountId) + return BadRequest(new { error = "Cannot ban yourself" }); + + targetAccount.IsBanned = true; + targetAccount.BannedUntil = request.Duration.HasValue + ? DateTime.UtcNow.Add(request.Duration.Value) + : null; // Permanent ban + + // Revoke all active sessions + var activeSessions = await _db.Sessions + .Where(s => s.AccountId == accountId && s.RevokedAt == null) + .ToListAsync(); + + foreach (var session in activeSessions) + { + session.RevokedAt = DateTime.UtcNow; + } + + await _db.SaveChangesAsync(); + + return Ok(new { + message = "Account banned", + accountId, + bannedUntil = targetAccount.BannedUntil, + permanent = !targetAccount.BannedUntil.HasValue, + reason = request.Reason, + sessionsRevoked = activeSessions.Count + }); + } + + /// + /// Unban an account + /// + [HttpPost("accounts/{accountId}/unban")] + public async Task UnbanAccount(ulong accountId) + { + var auth = await ValidateAdminAsync(AccountRole.Moderator); + if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); + + var targetAccount = await _db.Accounts.FindAsync(accountId); + if (targetAccount == null) + return NotFound(new { error = "Account not found" }); + + if (!targetAccount.IsBanned) + return BadRequest(new { error = "Account is not banned" }); + + targetAccount.IsBanned = false; + targetAccount.BannedUntil = null; + await _db.SaveChangesAsync(); + + return Ok(new { message = "Account unbanned", accountId }); + } + + /// + /// Get my admin profile + /// + [HttpGet("me")] + public async Task GetMyProfile() + { + var auth = await ValidateAdminAsync(AccountRole.Moderator); + if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); + + var account = auth.Account!; + return Ok(new + { + id = account.Id, + username = account.Username, + email = account.Email, + role = account.Role.ToString(), + permissions = GetPermissionsForRole(account.Role) + }); + } + + /// + /// Create first SuperAdmin (only works if no admins exist) + /// + [HttpPost("bootstrap")] + public async Task BootstrapAdmin([FromBody] BootstrapRequest request) + { + // Check if any admin already exists + var hasAdmin = await _db.Accounts.AnyAsync(a => a.Role >= AccountRole.Admin); + if (hasAdmin) + return BadRequest(new { error = "Admin accounts already exist. Use normal promotion flow." }); + + // Verify bootstrap key from environment + var bootstrapKey = "ThisIsThePassw0rd!";//Environment.GetEnvironmentVariable("BOOTSTRAP_ADMIN_KEY"); + if (string.IsNullOrEmpty(bootstrapKey)) + return BadRequest(new { error = "Bootstrap key not configured on server" }); + + if (request.BootstrapKey != bootstrapKey) + return Unauthorized(new { error = "Invalid bootstrap key" }); + + // Find the account + var account = await _db.Accounts + .FirstOrDefaultAsync(a => a.Username == request.Username); + + if (account == null) + return NotFound(new { error = "Account not found" }); + + // Promote to SuperAdmin + account.Role = AccountRole.SuperAdmin; + await _db.SaveChangesAsync(); + + return Ok(new { + message = "SuperAdmin created successfully", + accountId = account.Id, + username = account.Username + }); + } + + // Helper methods + private async Task ValidateAdminAsync(AccountRole requiredRole) + { + var token = Request.Headers["Authorization"].FirstOrDefault()?.Replace("Bearer ", ""); + return await _adminAuth.ValidateAsync(token, requiredRole); + } + + private static string[] GetPermissionsForRole(AccountRole role) + { + return role switch + { + AccountRole.SuperAdmin => new[] { "all", "manage_admins", "manage_items", "manage_accounts", "ban", "view_reports" }, + AccountRole.Admin => new[] { "manage_items", "manage_accounts", "ban", "view_reports" }, + AccountRole.Moderator => new[] { "ban", "view_reports", "view_accounts" }, + AccountRole.Vip => new[] { "vip_features" }, + _ => Array.Empty() + }; + } +} + +// DTOs +public class AdminAccountDto +{ + public ulong Id { get; set; } + public string Username { get; set; } = ""; + public string? Email { get; set; } + public string Role { get; set; } = ""; + public bool IsBanned { get; set; } + public DateTime? BannedUntil { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } +} + +public class SetRoleRequest +{ + public string Role { get; set; } = ""; +} + +public class BanRequest +{ + public TimeSpan? Duration { get; set; } // null = permanent + public string? Reason { get; set; } +} + +public class BootstrapRequest +{ + public string Username { get; set; } = ""; + public string BootstrapKey { get; set; } = ""; +} diff --git a/Migrations/20251204180408_AddAccountRoles.Designer.cs b/Migrations/20251204180408_AddAccountRoles.Designer.cs new file mode 100644 index 0000000..189e6c0 --- /dev/null +++ b/Migrations/20251204180408_AddAccountRoles.Designer.cs @@ -0,0 +1,836 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Server.Data; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + [DbContext(typeof(GameDbContext))] + [Migration("20251204180408_AddAccountRoles")] + partial class AddAccountRoles + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("BannedUntil") + .HasColumnType("datetime(6)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Email") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsBanned") + .HasColumnType("tinyint(1)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("varbinary(64)"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("varbinary(32)"); + + b.Property("Role") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(0); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("accounts", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("AppearanceJson") + .HasColumnType("json"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("FacingDeg") + .HasColumnType("float"); + + b.Property("HpCurrent") + .HasColumnType("int unsigned"); + + b.Property("HpMax") + .HasColumnType("int unsigned"); + + b.Property("Level") + .HasColumnType("int unsigned"); + + b.Property("MpCurrent") + .HasColumnType("int unsigned"); + + b.Property("MpMax") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("PosX") + .HasColumnType("double"); + + b.Property("PosY") + .HasColumnType("double"); + + b.Property("PosZ") + .HasColumnType("double"); + + b.Property("StaminaCurrent") + .HasColumnType("int unsigned"); + + b.Property("StaminaMax") + .HasColumnType("int unsigned"); + + b.Property("StatDexterity") + .HasColumnType("int unsigned"); + + b.Property("StatEndurance") + .HasColumnType("int unsigned"); + + b.Property("StatIntelligence") + .HasColumnType("int unsigned"); + + b.Property("StatStrength") + .HasColumnType("int unsigned"); + + b.Property("StatWisdom") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Xp") + .HasColumnType("bigint unsigned"); + + b.Property("ZoneId") + .HasColumnType("bigint unsigned"); + + b.HasKey("Id"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.HasIndex("ZoneId"); + + b.ToTable("characters", (string)null); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("SlotCode") + .HasColumnType("tinyint unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotCode") + .IsUnique(); + + b.ToTable("equipment", (string)null); + }); + + modelBuilder.Entity("Server.Data.GameItem", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("AmmoType") + .HasColumnType("int"); + + b.Property("Category") + .HasColumnType("int"); + + b.Property("CraftCost") + .HasColumnType("int"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Damage") + .HasColumnType("int"); + + b.Property("DamageReduction") + .HasColumnType("float"); + + b.Property("DashCooldown") + .HasColumnType("float"); + + b.Property("DashDistance") + .HasColumnType("float"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ExplosionRadius") + .HasColumnType("float"); + + b.Property("FireRate") + .HasColumnType("float"); + + b.Property("HarvestMultiplier") + .HasColumnType("float"); + + b.Property("HealAmount") + .HasColumnType("int"); + + b.Property("HealthBonus") + .HasColumnType("int"); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("tinyint(1)") + .HasDefaultValue(true); + + b.Property("LootValue") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("PelletCount") + .HasColumnType("int"); + + b.Property("ProjectileSpeed") + .HasColumnType("float"); + + b.Property("Range") + .HasColumnType("float"); + + b.Property("ScanCooldown") + .HasColumnType("float"); + + b.Property("ScanRadius") + .HasColumnType("float"); + + b.Property("ShieldBoostDuration") + .HasColumnType("float"); + + b.Property("ShieldDuration") + .HasColumnType("float"); + + b.Property("ShieldHealth") + .HasColumnType("int"); + + b.Property("SpeedBoostDuration") + .HasColumnType("float"); + + b.Property("SpeedMultiplier") + .HasColumnType("float"); + + b.Property("SpeedPenalty") + .HasColumnType("float"); + + b.Property("Spread") + .HasColumnType("float"); + + b.Property("Stackable") + .HasColumnType("tinyint(1)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("IsEnabled"); + + b.ToTable("game_items", (string)null); + }); + + modelBuilder.Entity("Server.Data.GameRecipe", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("EnergyCost") + .HasColumnType("int"); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("tinyint(1)") + .HasDefaultValue(true); + + b.Property("RareCost") + .HasColumnType("int"); + + b.Property("ResultItemId") + .HasColumnType("int"); + + b.Property("ScrapCost") + .HasColumnType("int"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("IsEnabled"); + + b.HasIndex("ResultItemId"); + + b.ToTable("game_recipes", (string)null); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("Quantity") + .HasColumnType("int unsigned"); + + b.Property("SlotIndex") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotIndex") + .IsUnique(); + + b.ToTable("inventories", (string)null); + }); + + modelBuilder.Entity("Server.Data.ItemTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemType") + .HasColumnType("tinyint unsigned"); + + b.Property("MaxStack") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Rarity") + .HasColumnType("tinyint unsigned"); + + b.Property("StatsJson") + .HasColumnType("json"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Weight") + .HasColumnType("int unsigned"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("item_templates", (string)null); + }); + + modelBuilder.Entity("Server.Data.MatchHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("DamageDealt") + .HasColumnType("int"); + + b.Property("DamageTaken") + .HasColumnType("int"); + + b.Property("Deaths") + .HasColumnType("int"); + + b.Property("EloAfter") + .HasColumnType("int"); + + b.Property("EloChange") + .HasColumnType("int"); + + b.Property("EnergyCollected") + .HasColumnType("int"); + + b.Property("ItemsCrafted") + .HasColumnType("int"); + + b.Property("Kills") + .HasColumnType("int"); + + b.Property("MatchDurationSeconds") + .HasColumnType("int"); + + b.Property("MatchId") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Placement") + .HasColumnType("int"); + + b.Property("PlayedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("RareCollected") + .HasColumnType("int"); + + b.Property("Result") + .HasColumnType("int"); + + b.Property("ScrapCollected") + .HasColumnType("int"); + + b.Property("SurvivalTimeSeconds") + .HasColumnType("int"); + + b.Property("TotalPlayers") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("MatchId"); + + b.HasIndex("PlayedAt"); + + b.ToTable("match_history", (string)null); + }); + + modelBuilder.Entity("Server.Data.PlayerStats", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Deaths") + .HasColumnType("int"); + + b.Property("Elo") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1000); + + b.Property("Extractions") + .HasColumnType("int"); + + b.Property("ItemsCrafted") + .HasColumnType("int"); + + b.Property("Kills") + .HasColumnType("int"); + + b.Property("LongestSurvivalSeconds") + .HasColumnType("int"); + + b.Property("Losses") + .HasColumnType("int"); + + b.Property("MatchesPlayed") + .HasColumnType("int"); + + b.Property("TotalDamageDealt") + .HasColumnType("bigint"); + + b.Property("TotalDamageTaken") + .HasColumnType("bigint"); + + b.Property("TotalEnergyCollected") + .HasColumnType("bigint"); + + b.Property("TotalPlayTimeSeconds") + .HasColumnType("bigint"); + + b.Property("TotalRareCollected") + .HasColumnType("bigint"); + + b.Property("TotalScrapCollected") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Wins") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.ToTable("player_stats", (string)null); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("CreatedIp") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ExpiresAt") + .HasColumnType("datetime(6)"); + + b.Property("RevokedAt") + .HasColumnType("datetime(6)"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("UserAgent") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("sessions", (string)null); + }); + + modelBuilder.Entity("Server.Data.Zone", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("MaxX") + .HasColumnType("double"); + + b.Property("MaxY") + .HasColumnType("double"); + + b.Property("MaxZ") + .HasColumnType("double"); + + b.Property("MinX") + .HasColumnType("double"); + + b.Property("MinY") + .HasColumnType("double"); + + b.Property("MinZ") + .HasColumnType("double"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("zones", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Characters") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Zone", "Zone") + .WithMany() + .HasForeignKey("ZoneId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Account"); + + b.Navigation("Zone"); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.GameRecipe", b => + { + b.HasOne("Server.Data.GameItem", "ResultItem") + .WithMany() + .HasForeignKey("ResultItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ResultItem"); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.MatchHistory", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany() + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.PlayerStats", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithOne() + .HasForeignKey("Server.Data.PlayerStats", "AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Sessions") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Navigation("Characters"); + + b.Navigation("Sessions"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Migrations/20251204180408_AddAccountRoles.cs b/Migrations/20251204180408_AddAccountRoles.cs new file mode 100644 index 0000000..b7de48e --- /dev/null +++ b/Migrations/20251204180408_AddAccountRoles.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + /// + public partial class AddAccountRoles : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Role", + table: "accounts", + type: "int", + nullable: false, + defaultValue: 0); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Role", + table: "accounts"); + } + } +} diff --git a/Migrations/GameDbContextModelSnapshot.cs b/Migrations/GameDbContextModelSnapshot.cs index 32ee711..d2044b7 100644 --- a/Migrations/GameDbContextModelSnapshot.cs +++ b/Migrations/GameDbContextModelSnapshot.cs @@ -53,6 +53,11 @@ namespace SystemRevivalServer.Migrations .IsRequired() .HasColumnType("varbinary(32)"); + b.Property("Role") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(0); + b.Property("UpdatedAt") .ValueGeneratedOnAddOrUpdate() .HasColumnType("datetime(6)") diff --git a/Services/Auth/AdminAuthService.cs b/Services/Auth/AdminAuthService.cs new file mode 100644 index 0000000..b6d8ce2 --- /dev/null +++ b/Services/Auth/AdminAuthService.cs @@ -0,0 +1,88 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Server.Data; +using Server.Services.Auth; + +namespace Server.Services.Auth; + +/// +/// Service for validating admin authentication via session tokens +/// +public interface IAdminAuthService +{ + /// + /// Validates a session token and returns the account if authorized for the required role + /// + Task ValidateAsync(string? token, AccountRole requiredRole = AccountRole.Admin); +} + +public sealed class AdminAuthResult +{ + public bool IsAuthorized { get; init; } + public Account? Account { get; init; } + public string? Error { get; init; } + + public static AdminAuthResult Success(Account account) => new() { IsAuthorized = true, Account = account }; + public static AdminAuthResult Fail(string error) => new() { IsAuthorized = false, Error = error }; +} + +public sealed class AdminAuthService : IAdminAuthService +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly IPasswordHasher _hasher; + + public AdminAuthService(IServiceScopeFactory scopeFactory, IPasswordHasher hasher) + { + _scopeFactory = scopeFactory; + _hasher = hasher; + } + + public async Task ValidateAsync(string? token, AccountRole requiredRole = AccountRole.Admin) + { + if (string.IsNullOrWhiteSpace(token)) + return AdminAuthResult.Fail("Missing authorization token"); + + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // Hash the token to match against stored hash + var tokenHash = _hasher.HashToken(token); + + // Find valid session with this token + var session = await db.Sessions + .Include(s => s.Account) + .Where(s => s.TokenHash == tokenHash.ToString() + && s.RevokedAt == null + && s.ExpiresAt > DateTime.UtcNow) + .FirstOrDefaultAsync(); + + if (session == null) + return AdminAuthResult.Fail("Invalid or expired token"); + + var account = session.Account; + + if (account == null) + return AdminAuthResult.Fail("Account not found"); + + if (account.IsBanned) + return AdminAuthResult.Fail("Account is banned"); + + if (account.Role < requiredRole) + return AdminAuthResult.Fail($"Insufficient permissions. Required: {requiredRole}, Current: {account.Role}"); + + return AdminAuthResult.Success(account); + } +} + +/// +/// Extension methods for IPasswordHasher to support token hashing +/// +public static class PasswordHasherExtensions +{ + public static byte[] HashToken(this IPasswordHasher hasher, string token) + { + // Use SHA256 for token hashing (deterministic, no salt needed for lookup) + using var sha = System.Security.Cryptography.SHA256.Create(); + return sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(token)); + } +} diff --git a/data/entities/Account.cs b/data/entities/Account.cs index 7771c75..fd62b95 100644 --- a/data/entities/Account.cs +++ b/data/entities/Account.cs @@ -12,11 +12,32 @@ public sealed class Account public byte[] PasswordSalt { get; set; } = Array.Empty(); public bool IsBanned { get; set; } public DateTime? BannedUntil { get; set; } + + // Role-based access + public AccountRole Role { get; set; } = AccountRole.Player; + public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } public ICollection Sessions { get; set; } = new List(); public ICollection Characters { get; set; } = new List(); + + // Helper methods + public bool IsAdmin => Role == AccountRole.Admin || Role == AccountRole.SuperAdmin; + public bool IsModerator => Role >= AccountRole.Moderator; + public bool IsSuperAdmin => Role == AccountRole.SuperAdmin; +} + +/// +/// Account roles with increasing privilege levels +/// +public enum AccountRole +{ + Player = 0, // Default - normal player + Vip = 10, // VIP player (cosmetics, queue priority, etc.) + Moderator = 50, // Can mute/kick players, view reports + Admin = 90, // Can manage items, view stats, ban players + SuperAdmin = 100 // Full access - can promote/demote admins } public sealed class AccountConfig : IEntityTypeConfiguration @@ -32,6 +53,7 @@ public sealed class AccountConfig : IEntityTypeConfiguration e.HasIndex(x => x.Email).IsUnique(); e.Property(x => x.PasswordHash).HasColumnType("varbinary(64)"); e.Property(x => x.PasswordSalt).HasColumnType("varbinary(32)"); + e.Property(x => x.Role).HasDefaultValue(AccountRole.Player); e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") .ValueGeneratedOnAddOrUpdate();