Files
sor/Client/origin-client/autoloads/Auth.gd
T
2508fe1297 client: force WebSocket reconnect on logout so auth arrives on a fresh connection
logout() now calls Network.force_reconnect() to tear down the existing Phase-5
connection; the next auth.login / auth.register is then the very first message
on the new connection, which is the only point where ConnectionLoop handles auth.

Also adds Network.force_reconnect() public method.

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>
2026-03-01 22:55:45 -05:00

164 lines
6.2 KiB
GDScript

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
## session_expired — auto-logout fired after disconnect timeout
const SAVE_PATH := "user://auth.cfg"
const SECTION := "auth"
## Saved sessions older than this are discarded on load (forces re-login).
const SESSION_TTL_DAYS := 30
## If the WebSocket stays disconnected for this many minutes while logged in,
## automatically clear the session and return to the login screen.
const DISCONNECT_LOGOUT_MIN := 30
signal auth_success(user_id: String, display_name: String)
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 = ""
## 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
# ── Lifecycle ─────────────────────────────────────────────────────────────────
func _ready() -> void:
_load_session()
Network.connected.connect(_on_network_connected)
Network.disconnected.connect(_on_network_disconnected)
func _process(_delta: float) -> void:
if _disconnect_at < 0.0 or session_token.is_empty():
return
if _now() - _disconnect_at >= DISCONNECT_LOGOUT_MIN * 60.0:
_disconnect_at = -1.0
logout()
session_expired.emit()
get_tree().change_scene_to_file("res://scenes/login/LoginScreen.tscn")
# ── 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.
func logout() -> void:
user_id = ""
display_name = ""
session_token = ""
needs_starter_deck = false
_save_session()
Network.force_reconnect()
# ── Private ───────────────────────────────────────────────────────────────────
## Called every time the WebSocket connects (including after reconnects).
## Cancels the disconnect timer. If a session token is saved, sends auth.hello.
func _on_network_connected() -> void:
_disconnect_at = -1.0 # Cancel any pending auto-logout.
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):
if code == "DISCONNECTED":
# Transient network drop — keep the token and retry on reconnect.
auth_failed.emit(code, msg)
return
# Session explicitly rejected (expired / revoked / invalid).
# Wipe all auth state, emit the failure, then drive the scene
# change here so every screen (main, collection, etc.) is covered
# without each needing its own auth_failed handler.
logout()
auth_failed.emit(code, msg)
get_tree().change_scene_to_file("res://scenes/login/LoginScreen.tscn")
)
## Called every time the WebSocket disconnects.
## Starts the auto-logout countdown (only if logged in).
func _on_network_disconnected() -> void:
if not session_token.is_empty():
_disconnect_at = _now()
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", "")
needs_starter_deck = p.get("needsStarterDeck", false)
_save_session()
auth_success.emit(user_id, display_name)
func _load_session() -> void:
var cfg := ConfigFile.new()
if cfg.load(SAVE_PATH) != OK:
return
# Discard sessions older than SESSION_TTL_DAYS.
var saved_at: int = cfg.get_value(SECTION, "saved_at", 0)
if saved_at > 0:
var age_days := (int(Time.get_unix_time_from_system()) - saved_at) / 86400
if age_days >= SESSION_TTL_DAYS:
return # Expired — treat as fresh launch.
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)
# Only write a timestamp when there is an active session to expire.
if not session_token.is_empty():
cfg.set_value(SECTION, "saved_at", int(Time.get_unix_time_from_system()))
cfg.save(SAVE_PATH)
func _now() -> float:
return Time.get_ticks_msec() / 1000.0