reset_user_password.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """
  2. 普通用户密码重置脚本
  3. 用法:
  4. python scripts/reset_user_password.py <email_or_username> <new_password>
  5. 示例:
  6. python scripts/reset_user_password.py user@example.com newpass123
  7. python scripts/reset_user_password.py myusername newpass123
  8. """
  9. import os
  10. import sys
  11. from pathlib import Path
  12. from dotenv import load_dotenv
  13. import psycopg2
  14. from passlib.context import CryptContext
  15. # 添加项目根目录到路径
  16. sys.path.insert(0, str(Path(__file__).parent.parent))
  17. # 加载环境变量
  18. env_path = Path(__file__).parent.parent / '.env'
  19. load_dotenv(dotenv_path=env_path)
  20. # 普通用户:直接 bcrypt,不做 sha256
  21. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  22. def get_db_connection():
  23. try:
  24. conn = psycopg2.connect(
  25. host=os.getenv("DB_HOST", "localhost"),
  26. port=int(os.getenv("DB_PORT", "5432")),
  27. database=os.getenv("DB_NAME", "aigcspace"),
  28. user=os.getenv("DB_USER", "postgres"),
  29. password=os.getenv("DB_PASSWORD", "")
  30. )
  31. return conn
  32. except Exception as e:
  33. print(f"❌ 数据库连接失败: {e}")
  34. sys.exit(1)
  35. def reset_password(identifier: str, new_password: str):
  36. conn = get_db_connection()
  37. cur = conn.cursor()
  38. # 先查用户(支持用户名、手机号或邮箱)
  39. cur.execute(
  40. "SELECT id, username, email, phone FROM aigcspace.users WHERE username = %s OR phone = %s OR email = %s",
  41. (identifier, identifier, identifier)
  42. )
  43. row = cur.fetchone()
  44. if not row:
  45. print(f"❌ 未找到用户: {identifier}")
  46. cur.close()
  47. conn.close()
  48. sys.exit(1)
  49. user_id, username, email, phone = row
  50. print(f"找到用户: id={user_id}, username={username}, email={email}, phone={phone}")
  51. # 生成新密码哈希,确保密码是字符串类型
  52. new_hash = pwd_context.hash(str(new_password))
  53. cur.execute(
  54. "UPDATE aigcspace.users SET password_hash = %s WHERE id = %s",
  55. (new_hash, user_id)
  56. )
  57. conn.commit()
  58. print(f"✓ 密码已更新")
  59. cur.close()
  60. conn.close()
  61. if __name__ == "__main__":
  62. if len(sys.argv) != 3:
  63. print("用法: python scripts/reset_user_password.py <email_or_username> <new_password>")
  64. sys.exit(1)
  65. identifier = sys.argv[1]
  66. new_password = sys.argv[2]
  67. reset_password(identifier, new_password)