AccountManager.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. namespace GFGGame
  6. {
  7. public sealed class AccountManager
  8. {
  9. private const string SAVE_KEY = "RecentAccountsData";
  10. private const int MAX_ACCOUNT_COUNT = 20;
  11. private List<AccountData> _cachedAccounts = new List<AccountData>();
  12. // 单例实例
  13. private static readonly Lazy<AccountManager> _instance = new Lazy<AccountManager>(() => new AccountManager());
  14. public static AccountManager Instance => _instance.Value;
  15. // 私有构造函数,防止外部实例化
  16. private AccountManager()
  17. {
  18. LoadAccounts();
  19. }
  20. /// <summary>
  21. /// 登录成功时调用此方法
  22. /// </summary>
  23. /// <param name="username">用户名</param>
  24. /// <param name="plainPassword">明文密码</param>
  25. public void SaveAccount(string username, string plainPassword)
  26. {
  27. // 1. 加密密码
  28. string encryptedPwd = null;
  29. if (plainPassword != null)
  30. {
  31. encryptedPwd = AesEncryption.Encrypt(plainPassword);
  32. }
  33. // 2. 检查列表中是否已有该账号
  34. AccountData existingAccount = _cachedAccounts.FirstOrDefault(a => a.username == username);
  35. if (existingAccount != null)
  36. {
  37. // 如果存在,更新密码和时间戳,并移到列表最前面(表示最新)
  38. existingAccount.encryptedPassword = encryptedPwd;
  39. existingAccount.timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
  40. _cachedAccounts.Remove(existingAccount);
  41. _cachedAccounts.Insert(0, existingAccount);
  42. }
  43. else
  44. {
  45. // 如果不存在,创建新账号数据并添加到最前面
  46. AccountData newAccount = new AccountData(username, encryptedPwd);
  47. _cachedAccounts.Insert(0, newAccount);
  48. }
  49. // 3. 如果超出最大数量,移除最旧的一个(列表最后一个)
  50. if (_cachedAccounts.Count > MAX_ACCOUNT_COUNT)
  51. {
  52. _cachedAccounts.RemoveAt(_cachedAccounts.Count - 1);
  53. }
  54. // 4. 立即保存
  55. SaveAccounts();
  56. }
  57. /// <summary>
  58. /// 获取存储的所有账号信息(密码已解密)
  59. /// </summary>
  60. public List<AccountPasswordModel> GetAccounts()
  61. {
  62. List<AccountPasswordModel> result = new List<AccountPasswordModel>();
  63. foreach (var acc in _cachedAccounts)
  64. {
  65. string decryptedPwd = null;
  66. if (acc.encryptedPassword != null)
  67. {
  68. decryptedPwd = AesEncryption.Decrypt(acc.encryptedPassword);
  69. }
  70. AccountPasswordModel accountPasswordModel = new AccountPasswordModel()
  71. {
  72. Account = acc.username,
  73. Password = decryptedPwd
  74. };
  75. result.Add(accountPasswordModel);
  76. }
  77. return result;
  78. }
  79. /// <summary>
  80. /// 删除指定的账号缓存
  81. /// </summary>
  82. /// <param name="username">要删除的用户名</param>
  83. /// <returns>是否成功删除</returns>
  84. public bool DeleteAccount(string username)
  85. {
  86. // 查找要删除的账号
  87. AccountData accountToDelete = _cachedAccounts.FirstOrDefault(a => a.username == username);
  88. if (accountToDelete != null)
  89. {
  90. // 从缓存列表中移除
  91. _cachedAccounts.Remove(accountToDelete);
  92. // 立即保存
  93. SaveAccounts();
  94. Debug.Log($"已成功删除账号: {username}");
  95. return true;
  96. }
  97. else
  98. {
  99. Debug.LogWarning($"未找到账号: {username},删除失败");
  100. return false;
  101. }
  102. }
  103. /// <summary>
  104. /// 批量删除多个账号缓存
  105. /// </summary>
  106. /// <param name="usernames">要删除的用户名列表</param>
  107. /// <returns>成功删除的数量</returns>
  108. public int DeleteAccounts(List<string> usernames)
  109. {
  110. int deletedCount = 0;
  111. foreach (string username in usernames)
  112. {
  113. if (DeleteAccount(username))
  114. {
  115. deletedCount++;
  116. }
  117. }
  118. Debug.Log($"成功删除了 {deletedCount} 个账号");
  119. return deletedCount;
  120. }
  121. /// <summary>
  122. /// 清除所有账号记录
  123. /// </summary>
  124. public void ClearAllAccounts()
  125. {
  126. _cachedAccounts.Clear();
  127. PlayerPrefs.DeleteKey(SAVE_KEY);
  128. PlayerPrefs.Save();
  129. Debug.Log("已清除所有账号记录");
  130. }
  131. /// <summary>
  132. /// 检查指定账号是否存在
  133. /// </summary>
  134. public bool HasAccount(string username)
  135. {
  136. return _cachedAccounts.Any(a => a.username == username);
  137. }
  138. /// <summary>
  139. /// 获取缓存的账号数量
  140. /// </summary>
  141. public int GetAccountCount()
  142. {
  143. return _cachedAccounts.Count;
  144. }
  145. // 内部方法:从PlayerPrefs加载账号列表
  146. private void LoadAccounts()
  147. {
  148. _cachedAccounts.Clear();
  149. string encryptedJson = PlayerPrefs.GetString(SAVE_KEY, null);
  150. if (!string.IsNullOrEmpty(encryptedJson))
  151. {
  152. string decryptedJson = AesEncryption.Decrypt(encryptedJson);
  153. if (!string.IsNullOrEmpty(decryptedJson))
  154. {
  155. try
  156. {
  157. // 反序列化JSON字符串到对象
  158. AccountDataList loadedData = JsonUtility.FromJson<AccountDataList>(decryptedJson);
  159. if (loadedData != null && loadedData.accounts != null)
  160. {
  161. // 按时间戳降序排序,最新的在最前面
  162. _cachedAccounts = loadedData.accounts
  163. .OrderByDescending(a => a.timestamp)
  164. .ToList();
  165. }
  166. }
  167. catch (Exception e)
  168. {
  169. Debug.LogError("Failed to parse account data: " + e.Message);
  170. }
  171. }
  172. }
  173. }
  174. // 内部方法:保存账号列表到PlayerPrefs
  175. private void SaveAccounts()
  176. {
  177. // 包装列表
  178. AccountDataList dataToSave = new AccountDataList();
  179. dataToSave.accounts = _cachedAccounts;
  180. // 序列化为JSON
  181. string json = JsonUtility.ToJson(dataToSave);
  182. // 加密JSON字符串
  183. string encryptedJson = AesEncryption.Encrypt(json);
  184. // 保存到PlayerPrefs
  185. PlayerPrefs.SetString(SAVE_KEY, encryptedJson);
  186. PlayerPrefs.Save(); // 确保立即写入磁盘
  187. }
  188. }
  189. public class AccountPasswordModel
  190. {
  191. public string Account { get; set; }
  192. public string Password { get; set; }
  193. }
  194. }