From bdd6e59dfeeac4960f54296defcdaaaa188a50b3 Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 28 Feb 2026 13:08:08 -0500 Subject: [PATCH] Add starter deck flow, admin force-logout + rename, shop flag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auth chain: - auth.proto: add needs_starter_deck to Login/Register/ValidateToken responses - auth.proto: add RevokeAllSessions RPC - AuthGrpcHandler: populate NeedsStarterDeck from Account.StarterDeckSelectedAt - AuthGrpcHandler: track tokens in UserSessions Redis SET on create/logout - AuthGrpcHandler: implement RevokeAllSessions (Redis + Postgres) - IGatewayAuthValidator / GatewayAuthValidator: thread NeedsStarterDeck through tuples - ConnectionLoop: include needsStarterDeck in auth ack payload Client: - Auth.gd: store needs_starter_deck from auth reply; clear on logout - login_screen.gd: route to StarterDeckScreen when needs_starter_deck = true - scenes/starter_deck/: new StarterDeckScreen (fetch decks → pick → confirm → InitScreen) Admin panel: - AccountDetail.razor: Force Logout All Sessions card (Redis + Postgres revoke) - AccountDetail.razor: Change Display Name form with uniqueness check - SOR.Admin: add StackExchange.Redis package + DI registration - PrebuiltDeckEditor.razor: split into IsStarterDeck + IsAvailableInShop checkboxes - PrebuiltDeck.cs: add IsAvailableInShop field - Migration: AddPrebuiltDeckShopFlag Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- Client/origin-client/autoloads/Auth.gd | 24 +- .../scenes/login/login_screen.gd | 5 +- .../starter_deck/StarterDeckScreen.tscn | 81 +++ .../starter_deck/starter_deck_screen.gd | 168 ++++++ .../Pages/Accounts/AccountDetail.razor | 121 +++++ .../Pages/Bazaar/PrebuiltDeckEditor.razor | 10 +- Server/src/SOR.Admin/Program.cs | 6 + Server/src/SOR.Admin/SOR.Admin.csproj | 2 + .../src/SOR.Auth/Handlers/AuthGrpcHandler.cs | 73 ++- .../Entities/Bazaar/PrebuiltDeck.cs | 6 + ...175431_AddPrebuiltDeckShopFlag.Designer.cs | 481 ++++++++++++++++++ .../20260228175431_AddPrebuiltDeckShopFlag.cs | 31 ++ .../Bazaar/BazaarDbContextModelSnapshot.cs | 3 + .../SOR.Gateway/Auth/GatewayAuthValidator.cs | 26 +- .../SOR.Gateway/Auth/IGatewayAuthValidator.cs | 6 +- Server/src/SOR.Gateway/ConnectionLoop.cs | 22 +- Server/src/SOR.Shared.Proto/Protos/auth.proto | 21 + 17 files changed, 1036 insertions(+), 50 deletions(-) create mode 100644 Client/origin-client/scenes/starter_deck/StarterDeckScreen.tscn create mode 100644 Client/origin-client/scenes/starter_deck/starter_deck_screen.gd create mode 100644 Server/src/SOR.Database/Migrations/Bazaar/20260228175431_AddPrebuiltDeckShopFlag.Designer.cs create mode 100644 Server/src/SOR.Database/Migrations/Bazaar/20260228175431_AddPrebuiltDeckShopFlag.cs diff --git a/Client/origin-client/autoloads/Auth.gd b/Client/origin-client/autoloads/Auth.gd index 130587c..4f3e1df 100644 --- a/Client/origin-client/autoloads/Auth.gd +++ b/Client/origin-client/autoloads/Auth.gd @@ -27,9 +27,13 @@ signal auth_failed(error_code: String, message: String) signal session_expired ## Fired when the disconnect timeout logs the user out. ## Set after a successful auth. Empty while unauthenticated. -var user_id: String = "" -var display_name: String = "" -var session_token: String = "" +var user_id: String = "" +var display_name: String = "" +var session_token: String = "" +## True when the authenticated account has not yet selected a starter deck. +## Reset to false on logout. Checked by login_screen.gd to route new players +## to StarterDeckScreen instead of the normal InitScreen flow. +var needs_starter_deck: bool = false ## Monotonic timestamp (seconds) when the last disconnect started; -1 = connected. var _disconnect_at: float = -1.0 @@ -77,9 +81,10 @@ func register(email: String, password: String, disp_name: String) -> void: ## Clear the saved session and reset auth state. func logout() -> void: - user_id = "" - display_name = "" - session_token = "" + user_id = "" + display_name = "" + session_token = "" + needs_starter_deck = false _save_session() # ── Private ─────────────────────────────────────────────────────────────────── @@ -114,9 +119,10 @@ func _on_network_disconnected() -> void: func _on_auth_ok(payload: Variant) -> void: var p := payload as Dictionary - user_id = p.get("userId", "") - display_name = p.get("displayName", "") - session_token = p.get("sessionToken", "") + user_id = p.get("userId", "") + display_name = p.get("displayName", "") + session_token = p.get("sessionToken", "") + needs_starter_deck = p.get("needsStarterDeck", false) _save_session() auth_success.emit(user_id, display_name) diff --git a/Client/origin-client/scenes/login/login_screen.gd b/Client/origin-client/scenes/login/login_screen.gd index 320b37e..0280ce4 100644 --- a/Client/origin-client/scenes/login/login_screen.gd +++ b/Client/origin-client/scenes/login/login_screen.gd @@ -95,7 +95,10 @@ func _on_auth_failed(error_code: String, message: String) -> void: # ── Helpers ─────────────────────────────────────────────────────────────────── func _go_to_main() -> void: - get_tree().change_scene_to_file("res://scenes/init/InitScreen.tscn") + if Auth.needs_starter_deck: + get_tree().change_scene_to_file("res://scenes/starter_deck/StarterDeckScreen.tscn") + else: + get_tree().change_scene_to_file("res://scenes/init/InitScreen.tscn") func _set_status(text: String, is_error: bool) -> void: diff --git a/Client/origin-client/scenes/starter_deck/StarterDeckScreen.tscn b/Client/origin-client/scenes/starter_deck/StarterDeckScreen.tscn new file mode 100644 index 0000000..a807dfd --- /dev/null +++ b/Client/origin-client/scenes/starter_deck/StarterDeckScreen.tscn @@ -0,0 +1,81 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://scenes/starter_deck/starter_deck_screen.gd" id="1_sds"] + +[node name="StarterDeckScreen" type="Control"] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +script = ExtResource("1_sds") + +[node name="Background" type="ColorRect" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +color = Color(0.094, 0.094, 0.137, 1.0) + +[node name="OuterMargin" type="MarginContainer" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +theme_override_constants/margin_left = 40 +theme_override_constants/margin_right = 40 +theme_override_constants/margin_top = 32 +theme_override_constants/margin_bottom = 32 + +[node name="Layout" type="VBoxContainer" parent="OuterMargin"] +layout_mode = 2 +theme_override_constants/separation = 16 + +[node name="TitleLabel" type="Label" parent="OuterMargin/Layout"] +layout_mode = 2 +text = "Choose Your Starter Deck" +horizontal_alignment = 1 +theme_override_font_sizes/font_size = 28 + +[node name="SubLabel" type="Label" parent="OuterMargin/Layout"] +layout_mode = 2 +text = "Select a deck to begin your journey. This choice is permanent." +horizontal_alignment = 1 +modulate = Color(0.7, 0.7, 0.8, 1.0) +theme_override_font_sizes/font_size = 13 + +[node name="HSeparator" type="HSeparator" parent="OuterMargin/Layout"] +layout_mode = 2 + +[node name="StatusLabel" type="Label" parent="OuterMargin/Layout"] +unique_name_in_owner = true +layout_mode = 2 +text = "Loading…" +horizontal_alignment = 1 +autowrap_mode = 3 +modulate = Color(0.75, 0.75, 0.8, 1.0) +theme_override_font_sizes/font_size = 13 + +[node name="Scroll" type="ScrollContainer" parent="OuterMargin/Layout"] +layout_mode = 2 +size_flags_vertical = 3 +horizontal_scroll_mode = 0 + +[node name="DeckList" type="VBoxContainer" parent="OuterMargin/Layout/Scroll"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +theme_override_constants/separation = 10 + +[node name="ConfirmBtn" type="Button" parent="OuterMargin/Layout"] +unique_name_in_owner = true +layout_mode = 2 +custom_minimum_size = Vector2(0, 48) +text = "Choose This Deck" +disabled = true +theme_override_font_sizes/font_size = 16 diff --git a/Client/origin-client/scenes/starter_deck/starter_deck_screen.gd b/Client/origin-client/scenes/starter_deck/starter_deck_screen.gd new file mode 100644 index 0000000..fadae2a --- /dev/null +++ b/Client/origin-client/scenes/starter_deck/starter_deck_screen.gd @@ -0,0 +1,168 @@ +extends Control +## Starter deck selection screen — shown to new players immediately after auth. +## +## Flow: +## 1. Send collection.get_starter_decks → populate deck list. +## 2. Player taps a deck item to select it (highlighted border). +## 3. "Choose This Deck" button becomes enabled; player confirms. +## 4. Send collection.select_starter_deck { starterDeckId }. +## 5. On success: set Auth.needs_starter_deck = false → navigate to InitScreen. + +@onready var status_label : Label = %StatusLabel +@onready var deck_list : VBoxContainer = %DeckList +@onready var confirm_btn : Button = %ConfirmBtn + +const SEL_COLOR := Color(0.36, 0.56, 1.0, 1.0) +const DEF_COLOR := Color(0.25, 0.25, 0.35, 1.0) + +var _selected_id: String = "" +var _confirming: bool = false + +# ── Lifecycle ───────────────────────────────────────────────────────────────── + +func _ready() -> void: + confirm_btn.disabled = true + confirm_btn.pressed.connect(_on_confirm_pressed) + _fetch_decks() + +# ── Deck fetch ──────────────────────────────────────────────────────────────── + +func _fetch_decks() -> void: + status_label.text = "Loading starter decks…" + status_label.visible = true + deck_list.visible = false + + Network.request( + "collection.get_starter_decks", + {}, + func(_type: String, p: Variant): _on_decks_ok(p), + func(code: String, _msg: String): _on_decks_error(code) + ) + + +func _on_decks_ok(payload: Variant) -> void: + var p := payload as Dictionary + var decks := p.get("decks", []) as Array + + if decks.is_empty(): + status_label.text = "No starter decks are available right now. Please contact support." + return + + status_label.visible = false + deck_list.visible = true + _populate_list(decks) + + +func _on_decks_error(code: String) -> void: + status_label.text = "Failed to load starter decks (%s). Check your connection." % code + +# ── Deck list ───────────────────────────────────────────────────────────────── + +func _populate_list(decks: Array) -> void: + for child in deck_list.get_children(): + child.queue_free() + + for deck in decks: + var d := deck as Dictionary + var id := d.get("id", "") as String + deck_list.add_child(_build_card(d, id)) + + +func _build_card(d: Dictionary, id: String) -> Button: + var btn := Button.new() + btn.name = "Deck_%s" % id + btn.flat = false + btn.focus_mode = Control.FOCUS_CLICK + btn.size_flags_horizontal = Control.SIZE_FILL + _apply_card_style(btn, false) + + var inner := VBoxContainer.new() + inner.add_theme_constant_override("separation", 5) + btn.add_child(inner) + + # Deck name + var name_lbl := Label.new() + name_lbl.text = d.get("name", "Unknown Deck") + name_lbl.add_theme_font_size_override("font_size", 16) + inner.add_child(name_lbl) + + # ArchSpirit · card count + var arch : String = d.get("archSpiritName", "") + var total : int = d.get("totalCards", 0) + var sub_lbl := Label.new() + sub_lbl.text = ("%s · %d cards" % [arch, total]) if not arch.is_empty() \ + else ("%d cards" % total) + sub_lbl.modulate = Color(0.7, 0.7, 0.8) + sub_lbl.add_theme_font_size_override("font_size", 12) + inner.add_child(sub_lbl) + + # Optional description + var desc : String = d.get("description", "") + if not desc.is_empty(): + var desc_lbl := Label.new() + desc_lbl.text = desc + desc_lbl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + desc_lbl.modulate = Color(0.65, 0.65, 0.75) + desc_lbl.add_theme_font_size_override("font_size", 11) + inner.add_child(desc_lbl) + + btn.pressed.connect(func(): _select_deck(id)) + return btn + + +func _apply_card_style(btn: Button, selected: bool, + bg: Color = Color(0.13, 0.13, 0.20, 1.0)) -> void: + var make := func(b: Color) -> StyleBoxFlat: + var s := StyleBoxFlat.new() + s.bg_color = b + s.border_color = SEL_COLOR if selected else DEF_COLOR + s.set_border_width_all(2) + s.set_corner_radius_all(6) + s.content_margin_left = 14 + s.content_margin_right = 14 + s.content_margin_top = 12 + s.content_margin_bottom = 12 + return s + btn.add_theme_stylebox_override("normal", make.call(bg)) + btn.add_theme_stylebox_override("hover", make.call(Color(0.20, 0.20, 0.30, 1.0))) + btn.add_theme_stylebox_override("pressed", make.call(bg)) + btn.add_theme_stylebox_override("focus", make.call(bg)) + + +func _select_deck(id: String) -> void: + _selected_id = id + for child in deck_list.get_children(): + var btn := child as Button + if btn == null: + continue + _apply_card_style(btn, btn.name == ("Deck_%s" % id)) + confirm_btn.disabled = false + +# ── Confirm ─────────────────────────────────────────────────────────────────── + +func _on_confirm_pressed() -> void: + if _selected_id.is_empty() or _confirming: + return + _confirming = true + confirm_btn.disabled = true + status_label.text = "Claiming your starter deck…" + status_label.visible = true + + Network.request( + "collection.select_starter_deck", + { "starterDeckId": _selected_id }, + func(_type: String, _p: Variant): _on_select_ok(), + func(code: String, msg: String): _on_select_error(code, msg) + ) + + +func _on_select_ok() -> void: + Auth.needs_starter_deck = false + get_tree().change_scene_to_file("res://scenes/init/InitScreen.tscn") + + +func _on_select_error(code: String, msg: String) -> void: + _confirming = false + confirm_btn.disabled = false + status_label.text = "Could not select deck (%s): %s" % [code, msg] + status_label.visible = true diff --git a/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor b/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor index db076d6..b987e62 100644 --- a/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor +++ b/Server/src/SOR.Admin/Components/Pages/Accounts/AccountDetail.razor @@ -3,7 +3,10 @@ @inject SorIdentityDbContext Db @inject UserManager UserManager @inject NavigationManager Nav +@inject IConnectionMultiplexer Redis @using Microsoft.AspNetCore.Identity +@using StackExchange.Redis +@using SOR.Shared.Redis Account – SOR Admin @@ -189,6 +192,49 @@ else + + +
+
+
Change Display Name
+
+
+ + +
+ +
+
+
+ + +
+
+
Force Logout All Sessions
+
+

