AccountManager.cs 7.3 KB

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