This commit is contained in:
dingo
2025-12-04 13:04:33 -05:00
parent d66ff2af40
commit 058cf95305
6 changed files with 1321 additions and 0 deletions
+341
View File
@@ -0,0 +1,341 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Data;
using Server.Services.Auth;
namespace VoidScavengers.Api;
/// <summary>
/// Admin API endpoints for account and server management
/// </summary>
[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;
}
/// <summary>
/// Get account info (admin view)
/// </summary>
[HttpGet("accounts/{accountId}")]
public async Task<IActionResult> 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);
}
/// <summary>
/// Search accounts
/// </summary>
[HttpGet("accounts")]
public async Task<IActionResult> 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)
});
}
/// <summary>
/// Set account role (Admin/SuperAdmin only)
/// </summary>
[HttpPost("accounts/{accountId}/role")]
public async Task<IActionResult> 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<AccountRole>(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()
});
}
/// <summary>
/// Ban an account
/// </summary>
[HttpPost("accounts/{accountId}/ban")]
public async Task<IActionResult> 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
});
}
/// <summary>
/// Unban an account
/// </summary>
[HttpPost("accounts/{accountId}/unban")]
public async Task<IActionResult> 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 });
}
/// <summary>
/// Get my admin profile
/// </summary>
[HttpGet("me")]
public async Task<IActionResult> 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)
});
}
/// <summary>
/// Create first SuperAdmin (only works if no admins exist)
/// </summary>
[HttpPost("bootstrap")]
public async Task<IActionResult> 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<AdminAuthResult> 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<string>()
};
}
}
// 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; } = "";
}
+836
View File
@@ -0,0 +1,836 @@
// <auto-generated />
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
{
/// <inheritdoc />
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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime?>("BannedUntil")
.HasColumnType("datetime(6)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<string>("Email")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<bool>("IsBanned")
.HasColumnType("tinyint(1)");
b.Property<byte[]>("PasswordHash")
.IsRequired()
.HasColumnType("varbinary(64)");
b.Property<byte[]>("PasswordSalt")
.IsRequired()
.HasColumnType("varbinary(32)");
b.Property<int>("Role")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasDefaultValue(0);
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<string>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<string>("AppearanceJson")
.HasColumnType("json");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<float>("FacingDeg")
.HasColumnType("float");
b.Property<uint>("HpCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("HpMax")
.HasColumnType("int unsigned");
b.Property<uint>("Level")
.HasColumnType("int unsigned");
b.Property<uint>("MpCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("MpMax")
.HasColumnType("int unsigned");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("varchar(32)");
b.Property<double>("PosX")
.HasColumnType("double");
b.Property<double>("PosY")
.HasColumnType("double");
b.Property<double>("PosZ")
.HasColumnType("double");
b.Property<uint>("StaminaCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("StaminaMax")
.HasColumnType("int unsigned");
b.Property<uint>("StatDexterity")
.HasColumnType("int unsigned");
b.Property<uint>("StatEndurance")
.HasColumnType("int unsigned");
b.Property<uint>("StatIntelligence")
.HasColumnType("int unsigned");
b.Property<uint>("StatStrength")
.HasColumnType("int unsigned");
b.Property<uint>("StatWisdom")
.HasColumnType("int unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<ulong>("Xp")
.HasColumnType("bigint unsigned");
b.Property<ulong>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("CharacterId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<ulong>("ItemTemplateId")
.HasColumnType("bigint unsigned");
b.Property<byte>("SlotCode")
.HasColumnType("tinyint unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("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<int>("Id")
.HasColumnType("int");
b.Property<int>("AmmoType")
.HasColumnType("int");
b.Property<int>("Category")
.HasColumnType("int");
b.Property<int>("CraftCost")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<int>("Damage")
.HasColumnType("int");
b.Property<float>("DamageReduction")
.HasColumnType("float");
b.Property<float>("DashCooldown")
.HasColumnType("float");
b.Property<float>("DashDistance")
.HasColumnType("float");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<float>("ExplosionRadius")
.HasColumnType("float");
b.Property<float>("FireRate")
.HasColumnType("float");
b.Property<float>("HarvestMultiplier")
.HasColumnType("float");
b.Property<int>("HealAmount")
.HasColumnType("int");
b.Property<int>("HealthBonus")
.HasColumnType("int");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("tinyint(1)")
.HasDefaultValue(true);
b.Property<int>("LootValue")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<int>("PelletCount")
.HasColumnType("int");
b.Property<float>("ProjectileSpeed")
.HasColumnType("float");
b.Property<float>("Range")
.HasColumnType("float");
b.Property<float>("ScanCooldown")
.HasColumnType("float");
b.Property<float>("ScanRadius")
.HasColumnType("float");
b.Property<float>("ShieldBoostDuration")
.HasColumnType("float");
b.Property<float>("ShieldDuration")
.HasColumnType("float");
b.Property<int>("ShieldHealth")
.HasColumnType("int");
b.Property<float>("SpeedBoostDuration")
.HasColumnType("float");
b.Property<float>("SpeedMultiplier")
.HasColumnType("float");
b.Property<float>("SpeedPenalty")
.HasColumnType("float");
b.Property<float>("Spread")
.HasColumnType("float");
b.Property<bool>("Stackable")
.HasColumnType("tinyint(1)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("Category");
b.HasIndex("IsEnabled");
b.ToTable("game_items", (string)null);
});
modelBuilder.Entity("Server.Data.GameRecipe", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<int>("EnergyCost")
.HasColumnType("int");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("tinyint(1)")
.HasDefaultValue(true);
b.Property<int>("RareCost")
.HasColumnType("int");
b.Property<int>("ResultItemId")
.HasColumnType("int");
b.Property<int>("ScrapCost")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("IsEnabled");
b.HasIndex("ResultItemId");
b.ToTable("game_recipes", (string)null);
});
modelBuilder.Entity("Server.Data.InventoryItem", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("CharacterId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<ulong>("ItemTemplateId")
.HasColumnType("bigint unsigned");
b.Property<uint>("Quantity")
.HasColumnType("int unsigned");
b.Property<uint>("SlotIndex")
.HasColumnType("int unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<byte>("ItemType")
.HasColumnType("tinyint unsigned");
b.Property<uint>("MaxStack")
.HasColumnType("int unsigned");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<byte>("Rarity")
.HasColumnType("tinyint unsigned");
b.Property<string>("StatsJson")
.HasColumnType("json");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<uint>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<int>("DamageDealt")
.HasColumnType("int");
b.Property<int>("DamageTaken")
.HasColumnType("int");
b.Property<int>("Deaths")
.HasColumnType("int");
b.Property<int>("EloAfter")
.HasColumnType("int");
b.Property<int>("EloChange")
.HasColumnType("int");
b.Property<int>("EnergyCollected")
.HasColumnType("int");
b.Property<int>("ItemsCrafted")
.HasColumnType("int");
b.Property<int>("Kills")
.HasColumnType("int");
b.Property<int>("MatchDurationSeconds")
.HasColumnType("int");
b.Property<string>("MatchId")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("varchar(32)");
b.Property<int>("Placement")
.HasColumnType("int");
b.Property<DateTime>("PlayedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<int>("RareCollected")
.HasColumnType("int");
b.Property<int>("Result")
.HasColumnType("int");
b.Property<int>("ScrapCollected")
.HasColumnType("int");
b.Property<int>("SurvivalTimeSeconds")
.HasColumnType("int");
b.Property<int>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<int>("Deaths")
.HasColumnType("int");
b.Property<int>("Elo")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasDefaultValue(1000);
b.Property<int>("Extractions")
.HasColumnType("int");
b.Property<int>("ItemsCrafted")
.HasColumnType("int");
b.Property<int>("Kills")
.HasColumnType("int");
b.Property<int>("LongestSurvivalSeconds")
.HasColumnType("int");
b.Property<int>("Losses")
.HasColumnType("int");
b.Property<int>("MatchesPlayed")
.HasColumnType("int");
b.Property<long>("TotalDamageDealt")
.HasColumnType("bigint");
b.Property<long>("TotalDamageTaken")
.HasColumnType("bigint");
b.Property<long>("TotalEnergyCollected")
.HasColumnType("bigint");
b.Property<long>("TotalPlayTimeSeconds")
.HasColumnType("bigint");
b.Property<long>("TotalRareCollected")
.HasColumnType("bigint");
b.Property<long>("TotalScrapCollected")
.HasColumnType("bigint");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<int>("Wins")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AccountId")
.IsUnique();
b.ToTable("player_stats", (string)null);
});
modelBuilder.Entity("Server.Data.Session", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<string>("CreatedIp")
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("datetime(6)");
b.Property<DateTime?>("RevokedAt")
.HasColumnType("datetime(6)");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("varchar(128)");
b.Property<string>("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<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<double>("MaxX")
.HasColumnType("double");
b.Property<double>("MaxY")
.HasColumnType("double");
b.Property<double>("MaxZ")
.HasColumnType("double");
b.Property<double>("MinX")
.HasColumnType("double");
b.Property<double>("MinY")
.HasColumnType("double");
b.Property<double>("MinZ")
.HasColumnType("double");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("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
}
}
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SystemRevivalServer.Migrations
{
/// <inheritdoc />
public partial class AddAccountRoles : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Role",
table: "accounts",
type: "int",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Role",
table: "accounts");
}
}
}
+5
View File
@@ -53,6 +53,11 @@ namespace SystemRevivalServer.Migrations
.IsRequired()
.HasColumnType("varbinary(32)");
b.Property<int>("Role")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasDefaultValue(0);
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
+88
View File
@@ -0,0 +1,88 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Server.Data;
using Server.Services.Auth;
namespace Server.Services.Auth;
/// <summary>
/// Service for validating admin authentication via session tokens
/// </summary>
public interface IAdminAuthService
{
/// <summary>
/// Validates a session token and returns the account if authorized for the required role
/// </summary>
Task<AdminAuthResult> 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<AdminAuthResult> 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<GameDbContext>();
// 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);
}
}
/// <summary>
/// Extension methods for IPasswordHasher to support token hashing
/// </summary>
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));
}
}
+22
View File
@@ -12,11 +12,32 @@ public sealed class Account
public byte[] PasswordSalt { get; set; } = Array.Empty<byte>();
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<Session> Sessions { get; set; } = new List<Session>();
public ICollection<Character> Characters { get; set; } = new List<Character>();
// Helper methods
public bool IsAdmin => Role == AccountRole.Admin || Role == AccountRole.SuperAdmin;
public bool IsModerator => Role >= AccountRole.Moderator;
public bool IsSuperAdmin => Role == AccountRole.SuperAdmin;
}
/// <summary>
/// Account roles with increasing privilege levels
/// </summary>
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<Account>
@@ -32,6 +53,7 @@ public sealed class AccountConfig : IEntityTypeConfiguration<Account>
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();