Files
systemrevivalserver/Api/AdminController.cs
T

345 lines
11 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DataServer.Data;
using Server.Services.Auth;
namespace Server.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 = 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; } = "";
}