This commit is contained in:
16 files changed
+672
-57
No files matched your search
@@ -406,6 +406,20 @@ func (g *Game) ClaimSlot(color core.Color, userID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReleaseUser clears userID's claims and name snapshots, leaving those slots
|
||||
// anonymous, and reports whether any slot changed. Player IDs stay: once the
|
||||
// account is gone they identify nobody. Caller must hold the lock.
|
||||
func (g *Game) ReleaseUser(userID string) bool {
|
||||
changed := false
|
||||
for _, player := range g.players {
|
||||
if player != nil && player.ClaimedBy == userID {
|
||||
player.ClaimedBy, player.Name = "", ""
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// GetSlotOwner returns the userID that claimed the slot, empty if unclaimed
|
||||
// Caller must hold the lock
|
||||
func (g *Game) GetSlotOwner(color core.Color) string {
|
||||
|
||||
@@ -30,6 +30,11 @@ type LoginRequest struct {
|
||||
Password string `json:"password" validate:"required"`
|
||||
}
|
||||
|
||||
// DeleteAccountRequest re-confirms the password before an account is deleted.
|
||||
type DeleteAccountRequest struct {
|
||||
Password string `json:"password" validate:"required"`
|
||||
}
|
||||
|
||||
// AuthResponse contains JWT token and user information
|
||||
type AuthResponse struct {
|
||||
Token string `json:"token"`
|
||||
@@ -269,3 +274,51 @@ func (h *HTTPHandler) LogoutHandler(c *fiber.Ctx) error {
|
||||
|
||||
return c.JSON(fiber.Map{"message": "logged out"})
|
||||
}
|
||||
|
||||
// DeleteAccountHandler deletes the caller's account after re-checking the
|
||||
// password. The caller's games lose the claim and the name; see
|
||||
// Service.DeleteAccount.
|
||||
func (h *HTTPHandler) DeleteAccountHandler(c *fiber.Ctx) error {
|
||||
userID, _ := c.Locals("userID").(string)
|
||||
sessionID, _ := c.Locals("sessionID").(string)
|
||||
if userID == "" || sessionID == "" {
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(core.ErrorResponse{
|
||||
Error: "unauthorized",
|
||||
Code: core.ErrInvalidRequest,
|
||||
})
|
||||
}
|
||||
|
||||
var req DeleteAccountRequest
|
||||
if err := c.BodyParser(&req); err != nil || req.Password == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(core.ErrorResponse{
|
||||
Error: "invalid request body",
|
||||
Code: core.ErrInvalidRequest,
|
||||
Details: "password is required to delete the account",
|
||||
})
|
||||
}
|
||||
|
||||
if err := h.svc.DeleteAccount(userID, sessionID, req.Password); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrInvalidCredentials):
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(core.ErrorResponse{
|
||||
Error: "invalid credentials",
|
||||
Code: core.ErrInvalidRequest,
|
||||
})
|
||||
case errors.Is(err, service.ErrAuthBusy):
|
||||
return c.Status(fiber.StatusServiceUnavailable).JSON(core.ErrorResponse{
|
||||
Error: "authentication temporarily unavailable", Code: core.ErrResourceLimit,
|
||||
})
|
||||
case errors.Is(err, service.ErrStorageDisabled) || errors.Is(err, service.ErrStorageUnavailable):
|
||||
return c.Status(fiber.StatusServiceUnavailable).JSON(core.ErrorResponse{
|
||||
Error: "account storage unavailable", Code: core.ErrStorageUnavailable,
|
||||
})
|
||||
default:
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(core.ErrorResponse{
|
||||
Error: "failed to delete account",
|
||||
Code: core.ErrInternalError,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
@@ -145,6 +145,22 @@ func NewFiberApp(proc *processor.Processor, svc *service.Service, opts Options)
|
||||
// Logout
|
||||
auth.Post("/logout", AuthRequired(validateToken), h.LogoutHandler)
|
||||
|
||||
// Delete own account: 5 req/min per IP. It takes a password, so it is
|
||||
// limited like login; authentication runs first, so only a signed-in
|
||||
// caller reaches the password check.
|
||||
auth.Delete("/me", AuthRequired(validateToken), limiter.New(limiter.Config{
|
||||
Max: 5,
|
||||
Expiration: 1 * time.Minute,
|
||||
KeyGenerator: clientIP,
|
||||
LimitReached: func(c *fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusTooManyRequests).JSON(core.ErrorResponse{
|
||||
Error: "rate limit exceeded",
|
||||
Code: core.ErrRateLimitExceeded,
|
||||
Details: "5 account deletion attempts per minute allowed",
|
||||
})
|
||||
},
|
||||
}), h.DeleteAccountHandler)
|
||||
|
||||
// Game routes with standard rate limiting
|
||||
maxReq := rateLimitRate
|
||||
if devMode {
|
||||
|
||||
@@ -88,6 +88,7 @@ func TestAPIRoutes(t *testing.T) {
|
||||
"POST /api/auth/login",
|
||||
"GET /api/auth/me",
|
||||
"POST /api/auth/logout",
|
||||
"DELETE /api/auth/me",
|
||||
"POST /api/games",
|
||||
"GET /api/games/:gameId",
|
||||
"GET /api/games/:gameId/history",
|
||||
@@ -212,3 +213,74 @@ func TestStoredGameEndpoints(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteAccountRequiresPasswordAndEndsTheSession(t *testing.T) {
|
||||
store, err := storage.NewStore(pgtest.DSN(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.InitDB(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc, err := service.New(store, []byte("test-secret-test-secret-test-secret"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { svc.Shutdown(time.Second) })
|
||||
app := NewFiberApp(nil, svc, Options{DevMode: true})
|
||||
|
||||
send := func(method, path, token, body string) int {
|
||||
t.Helper()
|
||||
var reader io.Reader
|
||||
if body != "" {
|
||||
reader = strings.NewReader(body)
|
||||
}
|
||||
request := httptest.NewRequest(method, path, reader)
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if token != "" {
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
response, err := app.Test(request, 10_000)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response.StatusCode
|
||||
}
|
||||
|
||||
user, sessionID, err := svc.RegisterUser("alice", "", "Password1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err := svc.GenerateUserToken(user.UserID, sessionID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for name, test := range map[string]struct {
|
||||
token, body string
|
||||
want int
|
||||
}{
|
||||
"no token": {"", `{"password":"Password1"}`, 401},
|
||||
"no password": {token, `{}`, 400},
|
||||
"wrong password": {token, `{"password":"Password2"}`, 401},
|
||||
} {
|
||||
if got := send("DELETE", "/api/auth/me", test.token, test.body); got != test.want {
|
||||
t.Errorf("%s: status %d, want %d", name, got, test.want)
|
||||
}
|
||||
}
|
||||
if got := send("GET", "/api/auth/me", token, ""); got != 200 {
|
||||
t.Fatalf("a refused deletion must leave the account working: /auth/me = %d", got)
|
||||
}
|
||||
|
||||
if got := send("DELETE", "/api/auth/me", token, `{"password":"Password1"}`); got != 204 {
|
||||
t.Fatalf("delete: status %d, want 204", got)
|
||||
}
|
||||
if got := send("GET", "/api/auth/me", token, ""); got != 401 {
|
||||
t.Errorf("token still accepted after deletion: /auth/me = %d", got)
|
||||
}
|
||||
if _, _, err := svc.AuthenticateUser("alice", "Password1"); err == nil {
|
||||
t.Error("deleted account can still sign in")
|
||||
}
|
||||
}
|
||||
@@ -203,6 +203,56 @@ func (s *Service) InvalidateSession(sessionID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteAccount deletes the caller's own account after re-checking the
|
||||
// password, so a token left on an unattended device is not enough. The
|
||||
// session goes first, so no new request can act for the account; then the
|
||||
// account's claims are released on every game in memory, then the store
|
||||
// clears them from stored games and deletes the account, behind any gameplay
|
||||
// write already queued. Games nobody else claimed are anonymous from then on
|
||||
// and are purged after the usual inactivity window.
|
||||
func (s *Service) DeleteAccount(userID, sessionID, password string) error {
|
||||
if s.store == nil {
|
||||
return ErrStorageDisabled
|
||||
}
|
||||
record, err := s.store.GetUserByID(userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrInvalidCredentials
|
||||
}
|
||||
return fmt.Errorf("%w: look up user: %v", ErrStorageUnavailable, err)
|
||||
}
|
||||
if err := s.verifyPassword(password, record.PasswordHash); err != nil {
|
||||
if errors.Is(err, ErrAuthBusy) {
|
||||
return err
|
||||
}
|
||||
return ErrInvalidCredentials
|
||||
}
|
||||
|
||||
if err := s.store.DeleteSession(sessionID); err != nil {
|
||||
return fmt.Errorf("%w: end session: %v", ErrStorageUnavailable, err)
|
||||
}
|
||||
released := s.releaseClaims(userID)
|
||||
if err := s.store.DeleteAccount(userID); err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return fmt.Errorf("%w: delete account: %v", ErrStorageUnavailable, err)
|
||||
}
|
||||
slog.Info("account deleted by its owner", "user_id", userID, "live_games_released", released)
|
||||
return nil
|
||||
}
|
||||
|
||||
// releaseClaims makes userID's slots anonymous in every game in memory and
|
||||
// returns how many games changed.
|
||||
func (s *Service) releaseClaims(userID string) int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
released := 0
|
||||
for _, g := range s.games {
|
||||
if g.ReleaseUser(userID) {
|
||||
released++
|
||||
}
|
||||
}
|
||||
return released
|
||||
}
|
||||
|
||||
// GetUserByID retrieves user information by user ID
|
||||
func (s *Service) GetUserByID(userID string) (*User, error) {
|
||||
if s.store == nil {
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lixenwraith/chess/internal/server/chess"
|
||||
"github.com/lixenwraith/chess/internal/server/core"
|
||||
"github.com/lixenwraith/chess/internal/server/storage"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -146,3 +148,44 @@ func TestNewRejectsShortJWTSecret(t *testing.T) {
|
||||
t.Fatal("31-byte JWT secret accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteAccountReleasesLiveClaims(t *testing.T) {
|
||||
svc := newPersistentTestService(t)
|
||||
user, sessionID, err := svc.RegisterUser("alice", "", "Password1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err := svc.GenerateUserToken(user.UserID, sessionID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
gameID := uuid.NewString()
|
||||
white := core.NewPlayer(core.PlayerConfig{Type: core.PlayerHuman}, core.ColorWhite)
|
||||
white.ID, white.ClaimedBy = user.UserID, user.UserID
|
||||
black := core.NewPlayer(core.PlayerConfig{Type: core.PlayerComputer, Level: 1, SearchTime: 100}, core.ColorBlack)
|
||||
if err := svc.CreateGame(gameID, white, black, chess.StartFEN, core.ColorWhite, core.StateOngoing, core.TermNone); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := svc.DeleteAccount(user.UserID, sessionID, "Password2"); !errors.Is(err, ErrInvalidCredentials) {
|
||||
t.Fatalf("wrong password: %v, want ErrInvalidCredentials", err)
|
||||
}
|
||||
if _, _, err := svc.ValidateToken(token); err != nil {
|
||||
t.Fatalf("a refused deletion ended the session: %v", err)
|
||||
}
|
||||
|
||||
if err := svc.DeleteAccount(user.UserID, sessionID, "Password1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := svc.ValidateToken(token); err == nil {
|
||||
t.Error("token still valid after deletion")
|
||||
}
|
||||
view, err := svc.GetGameView(gameID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if owner := view.WhitePlayer.ClaimedBy; owner != "" {
|
||||
t.Errorf("live game still claimed by the deleted account: %q", owner)
|
||||
}
|
||||
}
|
||||
@@ -284,6 +284,37 @@ func (s *Store) enqueue(operation, gameID string, fn func(context.Context, *sql.
|
||||
}
|
||||
}
|
||||
|
||||
// enqueueWait queues fn on the ordered writer and waits for its own outcome,
|
||||
// for a write that must be ordered after queued gameplay writes and must also
|
||||
// report success only once it is durable.
|
||||
func (s *Store) enqueueWait(ctx context.Context, operation string, fn func(context.Context, *sql.Tx) error) error {
|
||||
s.enqueueMu.RLock()
|
||||
if s.closed.Load() {
|
||||
s.enqueueMu.RUnlock()
|
||||
return ErrStoreClosed
|
||||
}
|
||||
if !s.healthStatus.Load() {
|
||||
s.enqueueMu.RUnlock()
|
||||
return ErrStorageDegraded
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
select {
|
||||
case s.writeChan <- writeRequest{operation: operation, run: fn, barrier: done}:
|
||||
s.enqueueMu.RUnlock()
|
||||
case <-ctx.Done():
|
||||
s.enqueueMu.RUnlock()
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// Flush waits until every write queued before this call has completed. Replay
|
||||
// reads use this barrier to provide read-after-write consistency while normal
|
||||
// gameplay retains the low-latency async write path.
|
||||
|
||||
@@ -837,6 +837,75 @@ func TestClaimsSnapshotPlayerNames(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteAccountClearsClaimsAndNames(t *testing.T) {
|
||||
store := openStore(t, pgtest.DSN(t))
|
||||
now := time.Now().UTC()
|
||||
alice, bob := uuid.NewString(), uuid.NewString()
|
||||
for id, name := range map[string]string{alice: "alice", bob: "bob"} {
|
||||
if err := store.CreateUser(UserRecord{UserID: id, Username: name, PasswordHash: "hash", CreatedAt: now}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := store.CreateSession(SessionRecord{
|
||||
SessionID: uuid.NewString(), UserID: alice, CreatedAt: now, ExpiresAt: now.Add(time.Hour),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Alice against Bob, and Alice alone against the computer.
|
||||
shared, solo := uuid.NewString(), uuid.NewString()
|
||||
for _, record := range []GameRecord{
|
||||
{GameID: shared, InitialFEN: "initial",
|
||||
WhitePlayerID: alice, WhiteType: 1, WhiteClaimedBy: alice,
|
||||
BlackPlayerID: bob, BlackType: 1, BlackClaimedBy: bob, StartTimeUTC: now},
|
||||
{GameID: solo, InitialFEN: "initial",
|
||||
WhitePlayerID: uuid.NewString(), WhiteType: 2,
|
||||
BlackPlayerID: alice, BlackType: 1, BlackClaimedBy: alice, StartTimeUTC: now},
|
||||
} {
|
||||
if err := store.RecordNewGame(record); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := store.DeleteAccount(alice); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.GetUserByID(alice); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("account still present: %v", err)
|
||||
}
|
||||
var sessions int
|
||||
if err := store.db.QueryRow(`SELECT count(*) FROM sessions WHERE user_id = $1`, alice).Scan(&sessions); err != nil || sessions != 0 {
|
||||
t.Fatalf("sessions left: %d, %v", sessions, err)
|
||||
}
|
||||
|
||||
record, _, err := store.GetGameHistory(shared)
|
||||
if err != nil || record.WhiteClaimedBy != "" || record.WhiteName != "" ||
|
||||
record.BlackClaimedBy != bob || record.BlackName != "bob" {
|
||||
t.Fatalf("shared game after deletion: white %q/%q black %q/%q, %v",
|
||||
record.WhiteClaimedBy, record.WhiteName, record.BlackClaimedBy, record.BlackName, err)
|
||||
}
|
||||
// Nobody claims the solo game now, so the inactivity purge takes it.
|
||||
if err := store.DeleteAnonymousGames(now.Add(time.Minute), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Flush(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := store.GetGameHistory(solo); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("solo game survived the anonymous purge: %v", err)
|
||||
}
|
||||
if _, _, err := store.GetGameHistory(shared); err != nil {
|
||||
t.Fatalf("a game another user claims must stay: %v", err)
|
||||
}
|
||||
|
||||
if err := store.DeleteAccount(alice); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("second deletion: %v, want sql.ErrNoRows", err)
|
||||
}
|
||||
if !store.IsHealthy() {
|
||||
t.Fatal("deleting a missing account degraded the writer")
|
||||
}
|
||||
}
|
||||
|
||||
func timePointer(value time.Time) *time.Time {
|
||||
return &value
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -124,6 +125,52 @@ func (s *Store) DeleteUser(userID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteAccount removes an account at its owner's request. Unlike DeleteUser,
|
||||
// which keeps the claim IDs and name snapshots for the record, it first clears
|
||||
// the user's claims and names from every stored game, so nothing in the
|
||||
// database still names the person, and a game nobody else claimed becomes
|
||||
// anonymous and falls to the inactivity purge. Sessions cascade.
|
||||
//
|
||||
// It runs on the ordered game writer, behind every gameplay write already
|
||||
// queued, so a queued claim cannot land on a game after it was cleared. It
|
||||
// returns sql.ErrNoRows when no such user exists.
|
||||
func (s *Store) DeleteAccount(userID string) error {
|
||||
if !validUUID(userID) {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
// Set inside the transaction, read after the writer reports back: the
|
||||
// barrier channel orders the two. A missing row is an answer, not a
|
||||
// failed write, so it must not degrade the writer.
|
||||
var deleted int64
|
||||
// Behind the queue, then its own transaction.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), flushTimeout+writeTimeout)
|
||||
defer cancel()
|
||||
err := s.enqueueWait(ctx, "delete_account", func(ctx context.Context, tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE games SET
|
||||
white_claimed_by = CASE WHEN white_claimed_by = $1 THEN NULL ELSE white_claimed_by END,
|
||||
white_name = CASE WHEN white_claimed_by = $1 THEN NULL ELSE white_name END,
|
||||
black_claimed_by = CASE WHEN black_claimed_by = $1 THEN NULL ELSE black_claimed_by END,
|
||||
black_name = CASE WHEN black_claimed_by = $1 THEN NULL ELSE black_name END
|
||||
WHERE white_claimed_by = $1 OR black_claimed_by = $1`, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, `DELETE FROM users WHERE user_id = $1`, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
deleted, err = result.RowsAffected()
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if deleted == 0 {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
slog.Debug("storage account deleted", "user_id", userID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateUserPassword updates user password hash
|
||||
func (s *Store) UpdateUserPassword(userID, passwordHash string) error {
|
||||
return s.execUserUpdate(`UPDATE users SET password_hash = $2 WHERE user_id = $1`,
|
||||
|
||||
@@ -17,6 +17,7 @@ let gameState = {
|
||||
username: null,
|
||||
authBusy: false,
|
||||
newGameBusy: false,
|
||||
accountBusy: false, // logout or account deletion in flight
|
||||
termination: '',
|
||||
actionBusy: false, // a draw or resign request is in flight
|
||||
};
|
||||
@@ -85,6 +86,9 @@ document.getElementById('login-submit-btn').addEventListener('click', handleLogi
|
||||
document.getElementById('register-submit-btn').addEventListener('click', handleRegister);
|
||||
document.getElementById('auth-cancel-btn').addEventListener('click', hideAuthModal);
|
||||
document.getElementById('auth-cancel-btn-2').addEventListener('click', hideAuthModal);
|
||||
document.getElementById('logout-btn').addEventListener('click', handleLogoutClick);
|
||||
document.getElementById('account-cancel-btn').addEventListener('click', hideAccountModal);
|
||||
document.getElementById('delete-account-btn').addEventListener('click', deleteAccount);
|
||||
document.querySelectorAll('.promotion-choice').forEach(btn => {
|
||||
btn.addEventListener('click', () => closePromotion(btn.dataset.piece));
|
||||
});
|
||||
@@ -143,15 +147,113 @@ function updateAuthIndicator(authenticated) {
|
||||
|
||||
function handleAuthClick() {
|
||||
if (gameState.authToken) {
|
||||
// Logged in - confirm logout
|
||||
if (confirm(`Logout ${gameState.username}?`)) {
|
||||
handleLogout();
|
||||
}
|
||||
showAccountModal();
|
||||
} else {
|
||||
showAuthModal();
|
||||
}
|
||||
}
|
||||
|
||||
// Account dialog, for a signed-in user: log out, or delete the account. It
|
||||
// replaces a native confirm(), which a sandboxed embed may not be allowed.
|
||||
function showAccountModal() {
|
||||
document.getElementById('account-username').textContent = gameState.username || '';
|
||||
document.getElementById('delete-account').open = false;
|
||||
document.getElementById('delete-password').value = '';
|
||||
clearModalMessage('account-modal-message');
|
||||
document.getElementById('account-overlay').classList.add('show');
|
||||
document.removeEventListener('keydown', handleAccountKeydown);
|
||||
document.addEventListener('keydown', handleAccountKeydown);
|
||||
document.getElementById('account-cancel-btn').focus();
|
||||
}
|
||||
|
||||
function hideAccountModal() {
|
||||
if (gameState.accountBusy) return;
|
||||
document.getElementById('account-overlay').classList.remove('show');
|
||||
document.getElementById('delete-password').value = '';
|
||||
document.removeEventListener('keydown', handleAccountKeydown);
|
||||
}
|
||||
|
||||
function setAccountBusy(busy) {
|
||||
gameState.accountBusy = busy;
|
||||
for (const id of ['logout-btn', 'account-cancel-btn', 'delete-account-btn', 'delete-password']) {
|
||||
document.getElementById(id).disabled = busy;
|
||||
}
|
||||
}
|
||||
|
||||
function handleAccountKeydown(e) {
|
||||
if (gameState.accountBusy) {
|
||||
if (e.key === 'Enter' || e.key === 'Escape') e.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
hideAccountModal();
|
||||
} else if (e.key === 'Enter' && document.activeElement?.id === 'delete-password') {
|
||||
e.preventDefault();
|
||||
deleteAccount();
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogoutClick() {
|
||||
setAccountBusy(true);
|
||||
await handleLogout();
|
||||
setAccountBusy(false);
|
||||
hideAccountModal();
|
||||
}
|
||||
|
||||
// The server re-checks the password, ends the session, clears the account's
|
||||
// claims and names from its games, then deletes it (DELETE /api/auth/me).
|
||||
async function deleteAccount() {
|
||||
if (gameState.accountBusy) return;
|
||||
const password = document.getElementById('delete-password').value;
|
||||
if (!password) {
|
||||
setModalMessage('account-modal-message', 'Enter your password to delete the account', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setAccountBusy(true);
|
||||
clearModalMessage('account-modal-message');
|
||||
let response;
|
||||
try {
|
||||
response = await authFetch(`${gameState.apiUrl}/api/auth/me`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
} catch {
|
||||
setAccountBusy(false);
|
||||
setModalMessage('account-modal-message', 'Network error: the account was not deleted', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
const name = gameState.username;
|
||||
clearAuthState();
|
||||
setModalMessage('account-modal-message', `Account ${name} deleted`, 'success');
|
||||
setTimeout(() => {
|
||||
setAccountBusy(false);
|
||||
hideAccountModal();
|
||||
}, MODAL_SUCCESS_DISPLAY_MS * 2);
|
||||
return;
|
||||
}
|
||||
|
||||
setAccountBusy(false);
|
||||
const data = await parseErrorResponse(response);
|
||||
let message;
|
||||
if (response.status === 401 && data.error === 'invalid credentials') {
|
||||
message = 'Wrong password';
|
||||
} else if (response.status === 401) {
|
||||
// The token itself was refused: the session is already gone.
|
||||
clearAuthState();
|
||||
message = 'Your session has ended. Log in again to delete the account.';
|
||||
} else if (response.status === 429) {
|
||||
message = 'Too many attempts. Wait a minute and try again.';
|
||||
} else {
|
||||
message = data.error ? `Not deleted: ${data.error}` : `Server error (${response.status})`;
|
||||
}
|
||||
setModalMessage('account-modal-message', message, 'error');
|
||||
}
|
||||
|
||||
// Disables/enables every interactive control in the auth modal at once, and tracks
|
||||
// whether a login/register request is in flight (or its success message is showing).
|
||||
// Guards re-entrancy from the Enter-key handler, which bypasses individual button
|
||||
|
||||
@@ -117,14 +117,40 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Account Modal: shown instead of the login modal while signed in -->
|
||||
<div id="account-overlay" class="modal-overlay">
|
||||
<div class="modal account-modal" role="dialog" aria-modal="true" aria-labelledby="account-title">
|
||||
<h2 id="account-title">Account</h2>
|
||||
<div id="account-modal-message" class="modal-message" role="status" aria-live="polite"></div>
|
||||
<p class="account-name">Signed in as <strong id="account-username"></strong></p>
|
||||
<div class="modal-buttons">
|
||||
<button id="logout-btn" class="btn btn-primary">Log out</button>
|
||||
<button id="account-cancel-btn" class="btn btn-secondary">Close</button>
|
||||
</div>
|
||||
<details class="danger-zone" id="delete-account">
|
||||
<summary>Delete account</summary>
|
||||
<p>Deletes the account and signs you out. Your name and claim are removed
|
||||
from every stored game; games nobody else plays are deleted 24 hours
|
||||
after their last move. This cannot be undone.</p>
|
||||
<div class="form-group account-form">
|
||||
<label for="delete-password">Password</label>
|
||||
<input type="password" id="delete-password" autocomplete="current-password">
|
||||
</div>
|
||||
<div class="modal-buttons">
|
||||
<button id="delete-account-btn" class="btn btn-danger">Delete account</button>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Overlay Modal -->
|
||||
<div id="modal-overlay" class="modal-overlay">
|
||||
<div class="modal">
|
||||
<h2>New Game</h2>
|
||||
<div id="new-game-modal-message" class="modal-message"></div>
|
||||
<div class="form-group">
|
||||
<label class="group-label">Your Color</label>
|
||||
<div class="radio-group">
|
||||
<div id="new-game-modal-message" class="modal-message" role="status" aria-live="polite"></div>
|
||||
<div class="form-group form-row">
|
||||
<span class="group-label" id="player-color-label">Your Color</span>
|
||||
<div class="radio-group" role="radiogroup" aria-labelledby="player-color-label">
|
||||
<label><input type="radio" name="player-color" value="white" checked><span>White</span></label>
|
||||
<label><input type="radio" name="player-color" value="black"><span>Black</span></label>
|
||||
</div>
|
||||
|
||||
@@ -490,6 +490,16 @@ main {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: var(--tokyo-red);
|
||||
color: var(--host-bg);
|
||||
}
|
||||
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
filter: brightness(1.1);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
@@ -546,7 +556,15 @@ main {
|
||||
}
|
||||
|
||||
.form-group .group-label {
|
||||
text-align: center;
|
||||
color: var(--tokyo-cyan);
|
||||
}
|
||||
|
||||
/* Label and control on one line: the colour choice. */
|
||||
.form-group.form-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.radio-group {
|
||||
@@ -643,7 +661,8 @@ input[type="range"]::-webkit-slider-thumb {
|
||||
|
||||
.auth-form input[type="text"],
|
||||
.auth-form input[type="email"],
|
||||
.auth-form input[type="password"] {
|
||||
.auth-form input[type="password"],
|
||||
.account-form input[type="password"] {
|
||||
width: 100%;
|
||||
padding: 0.5rem;
|
||||
background: var(--host-bg);
|
||||
@@ -653,7 +672,8 @@ input[type="range"]::-webkit-slider-thumb {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.auth-form input:focus {
|
||||
.auth-form input:focus,
|
||||
.account-form input:focus {
|
||||
outline: none;
|
||||
border-color: var(--host-royal);
|
||||
}
|
||||
@@ -679,18 +699,29 @@ input[type="range"]::-webkit-slider-thumb {
|
||||
color: var(--tokyo-green);
|
||||
}
|
||||
|
||||
/* --- Modal status message (Issue 2) --- */
|
||||
/* --- Modal status message ---
|
||||
A reserved slot, not a block that appears: an empty message keeps its height
|
||||
and is only invisible, so a message never moves the form or pushes the
|
||||
buttons out of a short frame (the embedded board on lixen.com is one). Sized
|
||||
for one line; a longer message wraps and grows the slot, which the modal's
|
||||
own scroll absorbs. */
|
||||
.modal-message {
|
||||
display: none;
|
||||
margin-bottom: 1rem;
|
||||
padding: 0.6rem 0.75rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 2.3rem;
|
||||
margin-bottom: 0.75rem;
|
||||
padding: 0.35rem 0.75rem;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 6px;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.3;
|
||||
text-align: center;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.modal-message.show {
|
||||
display: block;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.modal-message.error {
|
||||
@@ -706,7 +737,8 @@ input[type="range"]::-webkit-slider-thumb {
|
||||
}
|
||||
|
||||
/* --- Disabled state while a modal request is in flight (Issue 1) --- */
|
||||
.auth-form input:disabled {
|
||||
.auth-form input:disabled,
|
||||
.account-form input:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
@@ -956,6 +988,37 @@ input[type="range"]:disabled {
|
||||
text-shadow: 1px 1px 2px rgba(255,255,255,0.2);
|
||||
}
|
||||
|
||||
/* Account */
|
||||
.account-modal {
|
||||
max-width: 360px;
|
||||
}
|
||||
|
||||
.account-name {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.danger-zone {
|
||||
margin-top: 1.5rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid var(--tokyo-border);
|
||||
}
|
||||
|
||||
.danger-zone summary {
|
||||
cursor: pointer;
|
||||
color: var(--tokyo-red);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.danger-zone p {
|
||||
margin: 0.75rem 0 1rem;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.danger-zone .modal-buttons {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
/* Resign confirmation */
|
||||
.confirm-modal {
|
||||
max-width: 320px;
|
||||
|
||||
Reference in new issue
Block a user