Module: Lich::Common::GUI::AccountManager

Defined in:
documented/common/gui/account_manager.rb

Overview

Manages account-related operations for the Lich GUI login system Provides functionality for adding, removing, and modifying accounts and characters

Class Method Summary collapse

Class Method Details

.add_character(data_dir, username, character_data) ⇒ Hash

Adds a character to an account Normalizes account and character names for consistent storage Prevents duplicate characters using normalized comparison Returns detailed result information for user-friendly error messages

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • username (String) —

    Account username

  • character_data (Hash) —

    Character data (char_name, game_code, game_name, frontend, etc.)

Returns:

  • (Hash) —

    Result hash with :success (Boolean) and :message (String) keys Success: { success: true, message: "Character added successfully" } Failure: { success: false, message: "Specific reason for failure" }



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'documented/common/gui/account_manager.rb', line 198

def self.add_character(data_dir, username, character_data)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Check if YAML file exists
  unless File.exist?(yaml_file)
    return { success: false, message: "No account data file found. Please add an account first." }
  end

  begin
    yaml_data = YAML.load_file(yaml_file)

    # Normalize username to UPCASE for consistent lookup
    normalized_username = username.to_s.upcase
    normalized_char_name = character_data[:char_name].to_s.capitalize

    # Check if account exists
    unless yaml_data['accounts'] && yaml_data['accounts'][normalized_username]
      return { success: false, message: "Account '#{username}' not found. Please add the account first." }
    end

    # Initialize characters array if not present
    yaml_data['accounts'][normalized_username]['characters'] ||= []

    # Check for duplicate character using normalized comparison
    # Including custom_launch allows multiple entries for same character with different launch configurations
    existing_character = yaml_data['accounts'][normalized_username]['characters'].find do |char|
      char['char_name'] == normalized_char_name &&
        char['game_code'] == character_data[:game_code] &&
        char['frontend'] == character_data[:frontend] &&
        char['custom_launch'] == character_data[:custom_launch]
    end

    # Return specific message if character already exists
    if existing_character
      return {
        success: false,
        message: "Character '#{normalized_char_name}' already exists for #{character_data[:game_code]} (#{character_data[:frontend]}) with this launch configuration. Duplicates are not allowed."
      }
    end

    # Add character data with normalized character name
    yaml_data['accounts'][normalized_username]['characters'] << {
      'char_name'         => normalized_char_name,
      'game_code'         => character_data[:game_code],
      'game_name'         => character_data[:game_name],
      'frontend'          => character_data[:frontend],
      'custom_launch'     => character_data[:custom_launch],
      'custom_launch_dir' => character_data[:custom_launch_dir]
    }

    # Save updated data with verification
    if write_yaml_with_headers(yaml_file, yaml_data)
      return { success: true, message: "Character '#{normalized_char_name}' added successfully." }
    else
      return { success: false, message: "Failed to save character data. Please check file permissions." }
    end
  rescue StandardError => e
    Lich.log "error: Error adding character: #{e.message}"
    return { success: false, message: "Error adding character: #{e.message}" }
  end
end

.add_or_update_account(data_dir, username, password, characters = []) ⇒ Boolean

Note:

For existing accounts:

  • Password is always updated
  • Characters are merged (existing preserved, new ones added if not duplicates)
  • Existing character metadata (favorites, custom settings) is preserved
  • Duplicate detection uses normalized char_name + game_code + frontend + custom_launch
Note:

For new accounts:

  • Account created with normalized username (UPCASE)
  • Characters added with normalized names (Title case)

Adds or updates an account with password and optional characters Normalizes account and character names for consistent storage When updating existing accounts, merges characters to preserve existing metadata (favorites, etc.)

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • username (String) —

    Account username (will be normalized to UPCASE)

  • password (String) —

    Account password

  • characters (Array<Hash>) (defaults to: []) —

    Optional array of character data hashes (will be normalized to Title case) Character hash format: { char_name:, game_code:, game_name:, frontend:, custom_launch:, custom_launch_dir: }

Returns:

  • (Boolean) —

    True if operation was successful



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'documented/common/gui/account_manager.rb', line 40

