diff --git a/Server/Directory.Packages.props b/Server/Directory.Packages.props index d74475f..b35431f 100644 --- a/Server/Directory.Packages.props +++ b/Server/Directory.Packages.props @@ -34,6 +34,8 @@ + + diff --git a/Server/SOR.slnx b/Server/SOR.slnx index 692a0e4..3cd910f 100644 --- a/Server/SOR.slnx +++ b/Server/SOR.slnx @@ -1,6 +1,8 @@ + + diff --git a/Server/src/SOR.Admin/Components/App.razor b/Server/src/SOR.Admin/Components/App.razor new file mode 100644 index 0000000..d77fa7d --- /dev/null +++ b/Server/src/SOR.Admin/Components/App.razor @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + diff --git a/Server/src/SOR.Admin/Components/Layout/MainLayout.razor b/Server/src/SOR.Admin/Components/Layout/MainLayout.razor new file mode 100644 index 0000000..2bc161b --- /dev/null +++ b/Server/src/SOR.Admin/Components/Layout/MainLayout.razor @@ -0,0 +1,10 @@ +@inherits LayoutComponentBase + +
+ +
+
+ @Body +
+
+
diff --git a/Server/src/SOR.Admin/Components/Layout/NavMenu.razor b/Server/src/SOR.Admin/Components/Layout/NavMenu.razor new file mode 100644 index 0000000..8db0c3d --- /dev/null +++ b/Server/src/SOR.Admin/Components/Layout/NavMenu.razor @@ -0,0 +1,48 @@ + diff --git a/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor b/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor new file mode 100644 index 0000000..1feade0 --- /dev/null +++ b/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor @@ -0,0 +1,165 @@ +@page "/accounts/{Id:guid}" +@attribute [Authorize(Roles = "Admin,SuperAdmin")] +@inject SorIdentityDbContext Db +@inject UserManager UserManager +@inject NavigationManager Nav + +Account – SOR Admin + +@if (_account == null) +{ +

Loading…

+} +else +{ +
+ + Accounts + +

@(_account.DisplayName ?? _account.Email)

+
@_account.Id
+
+ + @if (_message != null) + { +
@_message
+ } + +
+ +
+
+
Profile
+
+
+
Email
+
@_account.Email
+
Display Name
+
@(_account.DisplayName ?? "–")
+
Created
+
@_account.CreatedAt.ToString("yyyy-MM-dd HH:mm UTC")
+
Last Login
+
@(_account.LastLoginAt?.ToString("yyyy-MM-dd HH:mm UTC") ?? "Never")
+
Email Confirmed
+
@(_account.EmailConfirmed ? "Yes" : "No")
+
2FA
+
@(_account.TwoFactorEnabled ? "Enabled" : "Disabled")
+
+
+
+
+ + +
+
+
Roles
+
+ @if (_roles.Count == 0) + { +

No roles assigned.

+ } + else + { + @foreach (var role in _roles) + { + @role + } + } +
+
+
+ + +
+
+
+ Account Status + @if (_isBanned) + { + Banned until @_account.LockoutEnd?.ToString("yyyy-MM-dd") + } + else + { + Active + } +
+
+ @if (_isBanned) + { + + } + else + { +
+
+ + +
+ +
+
+ +
+ } +
+
+
+
+} + +@code { + [Parameter] public Guid Id { get; set; } + + private Account? _account; + private List _roles = new(); + private bool _isBanned; + private int _banDays = 30; + private string? _message; + private bool _isError; + + protected override async Task OnInitializedAsync() + { + _account = await UserManager.FindByIdAsync(Id.ToString()); + if (_account != null) + { + _roles = (await UserManager.GetRolesAsync(_account)).ToList(); + _isBanned = _account.LockoutEnd > DateTimeOffset.UtcNow; + } + } + + private async Task BanAsync() + { + if (_account == null) return; + await UserManager.SetLockoutEndDateAsync( + _account, DateTimeOffset.UtcNow.AddDays(_banDays)); + _isBanned = true; + _message = $"Account banned for {_banDays} days."; + _isError = false; + } + + private async Task BanPermanentAsync() + { + if (_account == null) return; + await UserManager.SetLockoutEndDateAsync( + _account, DateTimeOffset.MaxValue); + _isBanned = true; + _message = "Account permanently banned."; + _isError = false; + } + + private async Task UnbanAsync() + { + if (_account == null) return; + await UserManager.SetLockoutEndDateAsync(_account, null); + _isBanned = false; + _message = "Account unbanned."; + _isError = false; + } +} diff --git a/Server/src/SOR.Admin/Components/Pages/Accounts/AccountList.razor b/Server/src/SOR.Admin/Components/Pages/Accounts/AccountList.razor new file mode 100644 index 0000000..7873e0a --- /dev/null +++ b/Server/src/SOR.Admin/Components/Pages/Accounts/AccountList.razor @@ -0,0 +1,99 @@ +@page "/accounts" +@attribute [Authorize(Roles = "Admin,SuperAdmin")] +@inject SorIdentityDbContext Db +@inject NavigationManager Nav + +Accounts – SOR Admin + +
+

Accounts

+
+ +
+
+ +
+
+ +
+
+ @if (_accounts == null) + { +

Loading…

+ } + else if (_accounts.Count == 0) + { +

No accounts found.

+ } + else + { + + + + + + + + + + + + + @foreach (var acc in _accounts) + { + + + + + + + + + } + +
EmailDisplay NameCreatedLast LoginStatus
@acc.Email@(acc.DisplayName ?? "–")@acc.CreatedAt.ToString("yyyy-MM-dd") + @(acc.LastLoginAt?.ToString("yyyy-MM-dd") ?? "Never") + + @if (acc.LockoutEnd > DateTimeOffset.UtcNow) + { + Banned + } + else + { + Active + } + + + View + +
+ } +
+
+ +@code { + private List? _accounts; + private List _all = new(); + private string _search = string.Empty; + + protected override async Task OnInitializedAsync() + { + _all = await Db.Users + .OrderByDescending(a => a.CreatedAt) + .ToListAsync(); + _accounts = _all; + } + + private void Filter() + { + _accounts = _all + .Where(a => + string.IsNullOrEmpty(_search) || + (a.Email?.Contains(_search, StringComparison.OrdinalIgnoreCase) == true) || + (a.DisplayName?.Contains(_search, StringComparison.OrdinalIgnoreCase) == true)) + .ToList(); + } +} diff --git a/Server/src/SOR.Admin/Components/Pages/Bazaar/BazaarOverview.razor b/Server/src/SOR.Admin/Components/Pages/Bazaar/BazaarOverview.razor new file mode 100644 index 0000000..1ff9785 --- /dev/null +++ b/Server/src/SOR.Admin/Components/Pages/Bazaar/BazaarOverview.razor @@ -0,0 +1,80 @@ +@page "/bazaar" +@attribute [Authorize(Roles = "Admin,SuperAdmin")] +@inject BazaarDbContext Db + +Bazaar – SOR Admin + +

Bazaar

