cursor_auth_manager.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import sqlite3
  2. import os
  3. class CursorAuthManager:
  4. """Cursor认证信息管理器"""
  5. def __init__(self):
  6. # 判断操作系统
  7. if os.name == "nt": # Windows
  8. self.db_path = os.path.join(
  9. os.getenv("APPDATA"), "Cursor", "User", "globalStorage", "state.vscdb"
  10. )
  11. else: # macOS
  12. self.db_path = os.path.expanduser(
  13. "~/Library/Application Support/Cursor/User/globalStorage/state.vscdb"
  14. )
  15. def update_auth(self, email=None, access_token=None, refresh_token=None):
  16. """
  17. 更新Cursor的认证信息
  18. :param email: 新的邮箱地址
  19. :param access_token: 新的访问令牌
  20. :param refresh_token: 新的刷新令牌
  21. :return: bool 是否成功更新
  22. """
  23. updates = []
  24. # 登录状态
  25. updates.append(("cursorAuth/cachedSignUpType", "Auth_0"))
  26. if email is not None:
  27. updates.append(("cursorAuth/cachedEmail", email))
  28. if access_token is not None:
  29. updates.append(("cursorAuth/accessToken", access_token))
  30. if refresh_token is not None:
  31. updates.append(("cursorAuth/refreshToken", refresh_token))
  32. if not updates:
  33. print("没有提供任何要更新的值")
  34. return False
  35. conn = None
  36. try:
  37. conn = sqlite3.connect(self.db_path)
  38. cursor = conn.cursor()
  39. for key, value in updates:
  40. # 如果没有更新任何行,说明key不存在,执行插入
  41. # 检查 accessToken 是否存在
  42. check_query = f"SELECT COUNT(*) FROM itemTable WHERE key = ?"
  43. cursor.execute(check_query, (key,))
  44. if cursor.fetchone()[0] == 0:
  45. insert_query = "INSERT INTO itemTable (key, value) VALUES (?, ?)"
  46. cursor.execute(insert_query, (key, value))
  47. else:
  48. update_query = "UPDATE itemTable SET value = ? WHERE key = ?"
  49. cursor.execute(update_query, (value, key))
  50. if cursor.rowcount > 0:
  51. print(f"成功更新 {key.split('/')[-1]}")
  52. else:
  53. print(f"未找到 {key.split('/')[-1]} 或值未变化")
  54. conn.commit()
  55. return True
  56. except sqlite3.Error as e:
  57. print("数据库错误:", str(e))
  58. return False
  59. except Exception as e:
  60. print("发生错误:", str(e))
  61. return False
  62. finally:
  63. if conn:
  64. conn.close()