+ Revokes every active session token for this account in both Redis and + the database. The player will be disconnected immediately and must log + in again on all devices. +

+ +
+
+
} @@ -207,6 +253,8 @@ else private string _newPassword = ""; private string _confirmPassword = ""; + private string _newDisplayName = ""; + private bool _forceLoggingOut; protected override async Task OnInitializedAsync() { @@ -311,4 +359,77 @@ else _isError = false; RefreshStatus(); } + + private async Task ChangeDisplayNameAsync() + { + if (_account == null) return; + + var name = _newDisplayName.Trim(); + if (string.IsNullOrEmpty(name)) + { + _message = "Display name cannot be empty."; + _isError = true; + return; + } + + var taken = await UserManager.Users.AnyAsync(u => u.DisplayName == name && u.Id != _account.Id); + if (taken) + { + _message = "That display name is already taken."; + _isError = true; + return; + } + + _account.DisplayName = name; + var result = await UserManager.UpdateAsync(_account); + if (result.Succeeded) + { + _message = $"Display name changed to \"{name}\"."; + _isError = false; + _newDisplayName = ""; + } + else + { + _message = string.Join(" ", result.Errors.Select(e => e.Description)); + _isError = true; + } + } + + private async Task ForceLogoutAsync() + { + if (_account == null) return; + _forceLoggingOut = true; + try + { + var cache = Redis.GetDatabase(); + var userKey = RedisKeys.UserSessions(_account.Id.ToString()); + + // Remove all session keys from Redis. + var members = await cache.SetMembersAsync(userKey); + foreach (var m in members) + await cache.KeyDeleteAsync(RedisKeys.Session(m!)); + await cache.KeyDeleteAsync(userKey); + + // Revoke all active Postgres sessions. + var now = DateTimeOffset.UtcNow; + var sessions = await Db.AccountSessions + .Where(s => s.AccountId == _account.Id && s.RevokedAt == null && s.ExpiresAt > now) + .ToListAsync(); + foreach (var s in sessions) + s.RevokedAt = now; + await Db.SaveChangesAsync(); + + _message = $"Revoked {sessions.Count} session(s). The player has been logged out."; + _isError = false; + } + catch (Exception ex) + { + _message = $"Force logout failed: {ex.Message}"; + _isError = true; + } + finally + { + _forceLoggingOut = false; + } + } } diff --git a/Server/src/SOR.Admin/Components/Pages/Bazaar/PrebuiltDeckEditor.razor b/Server/src/SOR.Admin/Components/Pages/Bazaar/PrebuiltDeckEditor.razor index fc0549b..183b54d 100644 --- a/Server/src/SOR.Admin/Components/Pages/Bazaar/PrebuiltDeckEditor.razor +++ b/Server/src/SOR.Admin/Components/Pages/Bazaar/PrebuiltDeckEditor.razor @@ -67,7 +67,7 @@ else class="form-control" placeholder="—" /> -
+
@@ -75,7 +75,13 @@ else
+
+
+ +
diff --git a/Server/src/SOR.Admin/Program.cs b/Server/src/SOR.Admin/Program.cs index 4f6308a..a3eeb4c 100644 --- a/Server/src/SOR.Admin/Program.cs +++ b/Server/src/SOR.Admin/Program.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; +using StackExchange.Redis; using SOR.Admin; using SOR.Admin.Components; using SOR.Cdn; @@ -71,6 +72,11 @@ builder.Services.AddIdentityCore(options => // ── Razor Pages (used for login/logout form posts) ───────────────────────── builder.Services.AddRazorPages(); +// ── Redis ────────────────────────────────────────────────────────────────── +builder.Services.AddSingleton(_ => + ConnectionMultiplexer.Connect( + builder.Configuration.GetConnectionString("Redis") ?? "localhost:6379")); + // ── CDN client ──────────────────────────────────────────────────────────── builder.Services.AddCdnClient(builder.Configuration); diff --git a/Server/src/SOR.Admin/SOR.Admin.csproj b/Server/src/SOR.Admin/SOR.Admin.csproj index 484ac9d..06a04b7 100644 --- a/Server/src/SOR.Admin/SOR.Admin.csproj +++ b/Server/src/SOR.Admin/SOR.Admin.csproj @@ -11,6 +11,8 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + + diff --git a/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs b/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs index 177a2db..7297334 100644 --- a/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs +++ b/Server/src/SOR.Auth/Handlers/AuthGrpcHandler.cs @@ -74,7 +74,12 @@ public sealed class AuthGrpcHandler : AuthService.AuthServiceBase var token = await CreateSessionAsync(user.Id, context); _logger.LogInformation("Login succeeded for account {AccountId}", user.Id); - return new LoginResponse { Success = true, SessionToken = token }; + return new LoginResponse + { + Success = true, + SessionToken = token, + NeedsStarterDeck = !user.StarterDeckSelectedAt.HasValue, + }; } // ── Register ────────────────────────────────────────────────────────────── @@ -108,7 +113,12 @@ public sealed class AuthGrpcHandler : AuthService.AuthServiceBase var token = await CreateSessionAsync(account.Id, context); _logger.LogInformation("Registered new account {AccountId}", account.Id); - return new RegisterResponse { Success = true, SessionToken = token }; + return new RegisterResponse + { + Success = true, + SessionToken = token, + NeedsStarterDeck = true, // new accounts always need to select a starter deck + }; } // ── ValidateToken ───────────────────────────────────────────────────────── @@ -129,9 +139,10 @@ public sealed class AuthGrpcHandler : AuthService.AuthServiceBase if (cached is not null) return new ValidateTokenResponse { - Valid = true, - UserId = cached.Id.ToString(), - DisplayName = cached.DisplayName ?? string.Empty, + Valid = true, + UserId = cached.Id.ToString(), + DisplayName = cached.DisplayName ?? string.Empty, + NeedsStarterDeck = !cached.StarterDeckSelectedAt.HasValue, }; } @@ -160,9 +171,10 @@ public sealed class AuthGrpcHandler : AuthService.AuthServiceBase return new ValidateTokenResponse { - Valid = true, - UserId = account.Id.ToString(), - DisplayName = account.DisplayName ?? string.Empty, + Valid = true, + UserId = account.Id.ToString(), + DisplayName = account.DisplayName ?? string.Empty, + NeedsStarterDeck = !account.StarterDeckSelectedAt.HasValue, }; } @@ -181,6 +193,10 @@ public sealed class AuthGrpcHandler : AuthService.AuthServiceBase { session.RevokedAt = DateTimeOffset.UtcNow; await _db.SaveChangesAsync(); + var cache2 = _redis.GetDatabase(); + await cache2.SetRemoveAsync( + RedisKeys.UserSessions(session.AccountId.ToString()), + request.SessionToken); } await _redis.GetDatabase().KeyDeleteAsync(RedisKeys.Session(request.SessionToken)); @@ -188,6 +204,39 @@ public sealed class AuthGrpcHandler : AuthService.AuthServiceBase return new LogoutResponse(); } + // ── RevokeAllSessions ───────────────────────────────────────────────────── + + public override async Task RevokeAllSessions( + RevokeAllSessionsRequest request, ServerCallContext context) + { + if (!Guid.TryParse(request.AccountId, out var accountId)) + return new RevokeAllSessionsResponse { SessionsRevoked = 0 }; + + var now = DateTimeOffset.UtcNow; + var cache = _redis.GetDatabase(); + var userKey = RedisKeys.UserSessions(accountId.ToString()); + + // Grab all raw tokens from the Redis SET, then delete each session key. + var members = await cache.SetMembersAsync(userKey); + foreach (var member in members) + await cache.KeyDeleteAsync(RedisKeys.Session(member!)); + await cache.KeyDeleteAsync(userKey); + + // Revoke all active Postgres sessions for this account. + var sessions = await _db.AccountSessions + .Where(s => s.AccountId == accountId && s.RevokedAt == null && s.ExpiresAt > now) + .ToListAsync(); + + foreach (var s in sessions) + s.RevokedAt = now; + + await _db.SaveChangesAsync(); + + _logger.LogInformation("Revoked {Count} sessions for account {AccountId}", + sessions.Count, accountId); + return new RevokeAllSessionsResponse { SessionsRevoked = sessions.Count }; + } + // ── Account Properties ──────────────────────────────────────────────────── public override async Task GetAccountProperty( @@ -322,10 +371,10 @@ public sealed class AuthGrpcHandler : AuthService.AuthServiceBase }); await _db.SaveChangesAsync(); - await _redis.GetDatabase().StringSetAsync( - RedisKeys.Session(token), - accountId.ToString(), - expiry - DateTimeOffset.UtcNow); + var ttl = expiry - DateTimeOffset.UtcNow; + var cache = _redis.GetDatabase(); + await cache.StringSetAsync(RedisKeys.Session(token), accountId.ToString(), ttl); + await cache.SetAddAsync(RedisKeys.UserSessions(accountId.ToString()), token); return token; } diff --git a/Server/src/SOR.Database/Entities/Bazaar/PrebuiltDeck.cs b/Server/src/SOR.Database/Entities/Bazaar/PrebuiltDeck.cs index f0ee2f5..514c8a5 100644 --- a/Server/src/SOR.Database/Entities/Bazaar/PrebuiltDeck.cs +++ b/Server/src/SOR.Database/Entities/Bazaar/PrebuiltDeck.cs @@ -33,6 +33,12 @@ public sealed class PrebuiltDeck /// public bool IsStarterDeck { get; set; } + /// + /// When true this deck is purchasable in the Bazaar shop (in addition to or instead + /// of the starter-deck flow). A deck may have both flags set simultaneously. + /// + public bool IsAvailableInShop { get; set; } + /// Cross-schema: the ArchSpirit card included in this deck. Bare Guid. public Guid? ArchSpiritCardDefinitionId { get; set; } diff --git a/Server/src/SOR.Database/Migrations/Bazaar/20260228175431_AddPrebuiltDeckShopFlag.Designer.cs b/Server/src/SOR.Database/Migrations/Bazaar/20260228175431_AddPrebuiltDeckShopFlag.Designer.cs new file mode 100644 index 0000000..f59344d --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Bazaar/20260228175431_AddPrebuiltDeckShopFlag.Designer.cs @@ -0,0 +1,481 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using SOR.Database.Contexts; + +#nullable disable + +namespace SOR.Database.Migrations.Bazaar +{ + [DbContext(typeof(BazaarDbContext))] + [Migration("20260228175431_AddPrebuiltDeckShopFlag")] + partial class AddPrebuiltDeckShopFlag + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("bazaar") + .HasAnnotation("ProductVersion", "8.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.AuctionBid", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Amount") + .HasColumnType("numeric(18,4)"); + + b.Property("BidderAccountId") + .HasColumnType("uuid"); + + b.Property("Currency") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsWinning") + .HasColumnType("boolean"); + + b.Property("ListingId") + .HasColumnType("uuid"); + + b.Property("PlacedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("BidderAccountId"); + + b.HasIndex("ListingId", "Amount"); + + b.HasIndex("ListingId", "IsWinning"); + + b.ToTable("auction_bids", "bazaar"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.BazaarListing", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CardDefinitionId") + .HasColumnType("uuid"); + + b.Property("Currency") + .IsRequired() + .HasColumnType("text"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsMasked") + .HasColumnType("boolean"); + + b.Property("ListedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ListingType") + .IsRequired() + .HasColumnType("text"); + + b.Property("PlayerCardId") + .HasColumnType("uuid"); + + b.Property("Price") + .HasColumnType("numeric(18,4)"); + + b.Property("SellerAccountId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("SellerAccountId"); + + b.HasIndex("Status", "CardDefinitionId"); + + b.HasIndex("Status", "ExpiresAt"); + + b.ToTable("listings", "bazaar"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.BazaarTransaction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Amount") + .HasColumnType("numeric(18,4)"); + + b.Property("BuyerAccountId") + .HasColumnType("uuid"); + + b.Property("Currency") + .IsRequired() + .HasColumnType("text"); + + b.Property("ListingId") + .HasColumnType("uuid"); + + b.Property("PlayerCardId") + .HasColumnType("uuid"); + + b.Property("SellerAccountId") + .HasColumnType("uuid"); + + b.Property("TransactedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("BuyerAccountId"); + + b.HasIndex("ListingId"); + + b.HasIndex("SellerAccountId"); + + b.HasIndex("TransactedAt"); + + b.ToTable("transactions", "bazaar"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.BoosterPack", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AvailableFrom") + .HasColumnType("timestamp with time zone"); + + b.Property("AvailableUntil") + .HasColumnType("timestamp with time zone"); + + b.Property("CardSetId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ImageCdnUrl") + .HasColumnType("text"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("OriginPointPrice") + .HasColumnType("integer"); + + b.Property("SlotsJson") + .HasColumnType("jsonb"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UsdPrice") + .HasColumnType("numeric(10,2)"); + + b.HasKey("Id"); + + b.HasIndex("IsActive"); + + b.HasIndex("AvailableFrom", "AvailableUntil"); + + b.ToTable("booster_packs", "bazaar"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.BoosterPackCardGrant", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CardDefinitionId") + .HasColumnType("uuid"); + + b.Property("CardName") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsFoil") + .HasColumnType("boolean"); + + b.Property("PlayerCardId") + .HasColumnType("uuid"); + + b.Property("PurchaseRecordId") + .HasColumnType("uuid"); + + b.Property("Rarity") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("PlayerCardId"); + + b.HasIndex("PurchaseRecordId"); + + b.ToTable("booster_pack_card_grants", "bazaar"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.Cosmetic", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AssetCdnUrl") + .IsRequired() + .HasColumnType("text"); + + b.Property("CardDefinitionId") + .HasColumnType("uuid"); + + b.Property("CosmeticType") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("OriginPointPrice") + .HasColumnType("integer"); + + b.Property("PreviewImageCdnUrl") + .HasColumnType("text"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UsdPrice") + .HasColumnType("numeric(10,2)"); + + b.HasKey("Id"); + + b.HasIndex("CardDefinitionId"); + + b.HasIndex("CosmeticType", "IsActive"); + + b.ToTable("cosmetics", "bazaar"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.PrebuiltDeck", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArchSpiritCardDefinitionId") + .HasColumnType("uuid"); + + b.Property("ArchSpiritName") + .HasColumnType("text"); + + b.Property("AvailableFrom") + .HasColumnType("timestamp with time zone"); + + b.Property("AvailableUntil") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("ImageCdnUrl") + .HasColumnType("text"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsAvailableInShop") + .HasColumnType("boolean"); + + b.Property("IsStarterDeck") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("OriginPointPrice") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UsdPrice") + .HasColumnType("numeric(10,2)"); + + b.HasKey("Id"); + + b.HasIndex("IsActive"); + + b.HasIndex("IsStarterDeck"); + + b.ToTable("prebuilt_decks", "bazaar"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.PrebuiltDeckCard", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CardDefinitionId") + .HasColumnType("uuid"); + + b.Property("CardName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("PrebuiltDeckId") + .HasColumnType("uuid"); + + b.Property("Quantity") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PrebuiltDeckId", "CardDefinitionId") + .IsUnique(); + + b.ToTable("prebuilt_deck_cards", "bazaar"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.PurchaseRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountId") + .HasColumnType("uuid"); + + b.Property("OriginPointsSpent") + .HasColumnType("integer"); + + b.Property("ProductId") + .HasColumnType("uuid"); + + b.Property("ProductType") + .IsRequired() + .HasColumnType("text"); + + b.Property("PurchasedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("QuantityGranted") + .HasColumnType("integer"); + + b.Property("UsdSpent") + .HasColumnType("numeric(10,2)"); + + b.HasKey("Id"); + + b.HasIndex("AccountId", "PurchasedAt"); + + b.HasIndex("ProductType", "PurchasedAt"); + + b.ToTable("purchase_records", "bazaar"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.AuctionBid", b => + { + b.HasOne("SOR.Database.Entities.Bazaar.BazaarListing", "Listing") + .WithMany() + .HasForeignKey("ListingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Listing"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.BazaarTransaction", b => + { + b.HasOne("SOR.Database.Entities.Bazaar.BazaarListing", "Listing") + .WithMany("Transactions") + .HasForeignKey("ListingId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Listing"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.BoosterPackCardGrant", b => + { + b.HasOne("SOR.Database.Entities.Bazaar.PurchaseRecord", "PurchaseRecord") + .WithMany("CardGrants") + .HasForeignKey("PurchaseRecordId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PurchaseRecord"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.PrebuiltDeckCard", b => + { + b.HasOne("SOR.Database.Entities.Bazaar.PrebuiltDeck", "PrebuiltDeck") + .WithMany("Cards") + .HasForeignKey("PrebuiltDeckId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PrebuiltDeck"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.BazaarListing", b => + { + b.Navigation("Transactions"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.PrebuiltDeck", b => + { + b.Navigation("Cards"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Bazaar.PurchaseRecord", b => + { + b.Navigation("CardGrants"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Bazaar/20260228175431_AddPrebuiltDeckShopFlag.cs b/Server/src/SOR.Database/Migrations/Bazaar/20260228175431_AddPrebuiltDeckShopFlag.cs new file mode 100644 index 0000000..2ab854d --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Bazaar/20260228175431_AddPrebuiltDeckShopFlag.cs @@ -0,0 +1,31 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SOR.Database.Migrations.Bazaar +{ + /// + public partial class AddPrebuiltDeckShopFlag : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsAvailableInShop", + schema: "bazaar", + table: "prebuilt_decks", + type: "boolean", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsAvailableInShop", + schema: "bazaar", + table: "prebuilt_decks"); + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Bazaar/BazaarDbContextModelSnapshot.cs b/Server/src/SOR.Database/Migrations/Bazaar/BazaarDbContextModelSnapshot.cs index ac19e92..9209780 100644 --- a/Server/src/SOR.Database/Migrations/Bazaar/BazaarDbContextModelSnapshot.cs +++ b/Server/src/SOR.Database/Migrations/Bazaar/BazaarDbContextModelSnapshot.cs @@ -320,6 +320,9 @@ namespace SOR.Database.Migrations.Bazaar b.Property("IsActive") .HasColumnType("boolean"); + b.Property("IsAvailableInShop") + .HasColumnType("boolean"); + b.Property("IsStarterDeck") .HasColumnType("boolean"); diff --git a/Server/src/SOR.Gateway/Auth/GatewayAuthValidator.cs b/Server/src/SOR.Gateway/Auth/GatewayAuthValidator.cs index 555dbe6..64e6763 100644 --- a/Server/src/SOR.Gateway/Auth/GatewayAuthValidator.cs +++ b/Server/src/SOR.Gateway/Auth/GatewayAuthValidator.cs @@ -29,7 +29,7 @@ public sealed class GatewayAuthValidator : IGatewayAuthValidator } /// - public async Task<(bool Valid, string UserId, string DisplayName)> ValidateAsync( + public async Task<(bool Valid, string UserId, string DisplayName, bool NeedsStarterDeck)> ValidateAsync( string sessionToken, CancellationToken cancellationToken = default) { @@ -42,21 +42,21 @@ public sealed class GatewayAuthValidator : IGatewayAuthValidator if (!response.Valid) { _logger.LogDebug("Token validation failed: token is invalid or expired"); - return (false, string.Empty, string.Empty); + return (false, string.Empty, string.Empty, false); } - return (true, response.UserId, response.DisplayName); + return (true, response.UserId, response.DisplayName, response.NeedsStarterDeck); } catch (Grpc.Core.RpcException ex) { _logger.LogWarning(ex, "Auth gRPC call failed during token validation: {Status}", ex.Status.StatusCode); - return (false, string.Empty, string.Empty); + return (false, string.Empty, string.Empty, false); } } /// - public async Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)> + public async Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName, bool NeedsStarterDeck)> LoginAsync(string email, string password, CancellationToken cancellationToken = default) { try @@ -66,21 +66,21 @@ public sealed class GatewayAuthValidator : IGatewayAuthValidator cancellationToken: cancellationToken); if (!response.Success) - return (false, response.ErrorCode, string.Empty, string.Empty, string.Empty); + return (false, response.ErrorCode, string.Empty, string.Empty, string.Empty, false); - // Token is returned; fetch display name via ValidateToken (it includes it). + // Token is returned; fetch display name + starter-deck flag via ValidateToken. var validate = await ValidateAsync(response.SessionToken, cancellationToken); - return (true, string.Empty, response.SessionToken, validate.UserId, validate.DisplayName); + return (true, string.Empty, response.SessionToken, validate.UserId, validate.DisplayName, validate.NeedsStarterDeck); } catch (Grpc.Core.RpcException ex) { _logger.LogWarning(ex, "Auth gRPC call failed during login: {Status}", ex.Status.StatusCode); - return (false, "AUTH_SERVICE_UNAVAILABLE", string.Empty, string.Empty, string.Empty); + return (false, "AUTH_SERVICE_UNAVAILABLE", string.Empty, string.Empty, string.Empty, false); } } /// - public async Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)> + public async Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName, bool NeedsStarterDeck)> RegisterAsync(string email, string password, string displayName, CancellationToken cancellationToken = default) { try @@ -90,15 +90,15 @@ public sealed class GatewayAuthValidator : IGatewayAuthValidator cancellationToken: cancellationToken); if (!response.Success) - return (false, response.ErrorCode, string.Empty, string.Empty, string.Empty); + return (false, response.ErrorCode, string.Empty, string.Empty, string.Empty, false); var validate = await ValidateAsync(response.SessionToken, cancellationToken); - return (true, string.Empty, response.SessionToken, validate.UserId, validate.DisplayName); + return (true, string.Empty, response.SessionToken, validate.UserId, validate.DisplayName, validate.NeedsStarterDeck); } catch (Grpc.Core.RpcException ex) { _logger.LogWarning(ex, "Auth gRPC call failed during register: {Status}", ex.Status.StatusCode); - return (false, "AUTH_SERVICE_UNAVAILABLE", string.Empty, string.Empty, string.Empty); + return (false, "AUTH_SERVICE_UNAVAILABLE", string.Empty, string.Empty, string.Empty, false); } } } diff --git a/Server/src/SOR.Gateway/Auth/IGatewayAuthValidator.cs b/Server/src/SOR.Gateway/Auth/IGatewayAuthValidator.cs index fcc2609..d44d095 100644 --- a/Server/src/SOR.Gateway/Auth/IGatewayAuthValidator.cs +++ b/Server/src/SOR.Gateway/Auth/IGatewayAuthValidator.cs @@ -17,7 +17,7 @@ public interface IGatewayAuthValidator /// Validates an existing session token. /// Returns (Valid=false, …) on invalid/expired token or Auth service error. /// - Task<(bool Valid, string UserId, string DisplayName)> ValidateAsync( + Task<(bool Valid, string UserId, string DisplayName, bool NeedsStarterDeck)> ValidateAsync( string sessionToken, CancellationToken cancellationToken = default); @@ -25,13 +25,13 @@ public interface IGatewayAuthValidator /// Authenticates with email + password. Returns the new session token on success. /// ErrorCode is set (and SessionToken is empty) on failure. /// - Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)> + Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName, bool NeedsStarterDeck)> LoginAsync(string email, string password, CancellationToken cancellationToken = default); /// /// Registers a new account. Returns the new session token on success. /// ErrorCode is set (and SessionToken is empty) on failure. /// - Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)> + Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName, bool NeedsStarterDeck)> RegisterAsync(string email, string password, string displayName, CancellationToken cancellationToken = default); } diff --git a/Server/src/SOR.Gateway/ConnectionLoop.cs b/Server/src/SOR.Gateway/ConnectionLoop.cs index 1270fa9..a5cdd66 100644 --- a/Server/src/SOR.Gateway/ConnectionLoop.cs +++ b/Server/src/SOR.Gateway/ConnectionLoop.cs @@ -104,6 +104,7 @@ public sealed class ConnectionLoop string userId; string displayName; string ackType; + bool needsStarterDeck; switch (parsedMsg.Type.ToLowerInvariant()) { @@ -113,7 +114,7 @@ public sealed class ConnectionLoop try { payload = _serializer.DeserializePayload(parsedMsg.Payload); } catch { await RejectAsync(rawConnection, parsedMsg.Seq, "INVALID_PAYLOAD", "auth.hello payload is malformed.", appCancellationToken); return; } - var (valid, uid, dname) = + var (valid, uid, dname, nsd) = await _authValidator.ValidateAsync(payload.SessionToken, appCancellationToken); if (!valid) { @@ -121,8 +122,8 @@ public sealed class ConnectionLoop "AUTH_FAILED", "Invalid or expired session token.", appCancellationToken); return; } - (sessionToken, userId, displayName, ackType) = - (payload.SessionToken, uid, dname, "auth.hello.ack"); + (sessionToken, userId, displayName, ackType, needsStarterDeck) = + (payload.SessionToken, uid, dname, "auth.hello.ack", nsd); break; } @@ -132,15 +133,15 @@ public sealed class ConnectionLoop try { payload = _serializer.DeserializePayload(parsedMsg.Payload); } catch { await RejectAsync(rawConnection, parsedMsg.Seq, "INVALID_PAYLOAD", "auth.login payload is malformed.", appCancellationToken); return; } - var (success, errorCode, token, uid, dname) = + var (success, errorCode, token, uid, dname, nsd) = await _authValidator.LoginAsync(payload.Email, payload.Password, appCancellationToken); if (!success) { await RejectAsync(rawConnection, parsedMsg.Seq, errorCode, "Login failed.", appCancellationToken); return; } - (sessionToken, userId, displayName, ackType) = - (token, uid, dname, "auth.login.ack"); + (sessionToken, userId, displayName, ackType, needsStarterDeck) = + (token, uid, dname, "auth.login.ack", nsd); break; } @@ -150,7 +151,7 @@ public sealed class ConnectionLoop try { payload = _serializer.DeserializePayload(parsedMsg.Payload); } catch { await RejectAsync(rawConnection, parsedMsg.Seq, "INVALID_PAYLOAD", "auth.register payload is malformed.", appCancellationToken); return; } - var (success, errorCode, token, uid, dname) = + var (success, errorCode, token, uid, dname, nsd) = await _authValidator.RegisterAsync( payload.Email, payload.Password, payload.DisplayName, appCancellationToken); if (!success) @@ -158,8 +159,8 @@ public sealed class ConnectionLoop await RejectAsync(rawConnection, parsedMsg.Seq, errorCode, "Registration failed.", appCancellationToken); return; } - (sessionToken, userId, displayName, ackType) = - (token, uid, dname, "auth.register.ack"); + (sessionToken, userId, displayName, ackType, needsStarterDeck) = + (token, uid, dname, "auth.register.ack", nsd); break; } @@ -183,9 +184,10 @@ public sealed class ConnectionLoop parsedMsg.Type, userId, displayName, rawConnection.ConnectionId); // Ack includes sessionToken so the client can persist it after login/register. + // needsStarterDeck tells the client to route new players to the deck-selection screen. await SendMessageAsync( rawConnection, - ServerMessage.Reply(ackType, parsedMsg.Seq, new { userId, displayName, sessionToken }), + ServerMessage.Reply(ackType, parsedMsg.Seq, new { userId, displayName, sessionToken, needsStarterDeck }), appCancellationToken); // ── Phase 4: Subscribe to Redis Push Channel ─────────────────────────── diff --git a/Server/src/SOR.Shared.Proto/Protos/auth.proto b/Server/src/SOR.Shared.Proto/Protos/auth.proto index 7525493..8e4d5b1 100644 --- a/Server/src/SOR.Shared.Proto/Protos/auth.proto +++ b/Server/src/SOR.Shared.Proto/Protos/auth.proto @@ -16,6 +16,8 @@ message LoginResponse { string session_token = 2; // Failure codes: USER_NOT_FOUND | INVALID_PASSWORD | ACCOUNT_BANNED | ACCOUNT_LOCKED string error_code = 3; + // True when the account has never selected a starter deck (StarterDeckSelectedAt is null). + bool needs_starter_deck = 4; } // ── Token Validation ────────────────────────────────────────────────────────── @@ -29,6 +31,8 @@ message ValidateTokenResponse { // Only populated when valid = true. string user_id = 2; string display_name = 3; + // True when the account has never selected a starter deck. + bool needs_starter_deck = 4; } // ── Registration ────────────────────────────────────────────────────────────── @@ -44,6 +48,8 @@ message RegisterResponse { string session_token = 2; // Failure codes: EMAIL_TAKEN | DISPLAY_NAME_TAKEN | WEAK_PASSWORD | REGISTRATION_FAILED string error_code = 3; + // Always true for new accounts — they have never selected a starter deck. + bool needs_starter_deck = 4; } // ── Logout ──────────────────────────────────────────────────────────────────── @@ -55,6 +61,18 @@ message LogoutRequest { // Empty response — logout always succeeds (idempotent; revoking a non-existent token is fine). message LogoutResponse {} +// ── Admin: Revoke all sessions ───────────────────────────────────────────────── +// Forces a user off all devices by revoking every active session. +// Used by Admin Portal for force-logout actions. + +message RevokeAllSessionsRequest { + string account_id = 1; +} + +message RevokeAllSessionsResponse { + int32 sessions_revoked = 1; +} + // ── Account Properties ──────────────────────────────────────────────────────── // Flexible key-value bag per account. // Keys are snake_case strings; values are always strings (caller interprets type). @@ -144,6 +162,9 @@ service AuthService { // Revoke a session token (idempotent — revoking a non-existent token is fine). rpc Logout(LogoutRequest) returns (LogoutResponse); + // Revoke ALL active sessions for an account (admin force-logout). + rpc RevokeAllSessions(RevokeAllSessionsRequest) returns (RevokeAllSessionsResponse); + // Per-account key-value property bag. rpc GetAccountProperty(GetAccountPropertyRequest) returns (GetAccountPropertyResponse); rpc SetAccountProperty(SetAccountPropertyRequest) returns (SetAccountPropertyResponse);