Godot client networking + auth + login/main screens; fix admin hamburger
Server: - ConnectionLoop: accept auth.login and auth.register as valid first messages (not just auth.hello); all ack payloads now include sessionToken for client persistence - IGatewayAuthValidator: add LoginAsync and RegisterAsync - GatewayAuthValidator: implement both via auth gRPC; fetch displayName from ValidateAsync after login/register succeeds - Admin hamburger: custom .sor-admin-hamburger CSS (hardcoded white, no Bootstrap btn-link theme fighting); topbar z-index 1050 with position:sticky Client (Godot 4.5, GDScript): - autoloads/Network.gd: WebSocketPeer state machine (CONNECTING / CONNECTED / RECONNECTING), exponential backoff (1→30s), app-level keepalive ping every 30s of idle, 30s ping timeout → reconnect, request/reply correlation by sequence number, debug_log_packets export flag for full packet dumps - autoloads/Auth.gd: drives auth.hello / auth.login / auth.register as first WS message; persists sessionToken + userId + displayName to user://auth.cfg; auto-resumes saved session on reconnect; auth_success / auth_failed signals - scenes/login/LoginScreen.tscn + login_screen.gd: Login + Register tabs, touch-friendly inputs (44px height), status label, Enter key submits, handles reconnect/resume states - scenes/main/MainScreen.tscn + main_screen.gd: top bar with live connection dot, welcome label, placeholder nav buttons, sign-out, redirects to login on session expiry - project.godot: Network and Auth autoloads registered; LoginScreen as main scene Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
extends Node
|
||||
## Authentication autoload.
|
||||
##
|
||||
## Drives the auth handshake (auth.hello / auth.login / auth.register) as the
|
||||
## first WebSocket message on every connection. Persists the session token to
|
||||
## disk so the next session can reconnect silently.
|
||||
##
|
||||
## Scenes interact with this node via signals and the three public methods.
|
||||
##
|
||||
## Signals:
|
||||
## auth_success(user_id, display_name) — auth succeeded; switch to main screen
|
||||
## auth_failed(error_code, message) — auth rejected; show error to user
|
||||
|
||||
const SAVE_PATH := "user://auth.cfg"
|
||||
const SECTION := "auth"
|
||||
|
||||
signal auth_success(user_id: String, display_name: String)
|
||||
signal auth_failed(error_code: String, message: String)
|
||||
|
||||
## Set after a successful auth. Empty while unauthenticated.
|
||||
var user_id: String = ""
|
||||
var display_name: String = ""
|
||||
var session_token: String = ""
|
||||
|
||||
# ── Lifecycle ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func _ready() -> void:
|
||||
_load_session()
|
||||
Network.connected.connect(_on_network_connected)
|
||||
|
||||
# ── Public API ────────────────────────────────────────────────────────────────
|
||||
|
||||
## Attempt to sign in with email and password.
|
||||
## Call from the login form.
|
||||
func login(email: String, password: String) -> void:
|
||||
Network.request(
|
||||
"auth.login",
|
||||
{ "email": email, "password": password },
|
||||
func(_type: String, p: Variant): _on_auth_ok(p),
|
||||
func(code: String, msg: String): auth_failed.emit(code, msg)
|
||||
)
|
||||
|
||||
|
||||
## Attempt to create a new account.
|
||||
## Call from the register form.
|
||||
func register(email: String, password: String, disp_name: String) -> void:
|
||||
Network.request(
|
||||
"auth.register",
|
||||
{ "email": email, "password": password, "displayName": disp_name },
|
||||
func(_type: String, p: Variant): _on_auth_ok(p),
|
||||
func(code: String, msg: String): auth_failed.emit(code, msg)
|
||||
)
|
||||
|
||||
|
||||
## Clear the saved session and reset auth state (e.g. logout button).
|
||||
func logout() -> void:
|
||||
user_id = ""
|
||||
display_name = ""
|
||||
session_token = ""
|
||||
_save_session()
|
||||
|
||||
# ── Private ───────────────────────────────────────────────────────────────────
|
||||
|
||||
## Called every time the WebSocket connects (including after reconnects).
|
||||
## If a session token is saved, send auth.hello to resume silently.
|
||||
func _on_network_connected() -> void:
|
||||
if session_token.is_empty():
|
||||
return # No token — LoginScreen will drive login/register.
|
||||
|
||||
Network.request(
|
||||
"auth.hello",
|
||||
{ "sessionToken": session_token },
|
||||
func(_type: String, p: Variant): _on_auth_ok(p),
|
||||
func(code: String, msg: String):
|
||||
# Keep the token on network errors — we'll retry on the next
|
||||
# reconnect. Only clear it on explicit auth rejections.
|
||||
if code != "DISCONNECTED":
|
||||
session_token = ""
|
||||
_save_session()
|
||||
auth_failed.emit(code, msg)
|
||||
)
|
||||
|
||||
|
||||
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", "")
|
||||
_save_session()
|
||||
auth_success.emit(user_id, display_name)
|
||||
|
||||
|
||||
func _load_session() -> void:
|
||||
var cfg := ConfigFile.new()
|
||||
if cfg.load(SAVE_PATH) != OK:
|
||||
return
|
||||
session_token = cfg.get_value(SECTION, "session_token", "")
|
||||
user_id = cfg.get_value(SECTION, "user_id", "")
|
||||
display_name = cfg.get_value(SECTION, "display_name", "")
|
||||
|
||||
|
||||
func _save_session() -> void:
|
||||
var cfg := ConfigFile.new()
|
||||
cfg.set_value(SECTION, "session_token", session_token)
|
||||
cfg.set_value(SECTION, "user_id", user_id)
|
||||
cfg.set_value(SECTION, "display_name", display_name)
|
||||
cfg.save(SAVE_PATH)
|
||||
@@ -0,0 +1,260 @@
|
||||
extends Node
|
||||
## Singleton WebSocket connection manager.
|
||||
##
|
||||
## Handles connection lifecycle, reconnection with exponential backoff,
|
||||
## request/reply correlation via sequence numbers, and application-level
|
||||
## keepalive (sends a network.ping every 30 s of idle; expects any reply
|
||||
## within 30 s or forces a reconnect).
|
||||
##
|
||||
## Usage:
|
||||
## Network.request("chat.send", payload, on_reply_callable, on_error_callable)
|
||||
## Network.send("game.move", payload)
|
||||
## Network.debug_log_packets = true # dump all sent/received JSON
|
||||
|
||||
# ── Configuration ─────────────────────────────────────────────────────────────
|
||||
|
||||
const SERVER_URL := "wss://hub.aeternalisgames.com/ws"
|
||||
|
||||
## Print every sent/received packet as JSON to stdout.
|
||||
@export var debug_log_packets: bool = false
|
||||
|
||||
const KEEPALIVE_INTERVAL_SEC := 30.0 ## Idle seconds before sending an app-level ping.
|
||||
const KEEPALIVE_TIMEOUT_SEC := 30.0 ## Seconds with no reply before forcing a reconnect.
|
||||
const MAX_RECONNECT_DELAY := 30.0 ## Cap on exponential backoff (seconds).
|
||||
|
||||
# ── Signals ───────────────────────────────────────────────────────────────────
|
||||
|
||||
## Emitted once the WebSocket handshake completes. Auth will send its
|
||||
## first message (auth.hello / auth.login / auth.register) in response.
|
||||
signal connected
|
||||
|
||||
## Emitted when the connection is lost. Reconnect loop starts automatically.
|
||||
signal disconnected
|
||||
|
||||
## Emitted for server-pushed messages that don't match a pending request.
|
||||
signal message_received(type: String, payload: Variant)
|
||||
|
||||
# ── State machine ─────────────────────────────────────────────────────────────
|
||||
|
||||
enum _State { DISCONNECTED, CONNECTING, CONNECTED, RECONNECTING }
|
||||
|
||||
var _state: _State = _State.DISCONNECTED
|
||||
var _ws: WebSocketPeer
|
||||
|
||||
var _seq: int = 0
|
||||
var _pending: Dictionary = {} ## int(seq) → { on_reply: Callable, on_error: Callable }
|
||||
var _ping_seq: int = -1 ## seq of the in-flight keepalive ping, or -1
|
||||
|
||||
var _reconnect_delay: float = 1.0
|
||||
var _reconnect_timer: float = 0.0
|
||||
|
||||
var _last_rx_time: float = 0.0 ## Epoch-seconds of last received packet.
|
||||
var _ping_sent_at: float = -1.0 ## Epoch-seconds when keepalive ping was sent, or -1.
|
||||
|
||||
# ── Lifecycle ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func _ready() -> void:
|
||||
_connect_now()
|
||||
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
# ── DISCONNECTED: nothing to do ────────────────────────────────────────────
|
||||
if _state == _State.DISCONNECTED:
|
||||
return
|
||||
|
||||
# ── RECONNECTING: count down and retry ────────────────────────────────────
|
||||
if _state == _State.RECONNECTING:
|
||||
_reconnect_timer -= delta
|
||||
if _reconnect_timer <= 0.0:
|
||||
_connect_now()
|
||||
return
|
||||
|
||||
# ── CONNECTING / CONNECTED: drive the WebSocket ───────────────────────────
|
||||
_ws.poll()
|
||||
var ws_ready := _ws.get_ready_state()
|
||||
|
||||
match ws_ready:
|
||||
WebSocketPeer.STATE_OPEN:
|
||||
if _state == _State.CONNECTING:
|
||||
_on_ws_opened()
|
||||
# Fall through to packet/keepalive processing below.
|
||||
|
||||
WebSocketPeer.STATE_CLOSED:
|
||||
if _state == _State.CONNECTED:
|
||||
_on_ws_closed()
|
||||
else: # STATE_CONNECTING → connection attempt failed
|
||||
_schedule_reconnect()
|
||||
return
|
||||
|
||||
WebSocketPeer.STATE_CLOSING:
|
||||
return # Wait for STATE_CLOSED on the next poll.
|
||||
|
||||
# Only run packet/keepalive while fully connected.
|
||||
if _state == _State.CONNECTED:
|
||||
_poll_packets()
|
||||
_tick_keepalive()
|
||||
|
||||
# ── Public API ────────────────────────────────────────────────────────────────
|
||||
|
||||
## Send [param type] with [param payload] and register callbacks.
|
||||
## [param on_reply] is called as (type: String, payload: Variant).
|
||||
## [param on_error] is called as (error_code: String, message: String).
|
||||
## Returns the sequence number used (useful for cancellation).
|
||||
func request(
|
||||
type: String,
|
||||
payload: Variant,
|
||||
on_reply: Callable,
|
||||
on_error: Callable = Callable()) -> int:
|
||||
_seq += 1
|
||||
var seq := _seq
|
||||
_pending[seq] = { &"on_reply": on_reply, &"on_error": on_error }
|
||||
_send_raw({ "type": type, "seq": seq, "payload": payload })
|
||||
return seq
|
||||
|
||||
|
||||
## Fire-and-forget send. No reply tracking.
|
||||
func send(type: String, payload: Variant = {}) -> void:
|
||||
_seq += 1
|
||||
_send_raw({ "type": type, "seq": _seq, "payload": payload })
|
||||
|
||||
|
||||
## True when the WebSocket is fully open.
|
||||
func is_online() -> bool:
|
||||
return _state == _State.CONNECTED
|
||||
|
||||
# ── Connection helpers ────────────────────────────────────────────────────────
|
||||
|
||||
func _connect_now() -> void:
|
||||
_ws = WebSocketPeer.new()
|
||||
_state = _State.CONNECTING
|
||||
var err := _ws.connect_to_url(SERVER_URL)
|
||||
if err != OK:
|
||||
push_warning("Network: connect_to_url failed — %s" % error_string(err))
|
||||
_schedule_reconnect()
|
||||
return
|
||||
if debug_log_packets:
|
||||
print("[Net] Connecting → %s" % SERVER_URL)
|
||||
|
||||
|
||||
func _on_ws_opened() -> void:
|
||||
_state = _State.CONNECTED
|
||||
_reconnect_delay = 1.0
|
||||
_last_rx_time = _now()
|
||||
_ping_sent_at = -1.0
|
||||
if debug_log_packets:
|
||||
print("[Net] Connected")
|
||||
connected.emit()
|
||||
|
||||
|
||||
func _on_ws_closed() -> void:
|
||||
var code := _ws.get_close_code()
|
||||
var reason := _ws.get_close_reason()
|
||||
if debug_log_packets:
|
||||
print("[Net] Closed code=%d reason=%s" % [code, reason])
|
||||
|
||||
# Fail all pending requests immediately.
|
||||
for seq in _pending.keys():
|
||||
var cb: Dictionary = _pending[seq]
|
||||
if cb[&"on_error"].is_valid():
|
||||
cb[&"on_error"].call("DISCONNECTED", "Connection lost.")
|
||||
_pending.clear()
|
||||
_ping_seq = -1
|
||||
_ping_sent_at = -1.0
|
||||
|
||||
_schedule_reconnect()
|
||||
disconnected.emit()
|
||||
|
||||
|
||||
func _schedule_reconnect() -> void:
|
||||
_state = _State.RECONNECTING
|
||||
_reconnect_timer = _reconnect_delay
|
||||
_reconnect_delay = minf(_reconnect_delay * 2.0, MAX_RECONNECT_DELAY)
|
||||
if debug_log_packets:
|
||||
print("[Net] Reconnecting in %.1f s (next backoff=%.1f s)"
|
||||
% [_reconnect_timer, _reconnect_delay])
|
||||
|
||||
# ── Packet I/O ────────────────────────────────────────────────────────────────
|
||||
|
||||
func _poll_packets() -> void:
|
||||
while _ws.get_available_packet_count() > 0:
|
||||
var raw := _ws.get_packet()
|
||||
var text := raw.get_string_from_utf8()
|
||||
|
||||
_last_rx_time = _now()
|
||||
_ping_sent_at = -1.0 # Any received packet resets the ping watchdog.
|
||||
|
||||
if debug_log_packets:
|
||||
print("[Net] << %s" % text)
|
||||
|
||||
var parsed: Variant = JSON.parse_string(text)
|
||||
if typeof(parsed) != TYPE_DICTIONARY:
|
||||
push_warning("Network: non-object packet — %s" % text)
|
||||
continue
|
||||
_dispatch(parsed as Dictionary)
|
||||
|
||||
|
||||
func _dispatch(packet: Dictionary) -> void:
|
||||
var ref : int = packet.get("ref", -1)
|
||||
var type : String = packet.get("type", "")
|
||||
var payload: Variant = packet.get("payload", {})
|
||||
|
||||
if ref >= 0 and _pending.has(ref):
|
||||
var cb: Dictionary = _pending[ref]
|
||||
_pending.erase(ref)
|
||||
|
||||
if type == "error":
|
||||
var error_code: String = (payload as Dictionary).get("errorCode", "UNKNOWN")
|
||||
var message: String = (payload as Dictionary).get("message", "")
|
||||
# UNKNOWN_TYPE for our own keepalive ping is expected — swallow it.
|
||||
if ref == _ping_seq and error_code == "UNKNOWN_TYPE":
|
||||
return
|
||||
if cb[&"on_error"].is_valid():
|
||||
cb[&"on_error"].call(error_code, message)
|
||||
else:
|
||||
if cb[&"on_reply"].is_valid():
|
||||
cb[&"on_reply"].call(type, payload)
|
||||
return
|
||||
|
||||
# Not a reply to a known request — broadcast/push to listeners.
|
||||
message_received.emit(type, payload)
|
||||
|
||||
|
||||
func _send_raw(msg: Dictionary) -> void:
|
||||
if _ws == null or _ws.get_ready_state() != WebSocketPeer.STATE_OPEN:
|
||||
push_warning("Network: dropped send (not connected) type=%s"
|
||||
% msg.get("type", "?"))
|
||||
return
|
||||
var text := JSON.stringify(msg)
|
||||
if debug_log_packets:
|
||||
print("[Net] >> %s" % text)
|
||||
_ws.send_text(text)
|
||||
|
||||
# ── Keepalive ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func _tick_keepalive() -> void:
|
||||
var now := _now()
|
||||
|
||||
if _ping_sent_at >= 0.0:
|
||||
# Ping already in flight — check for timeout.
|
||||
if now - _ping_sent_at > KEEPALIVE_TIMEOUT_SEC:
|
||||
push_warning("Network: keepalive timeout — forcing reconnect")
|
||||
_ws.close(1001, "keepalive_timeout")
|
||||
_on_ws_closed()
|
||||
return
|
||||
|
||||
if now - _last_rx_time >= KEEPALIVE_INTERVAL_SEC:
|
||||
# Send application-level ping. The server has no handler so it will
|
||||
# reply with error UNKNOWN_TYPE, which is silently swallowed in
|
||||
# _dispatch(). The reply itself resets _ping_sent_at and counts as
|
||||
# proof the round-trip works.
|
||||
_seq += 1
|
||||
_ping_seq = _seq
|
||||
_pending[_ping_seq] = { &"on_reply": Callable(), &"on_error": Callable() }
|
||||
_send_raw({ "type": "network.ping", "seq": _ping_seq, "payload": {} })
|
||||
_ping_sent_at = now
|
||||
if debug_log_packets:
|
||||
print("[Net] Keepalive ping seq=%d" % _ping_seq)
|
||||
|
||||
|
||||
func _now() -> float:
|
||||
return Time.get_ticks_msec() / 1000.0
|
||||
@@ -13,6 +13,12 @@ config_version=5
|
||||
config/name="Origin-Client"
|
||||
config/features=PackedStringArray("4.5", "Mobile")
|
||||
config/icon="res://icon.svg"
|
||||
run/main_scene="res://scenes/login/LoginScreen.tscn"
|
||||
|
||||
[autoload]
|
||||
|
||||
Network="*res://autoloads/Network.gd"
|
||||
Auth="*res://autoloads/Auth.gd"
|
||||
|
||||
[rendering]
|
||||
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://scenes/login/login_screen.gd" id="1_login"]
|
||||
|
||||
[node name="LoginScreen" 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_login")
|
||||
|
||||
[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="Center" type="CenterContainer" parent="."]
|
||||
layout_mode = 1
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
|
||||
[node name="Panel" type="PanelContainer" parent="Center"]
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(360, 0)
|
||||
|
||||
[node name="Margin" type="MarginContainer" parent="Center/Panel"]
|
||||
layout_mode = 2
|
||||
theme_override_constants/margin_left = 28
|
||||
theme_override_constants/margin_top = 28
|
||||
theme_override_constants/margin_right = 28
|
||||
theme_override_constants/margin_bottom = 28
|
||||
|
||||
[node name="VBox" type="VBoxContainer" parent="Center/Panel/Margin"]
|
||||
layout_mode = 2
|
||||
theme_override_constants/separation = 14
|
||||
|
||||
[node name="Title" type="Label" parent="Center/Panel/Margin/VBox"]
|
||||
layout_mode = 2
|
||||
text = "ORIGIN"
|
||||
horizontal_alignment = 1
|
||||
theme_override_font_sizes/font_size = 30
|
||||
|
||||
[node name="Subtitle" type="Label" parent="Center/Panel/Margin/VBox"]
|
||||
layout_mode = 2
|
||||
text = "Stone of Ruin"
|
||||
horizontal_alignment = 1
|
||||
modulate = Color(0.6, 0.6, 0.65, 1.0)
|
||||
theme_override_font_sizes/font_size = 13
|
||||
|
||||
[node name="Spacer" type="Control" parent="Center/Panel/Margin/VBox"]
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 6)
|
||||
|
||||
[node name="Tabs" type="TabContainer" parent="Center/Panel/Margin/VBox"]
|
||||
layout_mode = 2
|
||||
size_flags_vertical = 3
|
||||
|
||||
[node name="Login" type="VBoxContainer" parent="Center/Panel/Margin/VBox/Tabs"]
|
||||
layout_mode = 2
|
||||
theme_override_constants/separation = 8
|
||||
|
||||
[node name="EmailLabel" type="Label" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
layout_mode = 2
|
||||
text = "Email"
|
||||
|
||||
[node name="EmailInput" type="LineEdit" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 44)
|
||||
placeholder_text = "your@email.com"
|
||||
theme_override_font_sizes/font_size = 15
|
||||
|
||||
[node name="PasswordLabel" type="Label" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
layout_mode = 2
|
||||
text = "Password"
|
||||
|
||||
[node name="PasswordInput" type="LineEdit" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 44)
|
||||
placeholder_text = "••••••••"
|
||||
secret = true
|
||||
theme_override_font_sizes/font_size = 15
|
||||
|
||||
[node name="LoginSpacer" type="Control" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 4)
|
||||
|
||||
[node name="LoginBtn" type="Button" parent="Center/Panel/Margin/VBox/Tabs/Login"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 48)
|
||||
text = "Sign In"
|
||||
theme_override_font_sizes/font_size = 15
|
||||
|
||||
[node name="Register" type="VBoxContainer" parent="Center/Panel/Margin/VBox/Tabs"]
|
||||
layout_mode = 2
|
||||
theme_override_constants/separation = 8
|
||||
|
||||
[node name="RegEmailLabel" type="Label" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
layout_mode = 2
|
||||
text = "Email"
|
||||
|
||||
[node name="RegEmailInput" type="LineEdit" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 44)
|
||||
placeholder_text = "your@email.com"
|
||||
theme_override_font_sizes/font_size = 15
|
||||
|
||||
[node name="RegPasswordLabel" type="Label" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
layout_mode = 2
|
||||
text = "Password"
|
||||
|
||||
[node name="RegPasswordInput" type="LineEdit" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 44)
|
||||
placeholder_text = "••••••••"
|
||||
secret = true
|
||||
theme_override_font_sizes/font_size = 15
|
||||
|
||||
[node name="RegNameLabel" type="Label" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
layout_mode = 2
|
||||
text = "Display Name"
|
||||
|
||||
[node name="RegNameInput" type="LineEdit" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 44)
|
||||
placeholder_text = "YourName"
|
||||
theme_override_font_sizes/font_size = 15
|
||||
|
||||
[node name="RegSpacer" type="Control" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 4)
|
||||
|
||||
[node name="RegisterBtn" type="Button" parent="Center/Panel/Margin/VBox/Tabs/Register"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 48)
|
||||
text = "Create Account"
|
||||
theme_override_font_sizes/font_size = 15
|
||||
|
||||
[node name="StatusLabel" type="Label" parent="Center/Panel/Margin/VBox"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
horizontal_alignment = 1
|
||||
autowrap_mode = 3
|
||||
modulate = Color(0.8, 0.8, 0.8, 1.0)
|
||||
theme_override_font_sizes/font_size = 13
|
||||
@@ -0,0 +1,119 @@
|
||||
extends Control
|
||||
## Login / Register screen.
|
||||
##
|
||||
## Shown as the entry point before authentication. Uses two tabs:
|
||||
## "Login" — email + password → auth.login
|
||||
## "Register" — email + password + display name → auth.register
|
||||
##
|
||||
## Listens to Auth.auth_success and Auth.auth_failed.
|
||||
## On success: transitions to MainScreen.
|
||||
## On failure: shows an error message and re-enables the form.
|
||||
|
||||
# ── Node references (unique names set in the .tscn) ──────────────────────────
|
||||
|
||||
@onready var email_input : LineEdit = %EmailInput
|
||||
@onready var password_input : LineEdit = %PasswordInput
|
||||
@onready var login_btn : Button = %LoginBtn
|
||||
|
||||
@onready var reg_email_input : LineEdit = %RegEmailInput
|
||||
@onready var reg_password_input : LineEdit = %RegPasswordInput
|
||||
@onready var reg_name_input : LineEdit = %RegNameInput
|
||||
@onready var register_btn : Button = %RegisterBtn
|
||||
|
||||
@onready var status_label : Label = %StatusLabel
|
||||
|
||||
# ── Lifecycle ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func _ready() -> void:
|
||||
# If already authenticated (e.g. scene reloaded), skip straight to main.
|
||||
if not Auth.user_id.is_empty():
|
||||
_go_to_main()
|
||||
return
|
||||
|
||||
Auth.auth_success.connect(_on_auth_success)
|
||||
Auth.auth_failed.connect(_on_auth_failed)
|
||||
|
||||
login_btn.pressed.connect(_on_login_pressed)
|
||||
register_btn.pressed.connect(_on_register_pressed)
|
||||
|
||||
# Allow pressing Enter to submit the login form.
|
||||
password_input.text_submitted.connect(func(_t): _on_login_pressed())
|
||||
reg_name_input.text_submitted.connect(func(_t): _on_register_pressed())
|
||||
|
||||
# Show connection / session-resume status on first open.
|
||||
if not Auth.session_token.is_empty():
|
||||
_set_status("Resuming session…", false)
|
||||
_set_enabled(false)
|
||||
elif not Network.is_online():
|
||||
_set_status("Connecting…", false)
|
||||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
if Auth.auth_success.is_connected(_on_auth_success):
|
||||
Auth.auth_success.disconnect(_on_auth_success)
|
||||
if Auth.auth_failed.is_connected(_on_auth_failed):
|
||||
Auth.auth_failed.disconnect(_on_auth_failed)
|
||||
|
||||
# ── Button handlers ───────────────────────────────────────────────────────────
|
||||
|
||||
func _on_login_pressed() -> void:
|
||||
var email := email_input.text.strip_edges()
|
||||
var pass_ := password_input.text
|
||||
if email.is_empty() or pass_.is_empty():
|
||||
_set_status("Please enter your email and password.", true)
|
||||
return
|
||||
_set_status("Signing in…", false)
|
||||
_set_enabled(false)
|
||||
Auth.login(email, pass_)
|
||||
|
||||
|
||||
func _on_register_pressed() -> void:
|
||||
var email := reg_email_input.text.strip_edges()
|
||||
var pass_ := reg_password_input.text
|
||||
var name_ := reg_name_input.text.strip_edges()
|
||||
if email.is_empty() or pass_.is_empty() or name_.is_empty():
|
||||
_set_status("Please fill in all fields.", true)
|
||||
return
|
||||
_set_status("Creating account…", false)
|
||||
_set_enabled(false)
|
||||
Auth.register(email, pass_, name_)
|
||||
|
||||
# ── Auth signal handlers ──────────────────────────────────────────────────────
|
||||
|
||||
func _on_auth_success(_user_id: String, _display_name: String) -> void:
|
||||
_go_to_main()
|
||||
|
||||
|
||||
func _on_auth_failed(error_code: String, message: String) -> void:
|
||||
if error_code == "DISCONNECTED":
|
||||
_set_status("Connection lost. Retrying…", false)
|
||||
else:
|
||||
_set_status(_friendly_error(error_code, message), true)
|
||||
_set_enabled(true)
|
||||
|
||||
# ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
func _go_to_main() -> void:
|
||||
get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn")
|
||||
|
||||
|
||||
func _set_status(text: String, is_error: bool) -> void:
|
||||
status_label.text = text
|
||||
status_label.modulate = Color(1.0, 0.4, 0.4) if is_error else Color(0.8, 0.8, 0.8)
|
||||
|
||||
|
||||
func _set_enabled(enabled: bool) -> void:
|
||||
login_btn.disabled = not enabled
|
||||
register_btn.disabled = not enabled
|
||||
|
||||
|
||||
func _friendly_error(code: String, message: String) -> String:
|
||||
match code:
|
||||
"INVALID_CREDENTIALS": return "Wrong email or password."
|
||||
"EMAIL_TAKEN": return "That email is already in use."
|
||||
"WEAK_PASSWORD": return "Password must be at least 8 characters."
|
||||
"INVALID_EMAIL": return "Please enter a valid email address."
|
||||
"AUTH_FAILED": return "Authentication failed. Please try again."
|
||||
_:
|
||||
return message if not message.is_empty() \
|
||||
else "Something went wrong (%s)." % code
|
||||
@@ -0,0 +1,137 @@
|
||||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://scenes/main/main_screen.gd" id="1_main"]
|
||||
|
||||
[node name="MainScreen" 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_main")
|
||||
|
||||
[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="Layout" type="VBoxContainer" parent="."]
|
||||
layout_mode = 1
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
theme_override_constants/separation = 0
|
||||
|
||||
[node name="TopBar" type="HBoxContainer" parent="Layout"]
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 56)
|
||||
theme_override_constants/separation = 12
|
||||
|
||||
[node name="TopBarMargin" type="MarginContainer" parent="Layout/TopBar"]
|
||||
layout_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
theme_override_constants/margin_left = 16
|
||||
theme_override_constants/margin_right = 16
|
||||
|
||||
[node name="TopBarInner" type="HBoxContainer" parent="Layout/TopBar/TopBarMargin"]
|
||||
layout_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
theme_override_constants/separation = 0
|
||||
|
||||
[node name="BrandLabel" type="Label" parent="Layout/TopBar/TopBarMargin/TopBarInner"]
|
||||
layout_mode = 2
|
||||
text = "ORIGIN"
|
||||
theme_override_font_sizes/font_size = 18
|
||||
size_flags_vertical = 4
|
||||
|
||||
[node name="TopSpacer" type="Control" parent="Layout/TopBar/TopBarMargin/TopBarInner"]
|
||||
layout_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
|
||||
[node name="StatusLabel" type="Label" parent="Layout/TopBar/TopBarMargin/TopBarInner"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
text = "● Online"
|
||||
modulate = Color(0.3, 0.9, 0.4, 1.0)
|
||||
size_flags_vertical = 4
|
||||
theme_override_font_sizes/font_size = 13
|
||||
|
||||
[node name="Separator" type="HSeparator" parent="Layout"]
|
||||
layout_mode = 2
|
||||
|
||||
[node name="Scroll" type="ScrollContainer" parent="Layout"]
|
||||
layout_mode = 2
|
||||
size_flags_vertical = 3
|
||||
|
||||
[node name="Content" type="VBoxContainer" parent="Layout/Scroll"]
|
||||
layout_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
theme_override_constants/separation = 16
|
||||
|
||||
[node name="ContentMargin" type="MarginContainer" parent="Layout/Scroll/Content"]
|
||||
layout_mode = 2
|
||||
theme_override_constants/margin_left = 20
|
||||
theme_override_constants/margin_top = 20
|
||||
theme_override_constants/margin_right = 20
|
||||
theme_override_constants/margin_bottom = 20
|
||||
|
||||
[node name="ContentInner" type="VBoxContainer" parent="Layout/Scroll/Content/ContentMargin"]
|
||||
layout_mode = 2
|
||||
theme_override_constants/separation = 20
|
||||
|
||||
[node name="WelcomeLabel" type="Label" parent="Layout/Scroll/Content/ContentMargin/ContentInner"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
text = "Welcome!"
|
||||
theme_override_font_sizes/font_size = 24
|
||||
|
||||
[node name="NavSection" type="Label" parent="Layout/Scroll/Content/ContentMargin/ContentInner"]
|
||||
layout_mode = 2
|
||||
text = "PLAY"
|
||||
modulate = Color(0.6, 0.6, 0.65, 1.0)
|
||||
theme_override_font_sizes/font_size = 11
|
||||
|
||||
[node name="NavButtons" type="VBoxContainer" parent="Layout/Scroll/Content/ContentMargin/ContentInner"]
|
||||
layout_mode = 2
|
||||
theme_override_constants/separation = 10
|
||||
|
||||
[node name="CollectionBtn" type="Button" parent="Layout/Scroll/Content/ContentMargin/ContentInner/NavButtons"]
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 52)
|
||||
text = "My Collection"
|
||||
theme_override_font_sizes/font_size = 15
|
||||
|
||||
[node name="BazaarBtn" type="Button" parent="Layout/Scroll/Content/ContentMargin/ContentInner/NavButtons"]
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 52)
|
||||
text = "Bazaar"
|
||||
theme_override_font_sizes/font_size = 15
|
||||
|
||||
[node name="MatchBtn" type="Button" parent="Layout/Scroll/Content/ContentMargin/ContentInner/NavButtons"]
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 52)
|
||||
text = "Find Match"
|
||||
theme_override_font_sizes/font_size = 15
|
||||
|
||||
[node name="BottomBar" type="HBoxContainer" parent="Layout"]
|
||||
layout_mode = 2
|
||||
custom_minimum_size = Vector2(0, 56)
|
||||
|
||||
[node name="BottomMargin" type="MarginContainer" parent="Layout/BottomBar"]
|
||||
layout_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
theme_override_constants/margin_left = 16
|
||||
theme_override_constants/margin_right = 16
|
||||
|
||||
[node name="LogoutBtn" type="Button" parent="Layout/BottomBar/BottomMargin"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
text = "Sign Out"
|
||||
theme_override_font_sizes/font_size = 14
|
||||
@@ -0,0 +1,53 @@
|
||||
extends Control
|
||||
## Main hub screen — shown after successful authentication.
|
||||
##
|
||||
## Displays the player's display name and live connection status.
|
||||
## Placeholder navigation buttons for future game features.
|
||||
##
|
||||
## If auth.hello re-validation fails after a reconnect (expired session),
|
||||
## Auth.auth_failed fires and we redirect back to the login screen.
|
||||
|
||||
@onready var welcome_label : Label = %WelcomeLabel
|
||||
@onready var status_label : Label = %StatusLabel
|
||||
@onready var logout_btn : Button = %LogoutBtn
|
||||
|
||||
# ── Lifecycle ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func _ready() -> void:
|
||||
welcome_label.text = "Welcome, %s!" % Auth.display_name
|
||||
|
||||
Network.connected.connect(_update_status)
|
||||
Network.disconnected.connect(_update_status)
|
||||
Auth.auth_failed.connect(_on_auth_failed)
|
||||
logout_btn.pressed.connect(_on_logout_pressed)
|
||||
|
||||
_update_status()
|
||||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
if Network.connected.is_connected(_update_status):
|
||||
Network.connected.disconnect(_update_status)
|
||||
if Network.disconnected.is_connected(_update_status):
|
||||
Network.disconnected.disconnect(_update_status)
|
||||
if Auth.auth_failed.is_connected(_on_auth_failed):
|
||||
Auth.auth_failed.disconnect(_on_auth_failed)
|
||||
|
||||
# ── Signal handlers ───────────────────────────────────────────────────────────
|
||||
|
||||
func _update_status() -> void:
|
||||
if Network.is_online():
|
||||
status_label.text = "● Online"
|
||||
status_label.modulate = Color(0.3, 0.9, 0.4)
|
||||
else:
|
||||
status_label.text = "● Reconnecting…"
|
||||
status_label.modulate = Color(1.0, 0.8, 0.2)
|
||||
|
||||
|
||||
func _on_auth_failed(_error_code: String, _message: String) -> void:
|
||||
# Session expired or invalidated — return to login.
|
||||
get_tree().change_scene_to_file("res://scenes/login/LoginScreen.tscn")
|
||||
|
||||
|
||||
func _on_logout_pressed() -> void:
|
||||
Auth.logout()
|
||||
get_tree().change_scene_to_file("res://scenes/login/LoginScreen.tscn")
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
@* Mobile topbar: hamburger + brand. Hidden on desktop via CSS. *@
|
||||
<div class="sor-admin-topbar">
|
||||
<button class="btn btn-link text-white p-0 me-3"
|
||||
<button class="sor-admin-hamburger"
|
||||
@onclick="ToggleDrawer"
|
||||
aria-label="Toggle navigation">
|
||||
<i class="bi bi-list fs-3"></i>
|
||||
|
||||
@@ -75,16 +75,21 @@ html, body {
|
||||
/* ── Mobile overrides (< lg = 992px) ────────────────────────────────────────── */
|
||||
|
||||
@media (max-width: 991.98px) {
|
||||
/* Topbar strip: hamburger + brand */
|
||||
/* Topbar strip: hamburger + brand.
|
||||
position:sticky keeps it visible when content scrolls;
|
||||
z-index:1050 puts it above the sidebar (1045) and backdrop (1040)
|
||||
so the hamburger is always tappable. */
|
||||
.sor-admin-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 56px;
|
||||
padding: 0 1rem;
|
||||
background: var(--bs-dark, #212529);
|
||||
color: white;
|
||||
background: #212529; /* hard-coded: stays dark in both BS themes */
|
||||
color: #fff;
|
||||
flex-shrink: 0;
|
||||
z-index: 1000;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1050;
|
||||
}
|
||||
|
||||
/* Sidebar becomes a fixed overlay drawer, slides in from the left */
|
||||
@@ -117,6 +122,28 @@ html, body {
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Hamburger button ───────────────────────────────────────────────────────── */
|
||||
/* Bypasses Bootstrap btn/btn-link color overrides entirely — always white,
|
||||
regardless of the active BS theme (light or dark). */
|
||||
|
||||
.sor-admin-hamburger {
|
||||
background: none;
|
||||
border: none;
|
||||
color: #fff;
|
||||
padding: 0.375rem 0.5rem;
|
||||
margin-right: 0.5rem;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
|
||||
.sor-admin-hamburger:hover,
|
||||
.sor-admin-hamburger:focus {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* ── Monospace JSON editor ──────────────────────────────────────────────────── */
|
||||
|
||||
.font-monospace {
|
||||
|
||||
@@ -17,8 +17,6 @@ using SOR.Shared.Proto;
|
||||
/// </summary>
|
||||
public sealed class GatewayAuthValidator : IGatewayAuthValidator
|
||||
{
|
||||
// AuthService.AuthServiceClient is the generated client stub from auth.proto.
|
||||
// It wraps a gRPC channel and provides typed RPC methods (ValidateTokenAsync, etc.).
|
||||
private readonly AuthService.AuthServiceClient _grpcClient;
|
||||
private readonly ILogger<GatewayAuthValidator> _logger;
|
||||
|
||||
@@ -37,8 +35,6 @@ public sealed class GatewayAuthValidator : IGatewayAuthValidator
|
||||
{
|
||||
try
|
||||
{
|
||||
// Call the Auth service's ValidateToken RPC.
|
||||
// This is a synchronous RPC (request → response) over gRPC.
|
||||
var response = await _grpcClient.ValidateTokenAsync(
|
||||
new ValidateTokenRequest { SessionToken = sessionToken },
|
||||
cancellationToken: cancellationToken);
|
||||
@@ -53,11 +49,56 @@ public sealed class GatewayAuthValidator : IGatewayAuthValidator
|
||||
}
|
||||
catch (Grpc.Core.RpcException ex)
|
||||
{
|
||||
// gRPC exception: Auth service is unreachable, overloaded, or returned an error.
|
||||
// Treat as invalid — never accept a connection that cannot be validated.
|
||||
_logger.LogWarning(ex,
|
||||
"Auth gRPC call failed during token validation: {Status}", ex.Status.StatusCode);
|
||||
return (false, string.Empty, string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)>
|
||||
LoginAsync(string email, string password, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _grpcClient.LoginAsync(
|
||||
new LoginRequest { Email = email, Password = password },
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
if (!response.Success)
|
||||
return (false, response.ErrorCode, string.Empty, string.Empty, string.Empty);
|
||||
|
||||
// Token is returned; fetch display name via ValidateToken (it includes it).
|
||||
var validate = await ValidateAsync(response.SessionToken, cancellationToken);
|
||||
return (true, string.Empty, response.SessionToken, validate.UserId, validate.DisplayName);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)>
|
||||
RegisterAsync(string email, string password, string displayName, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _grpcClient.RegisterAsync(
|
||||
new RegisterRequest { Email = email, Password = password, DisplayName = displayName },
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
if (!response.Success)
|
||||
return (false, response.ErrorCode, string.Empty, string.Empty, string.Empty);
|
||||
|
||||
var validate = await ValidateAsync(response.SessionToken, cancellationToken);
|
||||
return (true, string.Empty, response.SessionToken, validate.UserId, validate.DisplayName);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,18 +14,24 @@ namespace SOR.Gateway.Auth;
|
||||
public interface IGatewayAuthValidator
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates a session token by calling the Auth service.
|
||||
///
|
||||
/// Returns a tuple:
|
||||
/// - Valid: true if the token exists and has not expired or been revoked
|
||||
/// - UserId: the token owner's user ID (empty string if Valid = false)
|
||||
/// - DisplayName: the token owner's display name (empty string if Valid = false)
|
||||
///
|
||||
/// On Auth service unavailability (gRPC exception), returns Valid = false.
|
||||
/// This treats auth failures as invalid — better to reject than to let
|
||||
/// potentially invalid connections through.
|
||||
/// Validates an existing session token.
|
||||
/// Returns (Valid=false, …) on invalid/expired token or Auth service error.
|
||||
/// </summary>
|
||||
Task<(bool Valid, string UserId, string DisplayName)> ValidateAsync(
|
||||
string sessionToken,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Authenticates with email + password. Returns the new session token on success.
|
||||
/// ErrorCode is set (and SessionToken is empty) on failure.
|
||||
/// </summary>
|
||||
Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)>
|
||||
LoginAsync(string email, string password, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Registers a new account. Returns the new session token on success.
|
||||
/// ErrorCode is set (and SessionToken is empty) on failure.
|
||||
/// </summary>
|
||||
Task<(bool Success, string ErrorCode, string SessionToken, string UserId, string DisplayName)>
|
||||
RegisterAsync(string email, string password, string displayName, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -13,85 +13,63 @@ using SOR.Shared.Networking;
|
||||
/// <summary>
|
||||
/// Runs the full lifecycle of a single client connection.
|
||||
///
|
||||
/// This is the most important class in the Gateway. Every connected client
|
||||
/// has exactly one ConnectionLoop running as an independent Task.
|
||||
///
|
||||
/// Lifecycle phases:
|
||||
/// Phase 1: Auth handshake — wait for auth.hello, validate token
|
||||
/// Phase 2: Promote to authenticated — register in ConnectionManager
|
||||
/// Phase 1: Receive first message (auth.hello / auth.login / auth.register)
|
||||
/// Phase 2: Validate / create session — promote to AuthenticatedConnection
|
||||
/// Phase 3: Subscribe to Redis push channel
|
||||
/// Phase 4: Main message loop — receive → dispatch → optional reply
|
||||
/// Phase 5: Cleanup — always runs in finally (guaranteed cleanup)
|
||||
///
|
||||
/// Lifetime: Transient per connection. GatewayHostedService fires one Task per
|
||||
/// accepted IClientConnection. Each Task owns this class for its lifetime.
|
||||
/// Lifetime: Transient per connection.
|
||||
/// </summary>
|
||||
public sealed class ConnectionLoop
|
||||
{
|
||||
private readonly ConnectionManager _connectionManager;
|
||||
private readonly IMessageDispatcher _dispatcher;
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly IGatewayAuthValidator _authValidator;
|
||||
private readonly IConnectionMultiplexer _redis;
|
||||
private readonly GatewayOptions _options;
|
||||
private readonly ConnectionManager _connectionManager;
|
||||
private readonly IMessageDispatcher _dispatcher;
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly IGatewayAuthValidator _authValidator;
|
||||
private readonly IConnectionMultiplexer _redis;
|
||||
private readonly GatewayOptions _options;
|
||||
private readonly ILogger<ConnectionLoop> _logger;
|
||||
|
||||
public ConnectionLoop(
|
||||
ConnectionManager connectionManager,
|
||||
IMessageDispatcher dispatcher,
|
||||
IMessageSerializer serializer,
|
||||
IGatewayAuthValidator authValidator,
|
||||
IConnectionMultiplexer redis,
|
||||
ConnectionManager connectionManager,
|
||||
IMessageDispatcher dispatcher,
|
||||
IMessageSerializer serializer,
|
||||
IGatewayAuthValidator authValidator,
|
||||
IConnectionMultiplexer redis,
|
||||
IOptions<GatewayOptions> options,
|
||||
ILogger<ConnectionLoop> logger)
|
||||
{
|
||||
_connectionManager = connectionManager;
|
||||
_dispatcher = dispatcher;
|
||||
_serializer = serializer;
|
||||
_authValidator = authValidator;
|
||||
_redis = redis;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_dispatcher = dispatcher;
|
||||
_serializer = serializer;
|
||||
_authValidator = authValidator;
|
||||
_redis = redis;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the full connection lifecycle for a raw, unauthenticated IClientConnection.
|
||||
///
|
||||
/// This method is called by GatewayHostedService as a fire-and-forget Task.
|
||||
/// It handles its own exceptions — errors here must not propagate to the accept loop.
|
||||
///
|
||||
/// The 'appCancellationToken' is the application shutdown token. When cancelled,
|
||||
/// the connection closes gracefully.
|
||||
/// </summary>
|
||||
public async Task RunAsync(
|
||||
IClientConnection rawConnection,
|
||||
CancellationToken appCancellationToken)
|
||||
{
|
||||
// 'authConn' is null until the handshake completes.
|
||||
// Used in finally to decide whether to unregister from ConnectionManager.
|
||||
AuthenticatedConnection? authConn = null;
|
||||
RedisPushSubscriber? pushSubscriber = null;
|
||||
AuthenticatedConnection? authConn = null;
|
||||
RedisPushSubscriber? pushSubscriber = null;
|
||||
|
||||
try
|
||||
{
|
||||
// ── Phase 1: Auth Handshake ────────────────────────────────────────────
|
||||
// ── Phase 1: Receive first message ────────────────────────────────────
|
||||
|
||||
_logger.LogDebug(
|
||||
"Connection accepted: ConnectionId={ConnectionId} Remote={Remote}",
|
||||
rawConnection.ConnectionId, rawConnection.RemoteAddress);
|
||||
|
||||
// Create a combined cancellation token: cancel if either the app shuts down
|
||||
// OR the auth timeout expires. Whichever comes first.
|
||||
//
|
||||
// CancellationTokenSource.CreateLinkedTokenSource creates a new token that
|
||||
// is cancelled when ANY of the source tokens are cancelled.
|
||||
using var authTimeoutSts =
|
||||
new CancellationTokenSource(TimeSpan.FromMilliseconds(_options.AuthTimeoutMs));
|
||||
using var authLinked = CancellationTokenSource.CreateLinkedTokenSource(
|
||||
appCancellationToken, authTimeoutSts.Token);
|
||||
|
||||
// Wait for the first message. Must be auth.hello.
|
||||
// Returns null on clean close (client disconnected before sending anything).
|
||||
var rawMsg = await rawConnection.ReceiveAsync(authLinked.Token);
|
||||
|
||||
if (rawMsg is null)
|
||||
@@ -102,8 +80,6 @@ public sealed class ConnectionLoop
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse the envelope (type, seq, inner payload bytes).
|
||||
// rawMsg.Payload contains the full wire bytes (envelope + payload).
|
||||
IClientMessage parsedMsg;
|
||||
try
|
||||
{
|
||||
@@ -118,80 +94,102 @@ public sealed class ConnectionLoop
|
||||
return;
|
||||
}
|
||||
|
||||
// The first message MUST be auth.hello.
|
||||
if (!string.Equals(parsedMsg.Type, "auth.hello", StringComparison.OrdinalIgnoreCase))
|
||||
// ── Phase 2: Auth Handshake — hello / login / register ────────────────
|
||||
//
|
||||
// auth.hello { sessionToken } — reconnect with saved token
|
||||
// auth.login { email, password } — credential login
|
||||
// auth.register { email, password, displayName } — new account
|
||||
|
||||
string sessionToken;
|
||||
string userId;
|
||||
string displayName;
|
||||
string ackType;
|
||||
|
||||
switch (parsedMsg.Type.ToLowerInvariant())
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"First message is not auth.hello: Type={Type} ConnectionId={ConnectionId}",
|
||||
parsedMsg.Type, rawConnection.ConnectionId);
|
||||
case "auth.hello":
|
||||
{
|
||||
AuthHelloPayload payload;
|
||||
try { payload = _serializer.DeserializePayload<AuthHelloPayload>(parsedMsg.Payload); }
|
||||
catch { await RejectAsync(rawConnection, parsedMsg.Seq, "INVALID_PAYLOAD", "auth.hello payload is malformed.", appCancellationToken); return; }
|
||||
|
||||
await SendErrorAsync(rawConnection, parsedMsg.Seq,
|
||||
"AUTH_REQUIRED", "First message must be auth.hello.", appCancellationToken);
|
||||
await rawConnection.CloseAsync("auth_required", appCancellationToken);
|
||||
return;
|
||||
}
|
||||
var (valid, uid, dname) =
|
||||
await _authValidator.ValidateAsync(payload.SessionToken, appCancellationToken);
|
||||
if (!valid)
|
||||
{
|
||||
await RejectAsync(rawConnection, parsedMsg.Seq,
|
||||
"AUTH_FAILED", "Invalid or expired session token.", appCancellationToken);
|
||||
return;
|
||||
}
|
||||
(sessionToken, userId, displayName, ackType) =
|
||||
(payload.SessionToken, uid, dname, "auth.hello.ack");
|
||||
break;
|
||||
}
|
||||
|
||||
// Deserialize the auth.hello payload to get the session token.
|
||||
AuthHelloPayload helloPayload;
|
||||
try
|
||||
{
|
||||
helloPayload = _serializer.DeserializePayload<AuthHelloPayload>(parsedMsg.Payload);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"Failed to deserialize auth.hello payload: ConnectionId={ConnectionId}",
|
||||
rawConnection.ConnectionId);
|
||||
await SendErrorAsync(rawConnection, parsedMsg.Seq,
|
||||
"INVALID_PAYLOAD", "auth.hello payload is malformed.", appCancellationToken);
|
||||
await rawConnection.CloseAsync("invalid_payload", appCancellationToken);
|
||||
return;
|
||||
}
|
||||
case "auth.login":
|
||||
{
|
||||
AuthLoginPayload payload;
|
||||
try { payload = _serializer.DeserializePayload<AuthLoginPayload>(parsedMsg.Payload); }
|
||||
catch { await RejectAsync(rawConnection, parsedMsg.Seq, "INVALID_PAYLOAD", "auth.login payload is malformed.", appCancellationToken); return; }
|
||||
|
||||
// ── Phase 2: Token Validation ──────────────────────────────────────────
|
||||
var (success, errorCode, token, uid, dname) =
|
||||
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");
|
||||
break;
|
||||
}
|
||||
|
||||
var (isValid, userId, displayName) =
|
||||
await _authValidator.ValidateAsync(helloPayload.SessionToken, appCancellationToken);
|
||||
case "auth.register":
|
||||
{
|
||||
AuthRegisterPayload payload;
|
||||
try { payload = _serializer.DeserializePayload<AuthRegisterPayload>(parsedMsg.Payload); }
|
||||
catch { await RejectAsync(rawConnection, parsedMsg.Seq, "INVALID_PAYLOAD", "auth.register payload is malformed.", appCancellationToken); return; }
|
||||
|
||||
if (!isValid)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Auth failed: ConnectionId={ConnectionId} Remote={Remote}",
|
||||
rawConnection.ConnectionId, rawConnection.RemoteAddress);
|
||||
var (success, errorCode, token, uid, dname) =
|
||||
await _authValidator.RegisterAsync(
|
||||
payload.Email, payload.Password, payload.DisplayName, appCancellationToken);
|
||||
if (!success)
|
||||
{
|
||||
await RejectAsync(rawConnection, parsedMsg.Seq, errorCode, "Registration failed.", appCancellationToken);
|
||||
return;
|
||||
}
|
||||
(sessionToken, userId, displayName, ackType) =
|
||||
(token, uid, dname, "auth.register.ack");
|
||||
break;
|
||||
}
|
||||
|
||||
await SendErrorAsync(rawConnection, parsedMsg.Seq,
|
||||
"AUTH_FAILED", "Invalid or expired session token.", appCancellationToken);
|
||||
await rawConnection.CloseAsync("auth_failed", appCancellationToken);
|
||||
return;
|
||||
default:
|
||||
_logger.LogWarning(
|
||||
"First message is not an auth type: Type={Type} ConnectionId={ConnectionId}",
|
||||
parsedMsg.Type, rawConnection.ConnectionId);
|
||||
await RejectAsync(rawConnection, parsedMsg.Seq, "AUTH_REQUIRED",
|
||||
"First message must be auth.hello, auth.login, or auth.register.",
|
||||
appCancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Phase 3: Promote to Authenticated Connection ───────────────────────
|
||||
|
||||
authConn = new AuthenticatedConnection(
|
||||
rawConnection, userId, displayName, helloPayload.SessionToken);
|
||||
|
||||
authConn = new AuthenticatedConnection(rawConnection, userId, displayName, sessionToken);
|
||||
_connectionManager.Register(authConn);
|
||||
|
||||
_logger.LogInformation(
|
||||
"User authenticated: UserId={UserId} DisplayName={DisplayName} " +
|
||||
"ConnectionId={ConnectionId}",
|
||||
userId, displayName, rawConnection.ConnectionId);
|
||||
"User authenticated via {Type}: UserId={UserId} DisplayName={DisplayName} ConnectionId={ConnectionId}",
|
||||
parsedMsg.Type, userId, displayName, rawConnection.ConnectionId);
|
||||
|
||||
// Send acknowledgement to client.
|
||||
// Ack includes sessionToken so the client can persist it after login/register.
|
||||
await SendMessageAsync(
|
||||
rawConnection,
|
||||
ServerMessage.Reply("auth.hello.ack", parsedMsg.Seq, new
|
||||
{
|
||||
userId,
|
||||
displayName
|
||||
}),
|
||||
ServerMessage.Reply(ackType, parsedMsg.Seq, new { userId, displayName, sessionToken }),
|
||||
appCancellationToken);
|
||||
|
||||
// ── Phase 4: Subscribe to Redis Push Channel ───────────────────────────
|
||||
|
||||
// Create a logger for the push subscriber that includes the userId.
|
||||
// GetRequiredService<ILogger{RedisPushSubscriber}> would give a generic logger;
|
||||
// we use CreateLogger with a category name that includes the userId for filtering.
|
||||
var pushLogger = _logger as ILogger<RedisPushSubscriber>
|
||||
?? Microsoft.Extensions.Logging.Abstractions.NullLogger<RedisPushSubscriber>.Instance;
|
||||
|
||||
@@ -202,8 +200,6 @@ public sealed class ConnectionLoop
|
||||
|
||||
while (rawConnection.IsConnected && !appCancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Wait for the next message from the client.
|
||||
// Returns null on clean close (client sent WebSocket close frame).
|
||||
IClientMessage? nextRaw;
|
||||
try
|
||||
{
|
||||
@@ -211,21 +207,17 @@ public sealed class ConnectionLoop
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// App is shutting down — exit the loop cleanly.
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Network error (connection dropped unexpectedly).
|
||||
_logger.LogDebug(ex,
|
||||
"Receive error for user {UserId}: connection dropped",
|
||||
userId);
|
||||
"Receive error for user {UserId}: connection dropped", userId);
|
||||
break;
|
||||
}
|
||||
|
||||
if (nextRaw is null) break; // Clean close from client.
|
||||
if (nextRaw is null) break;
|
||||
|
||||
// Parse the message envelope.
|
||||
IClientMessage nextMsg;
|
||||
try
|
||||
{
|
||||
@@ -235,13 +227,11 @@ public sealed class ConnectionLoop
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"Failed to deserialize message from user {UserId}", userId);
|
||||
// Malformed message: send an error but keep the connection alive.
|
||||
await SendErrorAsync(rawConnection, 0,
|
||||
"INVALID_MESSAGE", "Message could not be parsed.", appCancellationToken);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check that a handler exists for this message type.
|
||||
if (!_dispatcher.HasHandler(nextMsg.Type))
|
||||
{
|
||||
_logger.LogDebug(
|
||||
@@ -254,7 +244,6 @@ public sealed class ConnectionLoop
|
||||
continue;
|
||||
}
|
||||
|
||||
// Dispatch to the registered handler.
|
||||
IServerMessage? response;
|
||||
try
|
||||
{
|
||||
@@ -263,7 +252,6 @@ public sealed class ConnectionLoop
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Handler threw an unexpected exception.
|
||||
_logger.LogError(ex,
|
||||
"Handler for '{Type}' threw for user {UserId}",
|
||||
nextMsg.Type, userId);
|
||||
@@ -272,41 +260,30 @@ public sealed class ConnectionLoop
|
||||
continue;
|
||||
}
|
||||
|
||||
// Send the handler's reply if one was returned.
|
||||
if (response is not null)
|
||||
{
|
||||
await SendMessageAsync(rawConnection, response, appCancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Normal exit: auth timeout fired, or app shutdown, or client disconnected.
|
||||
// OperationCanceledException is not an error — it's the expected exit signal.
|
||||
_logger.LogDebug(
|
||||
"Connection loop cancelled: ConnectionId={ConnectionId}",
|
||||
rawConnection.ConnectionId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Unexpected error in the connection loop itself (not in a handler).
|
||||
_logger.LogError(ex,
|
||||
"Unexpected error in connection loop: ConnectionId={ConnectionId}",
|
||||
rawConnection.ConnectionId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// ── Phase 6: Cleanup — ALWAYS runs, regardless of how the loop exited ──
|
||||
|
||||
// Unsubscribe from Redis push channel.
|
||||
if (pushSubscriber is not null)
|
||||
await pushSubscriber.DisposeAsync();
|
||||
|
||||
// Unregister from the connection map.
|
||||
if (authConn is not null)
|
||||
_connectionManager.Unregister(rawConnection.ConnectionId);
|
||||
|
||||
// Dispose the connection (closes WebSocket, signals middleware done TCS).
|
||||
await rawConnection.DisposeAsync();
|
||||
|
||||
_logger.LogDebug(
|
||||
@@ -317,13 +294,9 @@ public sealed class ConnectionLoop
|
||||
|
||||
// ── Private helpers ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Serializes and sends a message to the raw (pre-auth) or authenticated connection.
|
||||
/// Errors here are swallowed — if the send fails the connection is already gone.
|
||||
/// </summary>
|
||||
private async Task SendMessageAsync(
|
||||
IClientConnection connection,
|
||||
IServerMessage message,
|
||||
IServerMessage message,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
@@ -341,25 +314,24 @@ public sealed class ConnectionLoop
|
||||
|
||||
private Task SendErrorAsync(
|
||||
IClientConnection connection,
|
||||
int refSeq,
|
||||
string errorCode,
|
||||
string errorMessage,
|
||||
int refSeq, string errorCode, string errorMessage,
|
||||
CancellationToken cancellationToken) =>
|
||||
SendMessageAsync(
|
||||
connection,
|
||||
SendMessageAsync(connection,
|
||||
ServerMessage.Error(refSeq, errorCode, errorMessage),
|
||||
cancellationToken);
|
||||
|
||||
// ── Inner type: auth.hello payload ────────────────────────────────────────
|
||||
private async Task RejectAsync(
|
||||
IClientConnection connection,
|
||||
int refSeq, string errorCode, string errorMessage,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await SendErrorAsync(connection, refSeq, errorCode, errorMessage, cancellationToken);
|
||||
await connection.CloseAsync(errorCode.ToLowerInvariant(), cancellationToken);
|
||||
}
|
||||
|
||||
// ── Auth payload types ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Deserialization target for the auth.hello message payload.
|
||||
///
|
||||
/// Client sends:
|
||||
/// { "type": "auth.hello", "seq": 1, "payload": { "sessionToken": "abc123..." } }
|
||||
///
|
||||
/// 'record' with 'init' properties: immutable after deserialization.
|
||||
/// Properties must match JSON keys (camelCase by default via IMessageSerializer options).
|
||||
/// </summary>
|
||||
private sealed record AuthHelloPayload(string SessionToken);
|
||||
private sealed record AuthLoginPayload(string Email, string Password);
|
||||
private sealed record AuthRegisterPayload(string Email, string Password, string DisplayName);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user