+ +
+
+
+
+
Active Listings
+
@(_active ?? 0)
+
+
+
+
+
+
+
Total Transactions
+
@(_txCount ?? 0)
+
+
+
+
+ +
+
Recent Transactions
+
+ @if (_recentTx == null) + { +

Loading…

+ } + else if (_recentTx.Count == 0) + { +

No transactions yet.

+ } + else + { + + + + + + + + + + + @foreach (var tx in _recentTx) + { + + + + + + + } + +
DateAmountCurrencyListing
@tx.TransactedAt.ToString("yyyy-MM-dd HH:mm")@tx.Amount.ToString("N2")@tx.Currency@tx.ListingId
+ } +
+
+ +@code { + private int? _active; + private int? _txCount; + private List? _recentTx; + + protected override async Task OnInitializedAsync() + { + _active = await Db.Listings.CountAsync(l => l.Status == BazaarListingStatus.Active); + _txCount = await Db.Transactions.CountAsync(); + _recentTx = await Db.Transactions + .OrderByDescending(t => t.TransactedAt) + .Take(50) + .ToListAsync(); + } +} diff --git a/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor b/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor new file mode 100644 index 0000000..21ceebc --- /dev/null +++ b/Server/src/SOR.Admin/Components/Pages/Cards/CardEditor.razor @@ -0,0 +1,463 @@ +@page "/cards/new" +@page "/cards/{Id:guid}" +@attribute [Authorize(Roles = "Admin,SuperAdmin")] +@inject CatalogDbContext Db +@inject NavigationManager Nav + +@(_isNew ? "New Card" : _card?.Name ?? "Card") – SOR Admin + +@if (_card == null) +{ +

Loading…

+} +else +{ +
+
+ + Cards + +

@(_isNew ? "New Card" : _card.Name)

+
+
+ @if (!_isNew) + { + + } + +
+
+ + @if (_saveError != null) + { +
@_saveError
+ } + @if (_saveSuccess) + { +
Saved successfully.
+ } + + + + + + @if (_activeTab == "Basic") + { +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ } + + + else if (_activeTab == "Stats") + { + @if (_card.CardType is CardType.ArchSpirit or CardType.Spirit) + { +
+
Channeling
+
+ + +
+
+ + +
+ @if (_card.CardType == CardType.ArchSpirit) + { +
+ + +
+ } + +
Combat
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
Movement
+
+ + +
+
+ + +
+ +
Flags
+ @foreach (var flag in _unitFlags) + { +
+
+ + +
+
+ } + +
Genus Tags
+
+ +
Stored as a Postgres text[] array.
+
+
+ } + else if (_card.CardType == CardType.Terramorpha) + { +
+
+ + +
+
+ } + else + { +

No additional stats for @_card.CardType cards.

+ } + } + + + else if (_activeTab == "Abilities") + { +
+ @if (_card.CardType is CardType.Repentance or CardType.Instinct or CardType.Terramorpha) + { + Effects JSON (Action[] array) — see abilities.md for schema. + } + else + { + Abilities JSON (AbilityDefinition[] array) — see abilities.md for schema. + } +
+ + } + + + else if (_activeTab == "Assets") + { +
Static Assets
+
+ @foreach (var asset in _card.Assets) + { +
+
+
+
+ @asset.AssetType + +
+ + +
+
+
+ } +
+
+ @foreach (var t in Enum.GetValues()) + { + + } +
+
+
+ +
Animation Bindings
+ + + + @foreach (var anim in _card.AnimationBindings) + { + + + + + + } + +
ActionCDN URL
+ + + + + +
+ + } +} + +@code { + [Parameter] public Guid? Id { get; set; } + + private CardDefinition? _card; + private bool _isNew; + private string _activeTab = "Basic"; + private readonly string[] _tabs = ["Basic", "Stats", "Abilities", "Assets"]; + private bool _saving; + private string? _saveError; + private bool _saveSuccess; + private string _genusInput = string.Empty; + private string _abilitiesJson = string.Empty; + + protected override async Task OnInitializedAsync() + { + _isNew = Id == null; + + if (_isNew) + { + _card = new CardDefinition + { + CreatedAt = DateTimeOffset.UtcNow, + UpdatedAt = DateTimeOffset.UtcNow, + }; + } + else + { + _card = await Db.CardDefinitions + .Include(c => c.Assets) + .Include(c => c.AnimationBindings) + .FirstOrDefaultAsync(c => c.Id == Id); + + if (_card != null) + { + _genusInput = _card.Genus != null + ? string.Join(", ", _card.Genus) + : string.Empty; + + _abilitiesJson = _card.CardType is CardType.Repentance + or CardType.Instinct or CardType.Terramorpha + ? _card.EffectsJson ?? string.Empty + : _card.AbilitiesJson ?? string.Empty; + } + } + } + + private async Task SaveAsync() + { + if (_card == null) return; + _saving = true; + _saveError = null; + _saveSuccess = false; + + try + { + // Flush genus input to array. + _card.Genus = string.IsNullOrWhiteSpace(_genusInput) + ? null + : _genusInput.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + // Flush abilities JSON to the correct column. + if (_card.CardType is CardType.Repentance or CardType.Instinct or CardType.Terramorpha) + _card.EffectsJson = string.IsNullOrWhiteSpace(_abilitiesJson) ? null : _abilitiesJson; + else + _card.AbilitiesJson = string.IsNullOrWhiteSpace(_abilitiesJson) ? null : _abilitiesJson; + + _card.UpdatedAt = DateTimeOffset.UtcNow; + + if (_isNew) + { + Db.CardDefinitions.Add(_card); + } + + await Db.SaveChangesAsync(); + _saveSuccess = true; + + if (_isNew) + { + _isNew = false; + Nav.NavigateTo($"/cards/{_card.Id}", replace: true); + } + } + catch (Exception ex) + { + _saveError = ex.Message; + } + finally + { + _saving = false; + } + } + + private async Task DeleteAsync() + { + if (_card == null || _isNew) return; + Db.CardDefinitions.Remove(_card); + await Db.SaveChangesAsync(); + Nav.NavigateTo("/cards"); + } + + private void AddAsset(CardAssetType type) + => _card!.Assets.Add(new CardAsset + { + CardDefinitionId = _card.Id, + AssetType = type, + CreatedAt = DateTimeOffset.UtcNow, + }); + + private void RemoveAsset(CardAsset asset) + { + _card!.Assets.Remove(asset); + if (asset.Id != Guid.Empty) + Db.CardAssets.Remove(asset); + } + + private void AddAnimation() + => _card!.AnimationBindings.Add(new CardAnimationBinding + { + CardDefinitionId = _card.Id, + }); + + private void RemoveAnimation(CardAnimationBinding anim) + { + _card!.AnimationBindings.Remove(anim); + if (anim.Id != Guid.Empty) + Db.AnimationBindings.Remove(anim); + } + + // ── Flag descriptors (avoids 10 identical checkboxes) ─────────────────── + + private sealed record FlagDescriptor( + string Label, + Func Get, + Action Set); + + private readonly FlagDescriptor[] _unitFlags = + [ + new("Can Attack", c => c.CanAttack ?? false, (c, v) => c.CanAttack = v), + new("Can Defend", c => c.CanDefend ?? false, (c, v) => c.CanDefend = v), + new("Can Be Attacked", c => c.CanBeAttacked ?? false, (c, v) => c.CanBeAttacked = v), + new("Can Be Blocked", c => c.CanBeBlocked ?? false, (c, v) => c.CanBeBlocked = v), + new("Can Move", c => c.CanMove ?? false, (c, v) => c.CanMove = v), + new("Can Be Obstructed",c => c.CanBeObstructed ?? false, (c, v) => c.CanBeObstructed = v), + new("Requires LOS", c => c.RequiresLos ?? false, (c, v) => c.RequiresLos = v), + new("Can Use Ability", c => c.CanUseAbility ?? false, (c, v) => c.CanUseAbility = v), + new("Can Be Sacrificed",c => c.CanBeSacrificed ?? false, (c, v) => c.CanBeSacrificed = v), + ]; +} diff --git a/Server/src/SOR.Admin/Components/Pages/Cards/CardList.razor b/Server/src/SOR.Admin/Components/Pages/Cards/CardList.razor new file mode 100644 index 0000000..d19cc28 --- /dev/null +++ b/Server/src/SOR.Admin/Components/Pages/Cards/CardList.razor @@ -0,0 +1,127 @@ +@page "/cards" +@attribute [Authorize(Roles = "Admin,SuperAdmin")] +@inject CatalogDbContext Db +@inject NavigationManager Nav + +Cards – SOR Admin + +
+

Cards

+ + New Card + +
+ +
+
+
+
+ +
+
+ +
+
+ +
+
+
+
+ +
+
+ @if (_cards == null) + { +

Loading…

+ } + else if (_cards.Count == 0) + { +

No cards match the current filter.

+ } + else + { + + + + + + + + + + + + + + + @foreach (var card in _cards) + { + + + + + + + + + + + } + +
NameTypeAffinitySPSTRarityStatus
@card.Name@card.CardType@card.Affinity@card.SpCost@card.StCost@card.Rarity + @if (card.IsPublished) + { + Published + } + else + { + Draft + } + + + Edit + +
+ } +
+
+ +@code { + private List? _cards; + private List _all = new(); + private string _search = string.Empty; + private string _filterType = string.Empty; + private string _filterPublished = string.Empty; + + protected override async Task OnInitializedAsync() + { + _all = await Db.CardDefinitions + .OrderBy(c => c.Name) + .ToListAsync(); + _cards = _all; + } + + private void Filter() + { + _cards = _all + .Where(c => string.IsNullOrEmpty(_search) || + c.Name.Contains(_search, StringComparison.OrdinalIgnoreCase)) + .Where(c => string.IsNullOrEmpty(_filterType) || + c.CardType.ToString() == _filterType) + .Where(c => string.IsNullOrEmpty(_filterPublished) || + c.IsPublished.ToString().ToLower() == _filterPublished) + .ToList(); + } +} diff --git a/Server/src/SOR.Admin/Components/Pages/Dashboard.razor b/Server/src/SOR.Admin/Components/Pages/Dashboard.razor new file mode 100644 index 0000000..ce1c029 --- /dev/null +++ b/Server/src/SOR.Admin/Components/Pages/Dashboard.razor @@ -0,0 +1,62 @@ +@page "/" +@attribute [Authorize(Roles = "Admin,SuperAdmin")] +@inject CatalogDbContext CatalogDb +@inject SorIdentityDbContext IdentityDb +@inject BazaarDbContext BazaarDb + +Dashboard – SOR Admin + +

Dashboard

+ +
+
+
+
+
Total Cards
+
@(_totalCards?.ToString("N0") ?? "–")
+
@(_publishedCards?.ToString("N0") ?? "–") published
+
+
+
+
+
+
+
Accounts
+
@(_totalAccounts?.ToString("N0") ?? "–")
+
+
+
+
+
+
+
Active Listings
+
@(_activeListings?.ToString("N0") ?? "–")
+
+
+
+
+
+
+
Transactions
+
@(_totalTransactions?.ToString("N0") ?? "–")
+
+
+
+
+ +@code { + private int? _totalCards; + private int? _publishedCards; + private int? _totalAccounts; + private int? _activeListings; + private int? _totalTransactions; + + protected override async Task OnInitializedAsync() + { + _totalCards = await CatalogDb.CardDefinitions.CountAsync(); + _publishedCards = await CatalogDb.CardDefinitions.CountAsync(c => c.IsPublished); + _totalAccounts = await IdentityDb.Users.CountAsync(); + _activeListings = await BazaarDb.Listings.CountAsync(l => l.Status == BazaarListingStatus.Active); + _totalTransactions = await BazaarDb.Transactions.CountAsync(); + } +} diff --git a/Server/src/SOR.Admin/Components/Pages/FeatureFlags.razor b/Server/src/SOR.Admin/Components/Pages/FeatureFlags.razor new file mode 100644 index 0000000..c923a14 --- /dev/null +++ b/Server/src/SOR.Admin/Components/Pages/FeatureFlags.razor @@ -0,0 +1,44 @@ +@page "/feature-flags" +@attribute [Authorize(Roles = "Admin,SuperAdmin")] + +Feature Flags – SOR Admin + +

Feature Flags

+ +
+ + Feature flags are stored in Redis via RedisKeys.FeatureFlag(flag). + This UI will read/write those keys once the Redis connection is wired into the admin site. + For now, use redis-cli SET feature:bazaar_enabled 1 directly. +
+ +
+
OAuth Providers
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ProviderStatusNote
GoogleStubbedEnable via appsettings OAuth config
SteamStubbedRequires OpenID 2.0 handler
AppleStubbedRequires Sign in with Apple OIDC
MicrosoftStubbedEnable via Azure AD app registration
+
diff --git a/Server/src/SOR.Admin/Components/Pages/Login.razor b/Server/src/SOR.Admin/Components/Pages/Login.razor new file mode 100644 index 0000000..95eedef --- /dev/null +++ b/Server/src/SOR.Admin/Components/Pages/Login.razor @@ -0,0 +1,45 @@ +@page "/login" +@attribute [AllowAnonymous] +@* Static SSR — no rendermode, keeps login available without a SignalR connection. *@ + +Sign In – SOR Admin + +
+
+
+

+ SOR Admin +

+

Sign in to continue

+ + @if (Error == "invalid") + { +
Invalid email or password.
+ } + else if (Error == "locked") + { +
Account locked — try again later.
+ } + +
+ + +
+ + +
+
+ + +
+ +
+
+
+
+ +@code { + [SupplyParameterFromQuery] public string? ReturnUrl { get; set; } + [SupplyParameterFromQuery] public string? Error { get; set; } +} diff --git a/Server/src/SOR.Admin/Components/Routes.razor b/Server/src/SOR.Admin/Components/Routes.razor new file mode 100644 index 0000000..124d395 --- /dev/null +++ b/Server/src/SOR.Admin/Components/Routes.razor @@ -0,0 +1,34 @@ + + + + + + @if (context.User.Identity?.IsAuthenticated != true) + { + + } + else + { +
+
+ Access denied. + You do not have permission to view this page. +
+
+ } +
+
+ +
+ + Not found + +
+
+ 404 — Nothing at this address. +
+
+
+
+
+
diff --git a/Server/src/SOR.Admin/Components/_Imports.razor b/Server/src/SOR.Admin/Components/_Imports.razor new file mode 100644 index 0000000..2e45fd0 --- /dev/null +++ b/Server/src/SOR.Admin/Components/_Imports.razor @@ -0,0 +1,20 @@ +@using System.Net.Http +@using System.Net.Http.Json +@using Microsoft.AspNetCore.Authorization +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.Components.Authorization +@using Microsoft.AspNetCore.Components.Forms +@using Microsoft.AspNetCore.Components.Routing +@using Microsoft.AspNetCore.Components.Web +@using static Microsoft.AspNetCore.Components.Web.RenderMode +@using Microsoft.AspNetCore.Components.Web.Virtualization +@using Microsoft.EntityFrameworkCore +@using SOR.Admin.Components +@using SOR.Admin.Components.Layout +@using SOR.Database.Contexts +@using SOR.Database.Entities.Catalog +@using SOR.Database.Entities.Identity +@using SOR.Database.Entities.Collection +@using SOR.Database.Entities.Bazaar +@using SOR.Database.Entities.Chat +@using SOR.Database.Enums diff --git a/Server/src/SOR.Admin/IdentityRevalidatingAuthenticationStateProvider.cs b/Server/src/SOR.Admin/IdentityRevalidatingAuthenticationStateProvider.cs new file mode 100644 index 0000000..e7e7b03 --- /dev/null +++ b/Server/src/SOR.Admin/IdentityRevalidatingAuthenticationStateProvider.cs @@ -0,0 +1,44 @@ +namespace SOR.Admin; + +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Components.Server; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using SOR.Database.Entities.Identity; + +/// +/// Revalidates the Identity cookie on a schedule while a Blazor Server circuit +/// is open, so that bans or role changes take effect without a page reload. +/// This is the standard pattern from the Blazor Identity scaffolding. +/// +internal sealed class IdentityRevalidatingAuthenticationStateProvider( + ILoggerFactory loggerFactory, + IServiceScopeFactory scopeFactory, + IOptions options) + : RevalidatingServerAuthenticationStateProvider(loggerFactory) +{ + protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30); + + protected override async Task ValidateAuthenticationStateAsync( + AuthenticationState authenticationState, + CancellationToken cancellationToken) + { + await using var scope = scopeFactory.CreateAsyncScope(); + var userManager = scope.ServiceProvider.GetRequiredService>(); + return await ValidateSecurityStampAsync(userManager, authenticationState.User); + } + + private async Task ValidateSecurityStampAsync( + UserManager userManager, + System.Security.Claims.ClaimsPrincipal principal) + { + var user = await userManager.GetUserAsync(principal); + if (user is null) return false; + if (!userManager.SupportsUserSecurityStamp) return true; + + var principalStamp = principal + .FindFirst(options.Value.ClaimsIdentity.SecurityStampClaimType)?.Value; + var userStamp = await userManager.GetSecurityStampAsync(user); + return principalStamp == userStamp; + } +} diff --git a/Server/src/SOR.Admin/Program.cs b/Server/src/SOR.Admin/Program.cs new file mode 100644 index 0000000..6531c37 --- /dev/null +++ b/Server/src/SOR.Admin/Program.cs @@ -0,0 +1,128 @@ +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using SOR.Admin; +using SOR.Admin.Components; +using SOR.Database; +using SOR.Database.Contexts; +using SOR.Database.Entities.Identity; + +var builder = WebApplication.CreateBuilder(args); + +// ── Blazor Server ────────────────────────────────────────────────────────── +builder.Services.AddRazorComponents() + .AddInteractiveServerComponents(); + +// Required for and [Authorize] in Blazor components. +builder.Services.AddCascadingAuthenticationState(); +builder.Services.AddScoped(); + +// ── Identity + Cookie Auth ────────────────────────────────────────────────── +builder.Services.AddAuthentication(options => + { + options.DefaultScheme = IdentityConstants.ApplicationScheme; + options.DefaultSignInScheme = IdentityConstants.ExternalScheme; + }) + .AddIdentityCookies(); + +// Redirect to /login instead of the default /Account/Login. +builder.Services.ConfigureApplicationCookie(options => +{ + options.LoginPath = "/login"; + options.AccessDeniedPath = "/login"; + options.SlidingExpiration = true; + options.ExpireTimeSpan = TimeSpan.FromHours(8); +}); + +// All Blazor pages require Admin or SuperAdmin role by default. +// Override per-page with [AllowAnonymous] (login page only). +builder.Services.AddAuthorization(options => +{ + options.FallbackPolicy = new AuthorizationPolicyBuilder() + .RequireAuthenticatedUser() + .RequireRole("Admin", "SuperAdmin") + .Build(); +}); + +builder.Services.AddIdentityCore(options => + { + options.SignIn.RequireConfirmedAccount = false; + options.Password.RequireDigit = true; + options.Password.RequireUppercase = true; + options.Password.RequireNonAlphanumeric = true; + options.Password.RequiredLength = 12; + options.Lockout.MaxFailedAccessAttempts = 5; + options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15); + }) + .AddRoles>() + .AddEntityFrameworkStores() + .AddSignInManager() + .AddDefaultTokenProviders(); + +// ── Razor Pages (used for login/logout form posts) ───────────────────────── +builder.Services.AddRazorPages(); + +// ── Databases ───────────────────────────────────────────────────────────── +builder.Services.AddIdentityDatabase(builder.Configuration); +builder.Services.AddCatalogDatabase(builder.Configuration); +builder.Services.AddCollectionDatabase(builder.Configuration); +builder.Services.AddBazaarDatabase(builder.Configuration); +builder.Services.AddChatDatabase(builder.Configuration); + +// ── HTTP pipeline ───────────────────────────────────────────────────────── +var app = builder.Build(); + +if (!app.Environment.IsDevelopment()) +{ + app.UseExceptionHandler("/Error"); + app.UseHsts(); +} + +app.UseHttpsRedirection(); +app.UseStaticFiles(); +app.UseRouting(); +app.UseAuthentication(); +app.UseAuthorization(); +app.UseAntiforgery(); + +// ── Auth endpoints (form POST targets — cookies cannot be set from Blazor) ── + +// Login: called by the /login page form. +app.MapPost("/auth/login", async ( + HttpContext ctx, + [FromForm] string email, + [FromForm] string password, + [FromForm] string? returnUrl, + UserManager userManager, + SignInManager signInManager) => +{ + var user = await userManager.FindByEmailAsync(email); + if (user is not null) + { + var result = await signInManager.PasswordSignInAsync( + user, password, isPersistent: false, lockoutOnFailure: true); + if (result.Succeeded) + return Results.LocalRedirect( + string.IsNullOrWhiteSpace(returnUrl) ? "/" : returnUrl); + if (result.IsLockedOut) + return Results.Redirect("/login?error=locked"); + } + return Results.Redirect("/login?error=invalid"); +}).AllowAnonymous().DisableAntiforgery(); + +// Logout: called by the nav menu form. +app.MapPost("/auth/logout", async (SignInManager signInManager) => +{ + await signInManager.SignOutAsync(); + return Results.Redirect("/login"); +}).DisableAntiforgery(); + +// ── Blazor + Razor Pages ────────────────────────────────────────────────── +app.MapRazorPages(); +app.MapRazorComponents() + .AddInteractiveServerRenderMode(); + +app.Run(); diff --git a/Server/src/SOR.Admin/SOR.Admin.csproj b/Server/src/SOR.Admin/SOR.Admin.csproj new file mode 100644 index 0000000..46f7d0e --- /dev/null +++ b/Server/src/SOR.Admin/SOR.Admin.csproj @@ -0,0 +1,17 @@ + + + SOR.Admin + Exe + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + diff --git a/Server/src/SOR.Admin/appsettings.json b/Server/src/SOR.Admin/appsettings.json new file mode 100644 index 0000000..799c155 --- /dev/null +++ b/Server/src/SOR.Admin/appsettings.json @@ -0,0 +1,17 @@ +{ + // All contexts share one Postgres database ("sor") with separate schemas. + // Override individual keys (e.g. "Catalog") to move a schema to its own server. + "ConnectionStrings": { + "Default": "Host=172.10.1.127;Port=5432;Database=sor;Username=SOR-DBA;Password=G073gxq7VtQaOfnITcxDh3bsibcipe6D" + }, + + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Microsoft.EntityFrameworkCore.Database.Command": "Warning" + } + }, + + "AllowedHosts": "*" +} diff --git a/Server/src/SOR.Admin/wwwroot/app.css b/Server/src/SOR.Admin/wwwroot/app.css new file mode 100644 index 0000000..d985075 --- /dev/null +++ b/Server/src/SOR.Admin/wwwroot/app.css @@ -0,0 +1,42 @@ +/* SOR Admin shell layout */ + +html, body { + height: 100%; + margin: 0; +} + +.sor-admin-shell { + display: flex; + height: 100vh; + overflow: hidden; +} + +.sor-admin-sidebar { + width: 220px; + min-width: 220px; + overflow-y: auto; + flex-shrink: 0; +} + +.sor-admin-content { + flex: 1; + overflow-y: auto; + background: #f8f9fa; +} + +/* Active nav link highlight */ +.sor-admin-sidebar .nav-link.active { + background: rgba(255, 255, 255, 0.15); + border-radius: 6px; +} + +.sor-admin-sidebar .nav-link:hover { + background: rgba(255, 255, 255, 0.08); + border-radius: 6px; +} + +/* Monospace JSON editor */ +.font-monospace { + font-family: 'Cascadia Code', 'Fira Code', 'Consolas', monospace; + font-size: 0.85rem; +} diff --git a/Server/src/SOR.Database/Contexts/BazaarDbContext.cs b/Server/src/SOR.Database/Contexts/BazaarDbContext.cs new file mode 100644 index 0000000..22e7aa5 --- /dev/null +++ b/Server/src/SOR.Database/Contexts/BazaarDbContext.cs @@ -0,0 +1,57 @@ +namespace SOR.Database.Contexts; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Entities.Bazaar; +using SOR.Database.Enums; + +/// +/// EF Core DbContext for the bazaar schema: listings and transaction history. +/// +/// Schema: "bazaar" +/// Run migrations: dotnet ef migrations add InitialCreate +/// --context BazaarDbContext +/// --project src/SOR.Database +/// --startup-project src/SOR.Admin +/// --output-dir Migrations/Bazaar +/// +public sealed class BazaarDbContext : DbContext +{ + public BazaarDbContext(DbContextOptions options) + : base(options) { } + + public DbSet Listings => Set(); + public DbSet Transactions => Set(); + + protected override void OnModelCreating(ModelBuilder builder) + { + builder.HasDefaultSchema("bazaar"); + + builder.Entity(e => + { + e.ToTable("listings"); + e.HasKey(l => l.Id); + e.Property(l => l.ListingType).HasConversion(); + e.Property(l => l.Currency).HasConversion(); + e.Property(l => l.Status).HasConversion(); + e.Property(l => l.Price).HasColumnType("numeric(18,4)"); + e.HasIndex(l => l.SellerAccountId); + e.HasIndex(l => new { l.Status, l.CardDefinitionId }); + e.HasIndex(l => new { l.Status, l.ExpiresAt }); + e.HasMany(l => l.Transactions) + .WithOne(t => t.Listing) + .HasForeignKey(t => t.ListingId) + .OnDelete(DeleteBehavior.Restrict); + }); + + builder.Entity(e => + { + e.ToTable("transactions"); + e.HasKey(t => t.Id); + e.Property(t => t.Currency).HasConversion(); + e.Property(t => t.Amount).HasColumnType("numeric(18,4)"); + e.HasIndex(t => t.BuyerAccountId); + e.HasIndex(t => t.SellerAccountId); + e.HasIndex(t => t.TransactedAt); + }); + } +} diff --git a/Server/src/SOR.Database/Contexts/CatalogDbContext.cs b/Server/src/SOR.Database/Contexts/CatalogDbContext.cs new file mode 100644 index 0000000..0afea58 --- /dev/null +++ b/Server/src/SOR.Database/Contexts/CatalogDbContext.cs @@ -0,0 +1,105 @@ +namespace SOR.Database.Contexts; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Entities.Catalog; +using SOR.Database.Enums; + +/// +/// EF Core DbContext for the catalog schema: card definitions, sets, and assets. +/// This is read-heavy in production (clients and game servers read cards constantly) +/// and write-heavy only from the admin tool. +/// +/// Schema: "catalog" +/// Run migrations: dotnet ef migrations add InitialCreate +/// --context CatalogDbContext +/// --project src/SOR.Database +/// --startup-project src/SOR.Admin +/// --output-dir Migrations/Catalog +/// +public sealed class CatalogDbContext : DbContext +{ + public CatalogDbContext(DbContextOptions options) + : base(options) { } + + public DbSet CardSets => Set(); + public DbSet CardDefinitions => Set(); + public DbSet CardAssets => Set(); + public DbSet AnimationBindings => Set(); + + protected override void OnModelCreating(ModelBuilder builder) + { + builder.HasDefaultSchema("catalog"); + + builder.Entity(e => + { + e.ToTable("card_sets"); + e.HasKey(s => s.Id); + e.HasIndex(s => s.Code).IsUnique(); + e.HasMany(s => s.Cards) + .WithOne(c => c.Set) + .HasForeignKey(c => c.SetId) + .OnDelete(DeleteBehavior.SetNull); + }); + + builder.Entity(e => + { + e.ToTable("card_definitions"); + e.HasKey(c => c.Id); + + // Store enums as strings for readability in the DB and JSONB payloads. + e.Property(c => c.CardType).HasConversion(); + e.Property(c => c.Affinity).HasConversion(); + e.Property(c => c.AttackType).HasConversion(); + e.Property(c => c.MovementType).HasConversion(); + e.Property(c => c.TerramorphaMode).HasConversion(); + e.Property(c => c.Rarity).HasConversion(); + + // JSONB columns — serialized by the service layer. + e.Property(c => c.AbilitiesJson) + .HasColumnType("jsonb") + .HasColumnName("abilities"); + e.Property(c => c.EffectsJson) + .HasColumnType("jsonb") + .HasColumnName("effects"); + e.Property(c => c.OtherCostsJson) + .HasColumnType("jsonb") + .HasColumnName("other_costs"); + + // Postgres native text[] array for genus tags. + e.Property(c => c.Genus).HasColumnType("text[]"); + + // Indexes for the most common query patterns. + e.HasIndex(c => c.Name); + e.HasIndex(c => c.CardType); + e.HasIndex(c => c.Affinity); + e.HasIndex(c => c.Rarity); + e.HasIndex(c => new { c.IsPublished, c.SetId }); + + e.HasMany(c => c.Assets) + .WithOne(a => a.CardDefinition) + .HasForeignKey(a => a.CardDefinitionId) + .OnDelete(DeleteBehavior.Cascade); + + e.HasMany(c => c.AnimationBindings) + .WithOne(a => a.CardDefinition) + .HasForeignKey(a => a.CardDefinitionId) + .OnDelete(DeleteBehavior.Cascade); + }); + + builder.Entity(e => + { + e.ToTable("card_assets"); + e.HasKey(a => a.Id); + e.Property(a => a.AssetType).HasConversion(); + e.HasIndex(a => new { a.CardDefinitionId, a.AssetType }); + }); + + builder.Entity(e => + { + e.ToTable("card_animation_bindings"); + e.HasKey(a => a.Id); + // One action name per card — no duplicate "attack" bindings. + e.HasIndex(a => new { a.CardDefinitionId, a.ActionName }).IsUnique(); + }); + } +} diff --git a/Server/src/SOR.Database/Contexts/ChatDbContext.cs b/Server/src/SOR.Database/Contexts/ChatDbContext.cs new file mode 100644 index 0000000..66231e9 --- /dev/null +++ b/Server/src/SOR.Database/Contexts/ChatDbContext.cs @@ -0,0 +1,65 @@ +namespace SOR.Database.Contexts; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Entities.Chat; +using SOR.Database.Enums; + +/// +/// EF Core DbContext for the chat schema. +/// At scale, high-frequency chat messages may be offloaded to a time-series store; +/// this table serves as the durable audit log and history retrieval source. +/// +/// Schema: "chat" +/// Run migrations: dotnet ef migrations add InitialCreate +/// --context ChatDbContext +/// --project src/SOR.Database +/// --startup-project src/SOR.Admin +/// --output-dir Migrations/Chat +/// +public sealed class ChatDbContext : DbContext +{ + public ChatDbContext(DbContextOptions options) + : base(options) { } + + public DbSet Channels => Set(); + public DbSet Members => Set(); + public DbSet Messages => Set(); + + protected override void OnModelCreating(ModelBuilder builder) + { + builder.HasDefaultSchema("chat"); + + builder.Entity(e => + { + e.ToTable("channels"); + e.HasKey(c => c.Id); + e.Property(c => c.ChannelType).HasConversion(); + e.HasIndex(c => c.ChannelType); + e.HasIndex(c => c.MatchId); + e.HasMany(c => c.Members) + .WithOne(m => m.Channel) + .HasForeignKey(m => m.ChannelId) + .OnDelete(DeleteBehavior.Cascade); + e.HasMany(c => c.Messages) + .WithOne(m => m.Channel) + .HasForeignKey(m => m.ChannelId) + .OnDelete(DeleteBehavior.Cascade); + }); + + builder.Entity(e => + { + e.ToTable("members"); + e.HasKey(m => m.Id); + e.HasIndex(m => new { m.ChannelId, m.AccountId }).IsUnique(); + e.HasIndex(m => m.AccountId); + }); + + builder.Entity(e => + { + e.ToTable("messages"); + e.HasKey(m => m.Id); + e.HasIndex(m => new { m.ChannelId, m.SentAt }); + e.HasIndex(m => m.SenderAccountId); + }); + } +} diff --git a/Server/src/SOR.Database/Contexts/CollectionDbContext.cs b/Server/src/SOR.Database/Contexts/CollectionDbContext.cs new file mode 100644 index 0000000..9d28220 --- /dev/null +++ b/Server/src/SOR.Database/Contexts/CollectionDbContext.cs @@ -0,0 +1,57 @@ +namespace SOR.Database.Contexts; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Entities.Collection; + +/// +/// EF Core DbContext for the collection schema: player-owned cards and decks. +/// All cross-schema IDs (AccountId, CardDefinitionId) are bare Guids — no EF FKs. +/// +/// Schema: "collection" +/// Run migrations: dotnet ef migrations add InitialCreate +/// --context CollectionDbContext +/// --project src/SOR.Database +/// --startup-project src/SOR.Admin +/// --output-dir Migrations/Collection +/// +public sealed class CollectionDbContext : DbContext +{ + public CollectionDbContext(DbContextOptions options) + : base(options) { } + + public DbSet PlayerCards => Set(); + public DbSet Decks => Set(); + public DbSet DeckCards => Set(); + + protected override void OnModelCreating(ModelBuilder builder) + { + builder.HasDefaultSchema("collection"); + + builder.Entity(e => + { + e.ToTable("player_cards"); + e.HasKey(c => c.Id); + e.HasIndex(c => c.AccountId); + e.HasIndex(c => new { c.AccountId, c.CardDefinitionId }); + }); + + builder.Entity(e => + { + e.ToTable("decks"); + e.HasKey(d => d.Id); + e.HasIndex(d => d.AccountId); + e.HasMany(d => d.Cards) + .WithOne(dc => dc.Deck) + .HasForeignKey(dc => dc.DeckId) + .OnDelete(DeleteBehavior.Cascade); + }); + + builder.Entity(e => + { + e.ToTable("deck_cards"); + e.HasKey(dc => dc.Id); + // Same card definition can only appear once per deck row (use Quantity for copies). + e.HasIndex(dc => new { dc.DeckId, dc.CardDefinitionId }).IsUnique(); + }); + } +} diff --git a/Server/src/SOR.Database/Contexts/SorIdentityDbContext.cs b/Server/src/SOR.Database/Contexts/SorIdentityDbContext.cs new file mode 100644 index 0000000..ff552b4 --- /dev/null +++ b/Server/src/SOR.Database/Contexts/SorIdentityDbContext.cs @@ -0,0 +1,60 @@ +namespace SOR.Database.Contexts; + +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using SOR.Database.Entities.Identity; + +/// +/// EF Core DbContext for the identity schema. +/// Extends IdentityDbContext so ASP.NET Core Identity manages users, roles, +/// claims, external logins, and tokens. We add AccountSession for explicit +/// session revocation. +/// +/// Schema: "identity" +/// Run migrations: dotnet ef migrations add InitialCreate +/// --context SorIdentityDbContext +/// --project src/SOR.Database +/// --startup-project src/SOR.Admin +/// --output-dir Migrations/Identity +/// +public sealed class SorIdentityDbContext + : IdentityDbContext, Guid> +{ + public SorIdentityDbContext(DbContextOptions options) + : base(options) { } + + public DbSet AccountSessions => Set(); + + protected override void OnModelCreating(ModelBuilder builder) + { + // MUST call base — Identity configures its own tables here. + base.OnModelCreating(builder); + + builder.HasDefaultSchema("identity"); + + // Rename Identity's default AspNet* tables to snake_case. + builder.Entity().ToTable("accounts"); + builder.Entity>().ToTable("roles"); + builder.Entity>().ToTable("account_roles"); + builder.Entity>().ToTable("account_claims"); + builder.Entity>().ToTable("external_logins"); + builder.Entity>().ToTable("role_claims"); + builder.Entity>().ToTable("account_tokens"); + + builder.Entity(e => + { + e.HasIndex(a => a.DisplayName); + }); + + builder.Entity(e => + { + e.ToTable("account_sessions"); + e.HasKey(s => s.Id); + // Hash lookup must be unique and fast. + e.HasIndex(s => s.TokenHash).IsUnique(); + // Compound index: find all active sessions for an account quickly. + e.HasIndex(s => new { s.AccountId, s.ExpiresAt }); + }); + } +} diff --git a/Server/src/SOR.Database/Entities/Bazaar/BazaarListing.cs b/Server/src/SOR.Database/Entities/Bazaar/BazaarListing.cs new file mode 100644 index 0000000..9afe84d --- /dev/null +++ b/Server/src/SOR.Database/Entities/Bazaar/BazaarListing.cs @@ -0,0 +1,34 @@ +namespace SOR.Database.Entities.Bazaar; + +using SOR.Database.Enums; + +/// +/// A player's offer to sell a card on the bazaar. +/// +/// CardDefinitionId is denormalized (also on PlayerCard) to allow efficient +/// filtering/searching without joining to the collection schema. +/// +/// All cross-schema Guids have no EF FKs by design. +/// +public sealed class BazaarListing +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + /// Cross-schema: seller's account. + public Guid SellerAccountId { get; set; } + + /// Cross-schema: the specific card instance being listed. + public Guid PlayerCardId { get; set; } + + /// Denormalized from PlayerCard for query performance. + public Guid CardDefinitionId { get; set; } + + public BazaarListingType ListingType { get; set; } + public decimal Price { get; set; } + public BazaarCurrency Currency { get; set; } + public DateTimeOffset ListedAt { get; set; } + public DateTimeOffset? ExpiresAt { get; set; } + public BazaarListingStatus Status { get; set; } = BazaarListingStatus.Active; + + public ICollection Transactions { get; set; } = new List(); +} diff --git a/Server/src/SOR.Database/Entities/Bazaar/BazaarTransaction.cs b/Server/src/SOR.Database/Entities/Bazaar/BazaarTransaction.cs new file mode 100644 index 0000000..14e0fe2 --- /dev/null +++ b/Server/src/SOR.Database/Entities/Bazaar/BazaarTransaction.cs @@ -0,0 +1,29 @@ +namespace SOR.Database.Entities.Bazaar; + +using SOR.Database.Enums; + +/// +/// Immutable record of a completed bazaar sale. +/// Created when a listing transitions to Sold status. +/// Never updated or deleted — the full audit trail is preserved. +/// +public sealed class BazaarTransaction +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public Guid ListingId { get; set; } + + /// Cross-schema: buyer's account. + public Guid BuyerAccountId { get; set; } + + /// Cross-schema: seller's account (denormalized from listing). + public Guid SellerAccountId { get; set; } + + /// Cross-schema: the card instance that changed hands. + public Guid PlayerCardId { get; set; } + + public decimal Amount { get; set; } + public BazaarCurrency Currency { get; set; } + public DateTimeOffset TransactedAt { get; set; } + + public BazaarListing Listing { get; set; } = null!; +} diff --git a/Server/src/SOR.Database/Entities/Catalog/CardAnimationBinding.cs b/Server/src/SOR.Database/Entities/Catalog/CardAnimationBinding.cs new file mode 100644 index 0000000..5e35585 --- /dev/null +++ b/Server/src/SOR.Database/Entities/Catalog/CardAnimationBinding.cs @@ -0,0 +1,30 @@ +namespace SOR.Database.Entities.Catalog; + +/// +/// Binds a named in-game action to an animation CDN asset for a specific card. +/// +/// ActionName is a free-form string matching the action identifiers used by the +/// game engine and client renderer, e.g.: +/// "idle", "attack", "defend", "death", "channel", +/// "ability_0", "ability_1" (per ability index), +/// "ascend", "transition" +/// +/// This keeps animation bindings flexible — adding new action types requires +/// no schema change, only a new row per card. +/// +public sealed class CardAnimationBinding +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public Guid CardDefinitionId { get; set; } + + /// + /// Action identifier string as expected by the client renderer. + /// Examples: "idle", "attack", "death", "ability_0", "ascend". + /// + public string ActionName { get; set; } = string.Empty; + + /// CDN URL to the animation file (glTF animation, Spine, etc.). + public string AnimationCdnUrl { get; set; } = string.Empty; + + public CardDefinition CardDefinition { get; set; } = null!; +} diff --git a/Server/src/SOR.Database/Entities/Catalog/CardAsset.cs b/Server/src/SOR.Database/Entities/Catalog/CardAsset.cs new file mode 100644 index 0000000..22ad516 --- /dev/null +++ b/Server/src/SOR.Database/Entities/Catalog/CardAsset.cs @@ -0,0 +1,25 @@ +namespace SOR.Database.Entities.Catalog; + +using SOR.Database.Enums; + +/// +/// Links a card definition to one of its static CDN assets (2D art or 3D model). +/// A card may have multiple assets of different types (e.g. one Art2D + one Model3D). +/// Animations are separate — see CardAnimationBinding. +/// +public sealed class CardAsset +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public Guid CardDefinitionId { get; set; } + public CardAssetType AssetType { get; set; } + + /// Full CDN URL, e.g. https://cdn.sor.gg/cards/{id}/art.webp + public string CdnUrl { get; set; } = string.Empty; + + /// MIME type of the asset, e.g. image/webp, model/gltf-binary. + public string? MimeType { get; set; } + + public DateTimeOffset CreatedAt { get; set; } + + public CardDefinition CardDefinition { get; set; } = null!; +} diff --git a/Server/src/SOR.Database/Entities/Catalog/CardDefinition.cs b/Server/src/SOR.Database/Entities/Catalog/CardDefinition.cs new file mode 100644 index 0000000..46a945f --- /dev/null +++ b/Server/src/SOR.Database/Entities/Catalog/CardDefinition.cs @@ -0,0 +1,89 @@ +namespace SOR.Database.Entities.Catalog; + +using SOR.Database.Enums; + +/// +/// The immutable definition of a card — what it IS, not who owns a copy. +/// +/// Core stats are stored as typed columns for fast filtering and sorting +/// (name, type, affinity, costs, combat stats). +/// +/// The ability/effect system is highly recursive and type-specific, so it is +/// stored as JSONB. The game engine and admin tool own serialization. +/// AbilitiesJson: used by ArchSpirit, Spirit, Ruin. +/// EffectsJson: used by Repentance, Instinct, Terramorpha. +/// +/// Genus tags are stored as a Postgres text[] array — fast for containment +/// queries (@>) without the overhead of a junction table. +/// +public sealed class CardDefinition +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + // ── Shared (all card types) ───────────────────────────────────────────── + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public CardType CardType { get; set; } + public Affinity Affinity { get; set; } + public int SpCost { get; set; } + public int StCost { get; set; } + + /// JSONB: additional non-SP/ST costs (e.g. discard a card). + public string? OtherCostsJson { get; set; } + + // ── Unit properties (ArchSpirit + Spirit) ─────────────────────────────── + public int? MinChannelRange { get; set; } + public int? MaxChannelRange { get; set; } + public AttackType? AttackType { get; set; } + public bool? RequiresLos { get; set; } + public int? MinAttackRange { get; set; } + public int? MaxAttackRange { get; set; } + public bool? CanAttack { get; set; } + public int? Damage { get; set; } + public bool? CanDefend { get; set; } + public int? MaxHealth { get; set; } + public int? MaxDefense { get; set; } + public bool? CanBeAttacked { get; set; } + public bool? CanBeBlocked { get; set; } + public bool? CanMove { get; set; } + public MovementType? MovementType { get; set; } + public int? MovementPoints { get; set; } + public bool? CanBeObstructed { get; set; } + public bool? CanUseAbility { get; set; } + + /// Postgres text[]: genus classification tags (e.g. "Elemental", "Beast"). + public string[]? Genus { get; set; } + + // ── Spirit-only ───────────────────────────────────────────────────────── + public bool? CanBeSacrificed { get; set; } + + // ── ArchSpirit-only ───────────────────────────────────────────────────── + /// Tier 1 = base form; higher tiers reached via Ascend/Transition. + public int? Tier { get; set; } + + // ── Terramorpha-only ──────────────────────────────────────────────────── + public TerramorphaMode? TerramorphaMode { get; set; } + + // ── Ability / Effect data (JSONB) ──────────────────────────────────────── + /// JSONB array of AbilityDefinition objects (ArchSpirit, Spirit, Ruin). + public string? AbilitiesJson { get; set; } + + /// JSONB array of Action objects (Repentance, Instinct, Terramorpha). + public string? EffectsJson { get; set; } + + // ── Publishing metadata ────────────────────────────────────────────────── + public CardRarity Rarity { get; set; } = CardRarity.Common; + public Guid? SetId { get; set; } + public int? CollectorNumber { get; set; } + + /// Only published cards are visible in the client and available for collection. + public bool IsPublished { get; set; } + + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset UpdatedAt { get; set; } + + // ── Navigation ─────────────────────────────────────────────────────────── + public CardSet? Set { get; set; } + public ICollection Assets { get; set; } = new List(); + public ICollection AnimationBindings { get; set; } = new List(); +} diff --git a/Server/src/SOR.Database/Entities/Catalog/CardSet.cs b/Server/src/SOR.Database/Entities/Catalog/CardSet.cs new file mode 100644 index 0000000..978a336 --- /dev/null +++ b/Server/src/SOR.Database/Entities/Catalog/CardSet.cs @@ -0,0 +1,25 @@ +namespace SOR.Database.Entities.Catalog; + +/// +/// A named release of cards (base set, expansion, promo, etc.). +/// Cards reference their set for collector numbering and filtering. +/// +public sealed class CardSet +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + /// Human-readable set name, e.g. "Core Set", "Shattered Realms". + public string Name { get; set; } = string.Empty; + + /// Short uppercase code used in collector numbers, e.g. "BASE", "SR1". + public string Code { get; set; } = string.Empty; + + public string? Description { get; set; } + + public DateOnly? ReleaseDate { get; set; } + + /// Whether the set is currently active / legal for play. + public bool IsActive { get; set; } + + public ICollection Cards { get; set; } = new List(); +} diff --git a/Server/src/SOR.Database/Entities/Chat/ChatChannel.cs b/Server/src/SOR.Database/Entities/Chat/ChatChannel.cs new file mode 100644 index 0000000..2ea35ac --- /dev/null +++ b/Server/src/SOR.Database/Entities/Chat/ChatChannel.cs @@ -0,0 +1,18 @@ +namespace SOR.Database.Entities.Chat; + +using SOR.Database.Enums; + +public sealed class ChatChannel +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public string Name { get; set; } = string.Empty; + public ChatChannelType ChannelType { get; set; } + + /// For Match channels: the match ID this channel belongs to. + public string? MatchId { get; set; } + + public DateTimeOffset CreatedAt { get; set; } + + public ICollection Members { get; set; } = new List(); + public ICollection Messages { get; set; } = new List(); +} diff --git a/Server/src/SOR.Database/Entities/Chat/ChatMember.cs b/Server/src/SOR.Database/Entities/Chat/ChatMember.cs new file mode 100644 index 0000000..ff2eb60 --- /dev/null +++ b/Server/src/SOR.Database/Entities/Chat/ChatMember.cs @@ -0,0 +1,17 @@ +namespace SOR.Database.Entities.Chat; + +public sealed class ChatMember +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public Guid ChannelId { get; set; } + + /// Cross-schema: no EF FK to identity.accounts. + public Guid AccountId { get; set; } + + public DateTimeOffset JoinedAt { get; set; } + + /// Set when the member explicitly leaves or is removed. + public DateTimeOffset? LeftAt { get; set; } + + public ChatChannel Channel { get; set; } = null!; +} diff --git a/Server/src/SOR.Database/Entities/Chat/ChatMessage.cs b/Server/src/SOR.Database/Entities/Chat/ChatMessage.cs new file mode 100644 index 0000000..8887e5f --- /dev/null +++ b/Server/src/SOR.Database/Entities/Chat/ChatMessage.cs @@ -0,0 +1,19 @@ +namespace SOR.Database.Entities.Chat; + +public sealed class ChatMessage +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public Guid ChannelId { get; set; } + + /// Cross-schema: no EF FK to identity.accounts. + public Guid SenderAccountId { get; set; } + + public string Content { get; set; } = string.Empty; + public DateTimeOffset SentAt { get; set; } + public DateTimeOffset? EditedAt { get; set; } + + /// Soft-delete: content is cleared but the row is kept for audit. + public bool IsDeleted { get; set; } + + public ChatChannel Channel { get; set; } = null!; +} diff --git a/Server/src/SOR.Database/Entities/Collection/Deck.cs b/Server/src/SOR.Database/Entities/Collection/Deck.cs new file mode 100644 index 0000000..8e78bb7 --- /dev/null +++ b/Server/src/SOR.Database/Entities/Collection/Deck.cs @@ -0,0 +1,34 @@ +namespace SOR.Database.Entities.Collection; + +/// +/// A named deck belonging to a player. +/// Each deck has exactly one ArchSpirit and any number of other cards. +/// IsValid is set by the server after validating against current deck construction rules. +/// +public sealed class Deck +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + /// Owner. Cross-schema: no EF FK to identity.accounts. + public Guid AccountId { get; set; } + + public string Name { get; set; } = string.Empty; + public string? Description { get; set; } + + /// + /// The ArchSpirit card definition this deck is built around. + /// Cross-schema: no EF FK to catalog.card_definitions. + /// + public Guid ArchSpiritCardDefinitionId { get; set; } + + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset UpdatedAt { get; set; } + + /// + /// True when last validated against deck construction rules. + /// Re-validated on each change and at match start. + /// + public bool IsValid { get; set; } + + public ICollection Cards { get; set; } = new List(); +} diff --git a/Server/src/SOR.Database/Entities/Collection/DeckCard.cs b/Server/src/SOR.Database/Entities/Collection/DeckCard.cs new file mode 100644 index 0000000..fc4830b --- /dev/null +++ b/Server/src/SOR.Database/Entities/Collection/DeckCard.cs @@ -0,0 +1,18 @@ +namespace SOR.Database.Entities.Collection; + +/// +/// One card slot in a deck: which card definition and how many copies. +/// Cross-schema: CardDefinitionId is a bare Guid with no EF FK. +/// +public sealed class DeckCard +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public Guid DeckId { get; set; } + + /// Cross-schema: no EF FK to catalog.card_definitions. + public Guid CardDefinitionId { get; set; } + + public int Quantity { get; set; } = 1; + + public Deck Deck { get; set; } = null!; +} diff --git a/Server/src/SOR.Database/Entities/Collection/PlayerCard.cs b/Server/src/SOR.Database/Entities/Collection/PlayerCard.cs new file mode 100644 index 0000000..6e7bf99 --- /dev/null +++ b/Server/src/SOR.Database/Entities/Collection/PlayerCard.cs @@ -0,0 +1,29 @@ +namespace SOR.Database.Entities.Collection; + +/// +/// One physical copy of a card owned by a player. +/// +/// CardDefinitionId references the catalog schema — intentionally no EF FK +/// (cross-schema references are by Guid only). +/// +/// Multiple copies of the same CardDefinitionId may exist per account; +/// each row is a distinct, individually tradeable instance. +/// +public sealed class PlayerCard +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + /// Owning player. Cross-schema: no EF FK to identity.accounts. + public Guid AccountId { get; set; } + + /// Template definition. Cross-schema: no EF FK to catalog.card_definitions. + public Guid CardDefinitionId { get; set; } + + public DateTimeOffset AcquiredAt { get; set; } + + /// Foil/premium visual variant of the card art. + public bool IsFoil { get; set; } + + /// Sequential print number for limited/numbered cards. Null = unlimited. + public int? SerialNumber { get; set; } +} diff --git a/Server/src/SOR.Database/Entities/Identity/Account.cs b/Server/src/SOR.Database/Entities/Identity/Account.cs new file mode 100644 index 0000000..d2140ac --- /dev/null +++ b/Server/src/SOR.Database/Entities/Identity/Account.cs @@ -0,0 +1,28 @@ +namespace SOR.Database.Entities.Identity; + +using Microsoft.AspNetCore.Identity; + +/// +/// Extends ASP.NET Core Identity's IdentityUser with SOR-specific profile fields. +/// +/// Identity manages: email, password hash, lockout, two-factor, external logins. +/// We add: display name (in-game handle), avatar CDN URL, audit timestamps. +/// +/// Ban handling uses Identity's built-in LockoutEnd + LockoutEnabled — no +/// separate ban table needed for basic bans. A separate audit log of ban +/// actions can be added later. +/// +public sealed class Account : IdentityUser +{ + /// Publicly visible in-game display name (not the login email). + public string? DisplayName { get; set; } + + /// CDN URL to the player's avatar image. + public string? AvatarCdnUrl { get; set; } + + /// UTC time the account was first created. + public DateTimeOffset CreatedAt { get; set; } + + /// UTC time of the most recent successful login. + public DateTimeOffset? LastLoginAt { get; set; } +} diff --git a/Server/src/SOR.Database/Entities/Identity/AccountSession.cs b/Server/src/SOR.Database/Entities/Identity/AccountSession.cs new file mode 100644 index 0000000..ada6f2e --- /dev/null +++ b/Server/src/SOR.Database/Entities/Identity/AccountSession.cs @@ -0,0 +1,34 @@ +namespace SOR.Database.Entities.Identity; + +/// +/// Tracks an issued session token so it can be explicitly revoked +/// (logout, password change, ban) before it naturally expires. +/// +/// The raw token is never stored — only its SHA-256 hash is kept so +/// that a stolen database row cannot be replayed. +/// +/// The Gateway validates tokens by hashing the incoming token and +/// looking it up here, checking RevokedAt == null and ExpiresAt > now. +/// +public sealed class AccountSession +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + /// Owner of this session. No FK to preserve cross-schema flexibility. + public Guid AccountId { get; set; } + + /// SHA-256 hex digest of the raw session token. + public string TokenHash { get; set; } = string.Empty; + + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset ExpiresAt { get; set; } + + /// Set when the session is explicitly invalidated (logout, ban, password change). + public DateTimeOffset? RevokedAt { get; set; } + + public string? IpAddress { get; set; } + public string? UserAgent { get; set; } + + /// Optional opaque device identifier supplied by the client. + public string? DeviceId { get; set; } +} diff --git a/Server/src/SOR.Database/Enums/Affinity.cs b/Server/src/SOR.Database/Enums/Affinity.cs new file mode 100644 index 0000000..6a6c5e0 --- /dev/null +++ b/Server/src/SOR.Database/Enums/Affinity.cs @@ -0,0 +1,47 @@ +namespace SOR.Database.Enums; + +/// +/// All valid card/tile affinity values. +/// +/// Basic affinities (the six primaries): Void, Aether, Lake, Hill, Forest, Field. +/// Non-basic affinities are combinations of two basics via the tile slot system +/// (Base1 + Base2). See affinity.md for full combination rules. +/// +/// Cards may only carry basic and standard non-basic affinities. +/// Gateway and UnstableAether affinities are tile-only — they cannot appear on cards. +/// +public enum Affinity +{ + // ── Basic ────────────────────────────────────────────────────────────── + Void, + Aether, + Lake, + Hill, + Forest, + Field, + + // ── Standard non-basic (two-basic combinations) ─────────────────────── + Ocean, // Lake + Lake + Island, // Lake + Hill + Marsh, // Lake + Forest + Swamp, // Lake + Field + Mountain, // Hill + Hill + Steppe, // Hill + Forest + Fort, // Hill + Field + Plains, // Forest + Field + Grove, // Forest + Forest + Jungle, // Field + Field + + // ── Aether combinations ─────────────────────────────────────────────── + UnstableAether, // Aether + any non-Aether (tile-only, cannot appear on cards) + PerfectAether, // Aether + Aether + + // ── Void combinations ───────────────────────────────────────────────── + PureVoid, // Void + Void + + // ── Gateway (Void + one basic, tile-only) ───────────────────────────── + GatewayLake, + GatewayHill, + GatewayForest, + GatewayField, +} diff --git a/Server/src/SOR.Database/Enums/BazaarEnums.cs b/Server/src/SOR.Database/Enums/BazaarEnums.cs new file mode 100644 index 0000000..5d5e647 --- /dev/null +++ b/Server/src/SOR.Database/Enums/BazaarEnums.cs @@ -0,0 +1,28 @@ +namespace SOR.Database.Enums; + +public enum BazaarListingStatus +{ + Active, + Sold, + Cancelled, + Expired, +} + +public enum BazaarListingType +{ + /// Buy-it-now at a fixed price. + Fixed, + /// Timed auction — highest bid wins. + Auction, +} + +/// +/// In-game currency types. +/// Gold: earned through gameplay, tradeable. +/// Premium: purchased with real money, non-tradeable. +/// +public enum BazaarCurrency +{ + Gold, + Premium, +} diff --git a/Server/src/SOR.Database/Enums/CardEnums.cs b/Server/src/SOR.Database/Enums/CardEnums.cs new file mode 100644 index 0000000..e046177 --- /dev/null +++ b/Server/src/SOR.Database/Enums/CardEnums.cs @@ -0,0 +1,67 @@ +namespace SOR.Database.Enums; + +public enum CardType +{ + ArchSpirit, + Spirit, + Repentance, + Terramorpha, + Ruin, + Instinct, +} + +/// +/// How a unit's attack is resolved on the battlefield. +/// The exact attack resolution rules are defined in gameplay.md. +/// +public enum AttackType +{ + Melee, + Ranged, +} + +/// +/// Governs how a unit traverses the battlefield. +/// Walk: blocked by any unit. +/// Flight: blocked by other Flight units only. +/// Jump: unblocked, min/max tile range, costs 1 MP per landing tile. +/// Teleport: unblocked, min/max range, requires line-of-sight, costs 1 MP per tile. +/// +public enum MovementType +{ + Walk, + Flight, + Jump, + Teleport, +} + +/// +/// How many affinity tiles a Terramorpha card affects when channeled. +/// Mono = 1 tile, Di = 2 adjacent tiles, Tri = 3 adjacent tiles. +/// +public enum TerramorphaMode +{ + Mono, + Di, + Tri, +} + +public enum CardRarity +{ + Common, + Uncommon, + Rare, + Epic, + Legendary, +} + +/// +/// Discriminates the type of CDN asset linked to a card. +/// Art2D: flat card illustration shown in hand/collection views. +/// Model3D: glTF/GLB model rendered on the battlefield. +/// +public enum CardAssetType +{ + Art2D, + Model3D, +} diff --git a/Server/src/SOR.Database/Enums/ChatEnums.cs b/Server/src/SOR.Database/Enums/ChatEnums.cs new file mode 100644 index 0000000..c0727db --- /dev/null +++ b/Server/src/SOR.Database/Enums/ChatEnums.cs @@ -0,0 +1,13 @@ +namespace SOR.Database.Enums; + +public enum ChatChannelType +{ + /// Server-wide public chat. + Global, + /// Private channel for an active match. + Match, + /// Direct message between two accounts. + Direct, + /// Guild/clan channel. + Guild, +} diff --git a/Server/src/SOR.Database/SOR.Database.csproj b/Server/src/SOR.Database/SOR.Database.csproj new file mode 100644 index 0000000..20abe7a --- /dev/null +++ b/Server/src/SOR.Database/SOR.Database.csproj @@ -0,0 +1,19 @@ + + + SOR.Database + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/Server/src/SOR.Database/ServiceRegistration.cs b/Server/src/SOR.Database/ServiceRegistration.cs new file mode 100644 index 0000000..5ab4e3e --- /dev/null +++ b/Server/src/SOR.Database/ServiceRegistration.cs @@ -0,0 +1,74 @@ +namespace SOR.Database; + +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using SOR.Database.Contexts; + +/// +/// Extension methods to register each DbContext independently. +/// Each service only calls the extension(s) it needs. +/// +/// All contexts fall back to "Default" if a context-specific connection string +/// is absent, so a single connection string works during local development +/// while production can split contexts across servers by overriding individual keys. +/// +/// Connection string key precedence (highest to lowest): +/// ConnectionStrings:{ContextName} → ConnectionStrings:Default +/// +public static class ServiceRegistration +{ + public static IServiceCollection AddIdentityDatabase( + this IServiceCollection services, + IConfiguration configuration) + { + services.AddDbContext(opts => + opts.UseNpgsql(Resolve(configuration, "Identity"))); + return services; + } + + public static IServiceCollection AddCatalogDatabase( + this IServiceCollection services, + IConfiguration configuration) + { + services.AddDbContext(opts => + opts.UseNpgsql(Resolve(configuration, "Catalog"))); + return services; + } + + public static IServiceCollection AddCollectionDatabase( + this IServiceCollection services, + IConfiguration configuration) + { + services.AddDbContext(opts => + opts.UseNpgsql(Resolve(configuration, "Collection"))); + return services; + } + + public static IServiceCollection AddBazaarDatabase( + this IServiceCollection services, + IConfiguration configuration) + { + services.AddDbContext(opts => + opts.UseNpgsql(Resolve(configuration, "Bazaar"))); + return services; + } + + public static IServiceCollection AddChatDatabase( + this IServiceCollection services, + IConfiguration configuration) + { + services.AddDbContext(opts => + opts.UseNpgsql(Resolve(configuration, "Chat"))); + return services; + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + private static string Resolve(IConfiguration configuration, string contextName) + => configuration.GetConnectionString(contextName) + ?? configuration.GetConnectionString("Default") + ?? throw new InvalidOperationException( + $"Missing connection string: '{contextName}' or 'Default'. " + + "Add it to appsettings.json or environment variables."); +}