def self.(data_dir, username, password, characters = [])
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Normalize username to UPCASE for consistent storage
  normalized_username = username.to_s.upcase

  # Load existing data or create new structure
  yaml_data = if File.exist?(yaml_file)
                begin
                  YAML.load_file(yaml_file)
                rescue StandardError => e
                  Lich.log "error: Error loading YAML entry file: #{e.message}"
                  { 'accounts' => {} }
                end
              else
                { 'accounts' => {} }
              end

  # Initialize accounts hash if not present
  yaml_data['accounts'] ||= {}

  # Determine encryption mode and get master password if needed
  encryption_mode = yaml_data['encryption_mode'] || 'plaintext'
  master_password = nil
  if encryption_mode.to_sym == :enhanced
    master_password = Lich::Common::GUI::MasterPasswordManager.retrieve_master_password
    if master_password.nil?
      Lich.log "error: Enhanced mode enabled but master password not found in Keychain"
      raise StandardError, "Master password required for enhanced mode encryption"
    end
  end

  # Encrypt the password based on encryption mode
  encrypted_password = Lich::Common::Authentication::EntryStore.encrypt_password(
    password,
    mode: encryption_mode,
    account_name: normalized_username,
    master_password: master_password
  )

  # Normalize character data if provided
  normalized_characters = characters.map do |char|
    {
      'char_name'         => char[:char_name].to_s.strip.split.map(&:capitalize).join(' '),
      'game_code'         => char[:game_code],
      'game_name'         => char[:game_name],
      'frontend'          => char[:frontend],
      'custom_launch'     => char[:custom_launch],
      'custom_launch_dir' => char[:custom_launch_dir]
    }
  end

  # Add or update account using normalized username
  if yaml_data['accounts'][normalized_username]
    # Update existing account password with encrypted value
    yaml_data['accounts'][normalized_username]['password'] = encrypted_password

    # Merge characters: preserve existing characters and their metadata (like favorites)
    # while adding any new characters from the provided list
    if !characters.empty?
      existing_characters = yaml_data['accounts'][normalized_username]['characters'] || []

      # Add new characters that don't already exist
      characters.each do |new_char|
        normalized_new_char_name = new_char[:char_name].to_s.capitalize

        # Check if character already exists (by char_name, game_code, frontend, custom_launch)
        # Including custom_launch allows multiple entries for same character with different launch configurations
        existing_char = existing_characters.find do |existing|
          existing['char_name'] == normalized_new_char_name &&
            existing['game_code'] == new_char[:game_code] &&
            existing['frontend'] == new_char[:frontend] &&
            existing['custom_launch'] == new_char[:custom_launch]
        end

        # Only add if character doesn't already exist
        unless existing_char
          existing_characters << {
            'char_name'         => normalized_new_char_name,
            'game_code'         => new_char[:game_code],
            'game_name'         => new_char[:game_name],
            'frontend'          => new_char[:frontend],
            'custom_launch'     => new_char[:custom_launch],
            'custom_launch_dir' => new_char[:custom_launch_dir]
          }
        end
      end

      yaml_data['accounts'][normalized_username]['characters'] = existing_characters
    end
  else
    # Create new account with normalized data and encrypted password
    yaml_data['accounts'][normalized_username] = {
      'password'   => encrypted_password,
      'characters' => normalized_characters
    }
  end

  # Save updated data with verification
  write_yaml_with_headers(yaml_file, yaml_data)
end

.change_password(data_dir, username, new_password) ⇒ Boolean

Changes the password for an account Updates the password for the specified account using normalized account name

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • username (String) —

    Account username

  • new_password (String) —

    New password for the account

Returns:

  • (Boolean) —

    True if operation was successful



181
182
183
184
185
# File 'documented/common/gui/account_manager.rb', line 181

def self.change_password(data_dir, username, new_password)
  # Normalize username to UPCASE for consistent storage
  normalized_username = username.to_s.upcase
  (data_dir, normalized_username, new_password)
end

.convert_auth_data_to_characters(auth_data, frontend = 'stormfront') ⇒ Array

Converts authentication response data to character format for storage Validates and filters character data, transforming from authentication response format (symbol keys) to storage format (symbol keys with validation)

Parameters:

  • auth_data (Array) —

    Array of character hashes from authentication

  • frontend (String) (defaults to: 'stormfront') —

    Selected frontend for all characters

Returns:

  • (Array) —

    Array of character data hashes formatted for storage



403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'documented/common/gui/account_manager.rb', line 403

def self.convert_auth_data_to_characters(auth_data, frontend = 'stormfront')
  characters = []
  return characters unless auth_data.is_a?(Array)

  auth_data.each do |char_data|
    # Ensure we have the required fields with symbol keys (as returned by authentication)
    next unless char_data.is_a?(Hash) &&
                char_data.key?(:char_name) &&
                char_data.key?(:game_name) &&
                char_data.key?(:game_code)

    characters << {
      char_name: char_data[:char_name],
      game_code: char_data[:game_code],
      game_name: char_data[:game_name],
      frontend: frontend
    }
  end

  characters
