247 lines
9.4 KiB
GDScript
247 lines
9.4 KiB
GDScript
extends Node
|
|
## Authentication autoload.
|
|
##
|
|
## Drives the auth handshake as the first WebSocket message on every connection:
|
|
## auth.hello — resume a saved SOR session token (silent reconnect)
|
|
## auth.keycloak — exchange a Keycloak access token for a new SOR session token
|
|
##
|
|
## Persists the SOR session token (30-day opaque token) and the Keycloak refresh
|
|
## token to disk so the player stays logged in across restarts.
|
|
##
|
|
## Silent re-authentication flow:
|
|
## 1. On connect, send auth.hello with saved SOR session token.
|
|
## 2. If rejected (token expired/revoked): clear session, use saved Keycloak
|
|
## refresh token to silently obtain a new Keycloak access token, then
|
|
## reconnect and send auth.keycloak — no browser required.
|
|
## 3. If the Keycloak refresh token is also expired: route to LoginScreen.
|
|
##
|
|
## 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 — disconnect timeout fired auto-logout
|
|
|
|
const SAVE_PATH := "user://auth.cfg"
|
|
const SECTION := "auth"
|
|
|
|
## Sessions older than this are discarded on load (forces re-login).
|
|
const SESSION_TTL_DAYS := 30
|
|
|
|
## If disconnected for this many minutes while logged in, auto-logout.
|
|
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
|
|
|
|
## Set after a successful auth. Empty while unauthenticated.
|
|
var user_id: String = ""
|
|
var display_name: String = ""
|
|
var session_token: String = ""
|
|
var needs_starter_deck: bool = false
|
|
|
|
## Keycloak refresh token — persisted to enable silent re-auth when the SOR
|
|
## session token expires. Cleared on logout.
|
|
var keycloak_refresh_token: String = ""
|
|
|
|
## Pending Keycloak access token waiting for the next WebSocket connection.
|
|
## Set by _try_silent_refresh and login_with_keycloak; consumed in _on_network_connected.
|
|
var _pending_keycloak_token: String = ""
|
|
|
|
## True while a silent Keycloak refresh is in-flight (prevents duplicate attempts).
|
|
var _refresh_in_progress: 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 ────────────────────────────────────────────────────────────────
|
|
|
|
## Exchange a freshly obtained Keycloak access token for a SOR session token.
|
|
## Also stores the refresh token so silent re-auth works on next session.
|
|
## Called by login_screen.gd after Keycloak.token_received fires.
|
|
func login_with_keycloak(access_token: String, refresh_token: String) -> void:
|
|
keycloak_refresh_token = refresh_token
|
|
_save_session()
|
|
_pending_keycloak_token = access_token
|
|
# Always force a fresh WebSocket connection so auth.keycloak is the very
|
|
# first message the server sees. The socket that was open while the user
|
|
# was in the browser has likely already been closed by the server's
|
|
# AuthTimeoutMs (10 s of silence) — sending on that stale connection
|
|
# yields no reply. force_reconnect() closes it immediately; the next
|
|
# _on_network_connected() will call _send_keycloak_auth().
|
|
Network.force_reconnect()
|
|
|
|
|
|
## Clear all auth state and disconnect, returning to the login screen.
|
|
func logout() -> void:
|
|
# Revoke the Keycloak refresh token with the server (fire-and-forget).
|
|
if not keycloak_refresh_token.is_empty():
|
|
Keycloak.revoke(keycloak_refresh_token)
|
|
|
|
user_id = ""
|
|
display_name = ""
|
|
session_token = ""
|
|
keycloak_refresh_token = ""
|
|
_pending_keycloak_token = ""
|
|
needs_starter_deck = false
|
|
_refresh_in_progress = false
|
|
session_expired.emit()
|
|
_save_session()
|
|
Network.force_reconnect()
|
|
|
|
# ── Internal connection handlers ──────────────────────────────────────────────
|
|
|
|
func _on_network_connected() -> void:
|
|
_disconnect_at = -1.0
|
|
|
|
if not session_token.is_empty():
|
|
# Try to resume the existing SOR session silently.
|
|
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 drop — keep the token and retry on next reconnect.
|
|
auth_failed.emit(code, msg)
|
|
return
|
|
# SOR session rejected (expired / revoked).
|
|
session_token = ""
|
|
_save_session()
|
|
if not keycloak_refresh_token.is_empty() and not _refresh_in_progress:
|
|
_try_silent_refresh()
|
|
else:
|
|
_do_logout_and_redirect(code, msg)
|
|
)
|
|
return
|
|
|
|
if not _pending_keycloak_token.is_empty():
|
|
_send_keycloak_auth()
|
|
return
|
|
|
|
# No credentials — LoginScreen will drive login.
|
|
|
|
|
|
func _on_network_disconnected() -> void:
|
|
if not session_token.is_empty():
|
|
_disconnect_at = _now()
|
|
|
|
|
|
func _send_keycloak_auth() -> void:
|
|
var token := _pending_keycloak_token
|
|
_pending_keycloak_token = ""
|
|
Network.request(
|
|
"auth.keycloak",
|
|
{ "keycloakToken": token },
|
|
func(_type: String, p: Variant): _on_auth_ok(p),
|
|
func(code: String, msg: String):
|
|
if code == "DISCONNECTED":
|
|
# Transient drop — restore the token so the next reconnect retries.
|
|
_pending_keycloak_token = token
|
|
auth_failed.emit(code, msg)
|
|
return
|
|
# Keycloak token rejected (invalid, expired, missing role).
|
|
keycloak_refresh_token = ""
|
|
_save_session()
|
|
auth_failed.emit(code, msg)
|
|
# Do NOT change scene here — the login screen is already active and
|
|
# handles auth_failed by showing the error and re-enabling the button.
|
|
# Calling change_scene_to_file would reload the screen and wipe the error.
|
|
)
|
|
|
|
|
|
## Attempt to silently refresh the Keycloak refresh token and re-establish the session.
|
|
func _try_silent_refresh() -> void:
|
|
_refresh_in_progress = true
|
|
|
|
Keycloak.token_refreshed.connect(
|
|
func(access_token: String, refresh_token: String) -> void:
|
|
_refresh_in_progress = false
|
|
keycloak_refresh_token = refresh_token # Rotate: Keycloak issues a new one.
|
|
_save_session()
|
|
_pending_keycloak_token = access_token
|
|
Network.force_reconnect(),
|
|
CONNECT_ONE_SHOT)
|
|
|
|
Keycloak.auth_error.connect(
|
|
func(msg: String) -> void:
|
|
_refresh_in_progress = false
|
|
keycloak_refresh_token = "" # Refresh token expired — full re-login required.
|
|
_save_session()
|
|
_do_logout_and_redirect("AUTH_FAILED", msg),
|
|
CONNECT_ONE_SHOT)
|
|
|
|
Keycloak.refresh(keycloak_refresh_token)
|
|
|
|
|
|
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 _do_logout_and_redirect(code: String = "AUTH_FAILED", msg: String = "") -> void:
|
|
# Full state wipe without revoking the Keycloak token (it's already gone).
|
|
user_id = ""
|
|
display_name = ""
|
|
session_token = ""
|
|
keycloak_refresh_token = ""
|
|
_pending_keycloak_token = ""
|
|
needs_starter_deck = false
|
|
_save_session()
|
|
Network.force_reconnect()
|
|
auth_failed.emit(code, msg)
|
|
get_tree().change_scene_to_file("res://scenes/login/LoginScreen.tscn")
|
|
|
|
# ── Persistence ───────────────────────────────────────────────────────────────
|
|
|
|
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
|
|
session_token = cfg.get_value(SECTION, "session_token", "")
|
|
user_id = cfg.get_value(SECTION, "user_id", "")
|
|
display_name = cfg.get_value(SECTION, "display_name", "")
|
|
keycloak_refresh_token = cfg.get_value(SECTION, "keycloak_refresh_token", "")
|
|
|
|
|
|
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.set_value(SECTION, "keycloak_refresh_token", keycloak_refresh_token)
|
|
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
|