end

.get_accounts(data_dir) ⇒ Array

Gets all accounts

Parameters:

  • data_dir (String) —

    Directory containing entry data

Returns:

  • (Array) —

    Array of account usernames



429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'documented/common/gui/account_manager.rb', line 429

def self.get_accounts(data_dir)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Load existing data
  return [] unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)
    yaml_data['accounts']&.keys || []
  rescue StandardError => e
    Lich.log "error: Error getting accounts: #{e.message}"
    []
  end
end

.get_all_accounts(data_dir) ⇒ Hash

Gets all accounts with their characters This method is used by AccountManagerUI.populate_accounts_view

Parameters:

  • data_dir (String) —

    Directory containing entry data

Returns:

  • (Hash) —

    Hash of accounts with their characters



449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'documented/common/gui/account_manager.rb', line 449

def self.get_all_accounts(data_dir)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Load existing data
  return {} unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)
    return {} unless yaml_data['accounts']

    # Build accounts hash with characters
    accounts = {}
    yaml_data['accounts'].each do |username, |
      accounts[username] = ['characters']&.map do |char|
        {
          char_name: char['char_name'],
          game_code: char['game_code'],
          game_name: char['game_name'],
          frontend: char['frontend'],
          custom_launch: char['custom_launch'],
          custom_launch_dir: char['custom_launch_dir']
        }
      end || []
    end

    accounts
  rescue StandardError => e
    Lich.log "error: Error getting all accounts: #{e.message}"
    {}
  end
end

.get_characters(data_dir, username) ⇒ Array

Gets all characters for an account

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • username (String) —

    Account username

Returns:

  • (Array) —

    Array of character data hashes



486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'documented/common/gui/account_manager.rb', line 486

def self.get_characters(data_dir, username)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Load existing data
  return [] unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)

    # Normalize username to UPCASE for consistent lookup
    normalized_username = username.to_s.upcase

    # Check if account exists
    return [] unless yaml_data['accounts'] &&
                     yaml_data['accounts'][normalized_username] &&
                     yaml_data['accounts'][normalized_username]['characters']

    # Return characters with symbolized keys
    yaml_data['accounts'][normalized_username]['characters'].map do |char|
      char.transform_keys(&:to_sym)
    end
  rescue StandardError => e
    Lich.log "error: Error getting characters: #{e.message}"
    []
  end
end

.remove_account(data_dir, username) ⇒ Boolean

Removes an account and all associated characters Uses normalized account name for consistent lookup

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • username (String) —

    Account username to remove

Returns:

  • (Boolean) —

    True if operation was successful



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'documented/common/gui/account_manager.rb', line 148

def self.(data_dir, username)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Load existing data
  return false unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)

    # Normalize username to UPCASE for consistent lookup
    normalized_username = username.to_s.upcase

    # Check if account exists
    return false unless yaml_data['accounts'] && yaml_data['accounts'][normalized_username]

    # Remove account
    yaml_data['accounts'].delete(normalized_username)

    # Save updated data with verification
    write_yaml_with_headers(yaml_file, yaml_data)
  rescue StandardError => e
    Lich.log "error: Error removing account: #{e.message}"
    false
  end
end

.remove_character(data_dir, username, char_name, game_code, frontend = nil, custom_launch = :__unset) ⇒ Boolean

Removes a character from an account with frontend precision Uses normalized account and character names for consistent lookup

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • username (String) —

    Account username

  • char_name (String) —

    Character name

  • game_code (String) —

    Game code

  • frontend (String) (defaults to: nil) —

    Frontend identifier (optional for backward compatibility)

  • custom_launch (String, nil, Symbol) (defaults to: :__unset) —

    Exact custom launch command, or :__unset for legacy matching

Returns:

  • (Boolean) —

    True if operation was successful



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'documented/common/gui/account_manager.rb', line 270

def self.remove_character(data_dir, username, char_name, game_code, frontend = nil, custom_launch = :__unset)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Load existing data
  return false unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)

    # Normalize username and character name for consistent lookup
    normalized_username = username.to_s.upcase
    normalized_char_name = char_name.to_s.capitalize

    # Check if account exists
    return false unless yaml_data['accounts'] &&
                        yaml_data['accounts'][normalized_username] &&
                        yaml_data['accounts'][normalized_username]['characters']

    # Find and remove character with frontend precision
    characters = yaml_data['accounts'][normalized_username]['characters']
    initial_count = characters.size

    characters.reject! do |char|
      matches_basic = char['char_name'] == normalized_char_name && char['game_code'] == game_code
      matches_custom_launch = custom_launch == :__unset ||
                              char['custom_launch'].to_s.strip == custom_launch.to_s.strip

      if frontend.nil?
        # Backward compatibility: if no frontend specified, match any frontend
        matches_basic && matches_custom_launch
      else
        # Frontend precision: must match exact frontend
        matches_basic && char['frontend'] == frontend && matches_custom_launch
      end
    end

    # Check if any characters were removed
    return false if characters.size == initial_count

    # Save updated data with verification
    write_yaml_with_headers(yaml_file, yaml_data)
  rescue StandardError => e
    Lich.log "error: Error removing character: #{e.message}"
    false
  end
end

.to_legacy_format(data_dir) ⇒ Array

Converts the YAML data to legacy format for compatibility

Parameters:

  • data_dir (String) —

    Directory containing entry data

Returns:

  • (Array) —

    Array of entry data in legacy format



517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'documented/common/gui/account_manager.rb', line 517

def self.to_legacy_format(data_dir)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Load existing data
  return [] unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)
    Lich::Common::Authentication::EntryStore.convert_yaml_to_legacy_format(yaml_data)
  rescue StandardError => e
    Lich.log "error: Error converting to legacy format: #{e.message}"
    []
  end
end

.update_character(data_dir, username, char_name, game_code, updates) ⇒ Boolean

Updates a character's properties

Parameters:

  • data_dir (String) —

    Directory containing entry data

  • username (String) —

    Account username

  • char_name (String) —

    Character name

  • game_code (String) —

    Game code

  • updates (Hash) —

    Properties to update

Returns:

  • (Boolean) —

    True if operation was successful



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'documented/common/gui/account_manager.rb', line 325

def self.update_character(data_dir, username, char_name, game_code, updates)
  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)

  # Load existing data
  return false unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)

    # Check if account exists
    return false unless yaml_data['accounts'] &&
                        yaml_data['accounts'][username] &&
                        yaml_data['accounts'][username]['characters']

    # Find and update character
    characters = yaml_data['accounts'][username]['characters']
    character = characters.find { |char| char['char_name'] == char_name && char['game_code'] == game_code }

    return false unless character

    # Update properties
    updates.each do |key, value|
      character[key.to_s] = value
    end

    # Save updated data with verification
    write_yaml_with_headers(yaml_file, yaml_data)
  rescue StandardError => e
    Lich.log "error: Error updating character: #{e.message}"
    false
  end
end

.update_launch_settings(data_dir, username, char_name, game_code, old_frontend:, custom_launch:, frontend: old_frontend) ⇒ Boolean

Reassigns exactly one saved entry without changing account credentials, favorites or per-entry custom launch settings. Rejects stale selections and duplicate destinations rather than editing a different entry.

Parameters:

  • data_dir (String) —

    saved entry directory

  • username (String) —

    account name

  • char_name (String) —

    character name

  • game_code (String) —

    game instance

  • old_frontend (String) —

    frontend of the selected entry

  • custom_launch (String, nil) —

    exact selected custom command

  • frontend (String) (defaults to: old_frontend) —

    new configured frontend identifier

Returns:

  • (Boolean) —

    whether the change was saved



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'documented/common/gui/account_manager.rb', line 370

def self.update_launch_settings(data_dir, username, char_name, game_code, old_frontend:, custom_launch:, frontend: old_frontend)
  definition = Frontend.definition_for(frontend)
  return false if definition.dig(:metadata, :native_launch_only) && !custom_launch.to_s.strip.empty?

  yaml_file = Lich::Common::Authentication::EntryStore.yaml_file_path(data_dir)
  return false unless File.exist?(yaml_file)

  yaml_data = YAML.load_file(yaml_file)
   = yaml_data.fetch('accounts', {}).find { |name, _| name.casecmp?(username) }&.last
  candidates = &.fetch('characters', [])&.select do |character|
    character['char_name'] == char_name && character['game_code'] == game_code &&
      character['custom_launch'] == custom_launch
  end || []
  selected = candidates.select { |character| character['frontend'] == old_frontend }
  return false unless selected.one?

  character = selected.first
  return false if candidates.any? { |other| !other.equal?(character) && Frontend.canonical_name(other['frontend']) == definition[:id] }

  character['frontend'] = definition[:id]
  write_yaml_with_headers(yaml_file, yaml_data)
rescue StandardError => e
  Lich.log "error: Could not change saved frontend: #{e.class}"
  false
end