create_admin_users_table.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #!/usr/bin/env python3
  2. """
  3. Migration script to create the admin_users table and default admin user.
  4. This creates the authentication system for admin users.
  5. """
  6. import os
  7. import sys
  8. # Add parent directory to path
  9. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  10. import bcrypt
  11. from sqlalchemy import inspect
  12. from database.database import AdminUser, get_engine, get_session
  13. def hash_password(password: str) -> tuple[str, str]:
  14. """Hash a password with bcrypt and return (hash, salt)."""
  15. # Generate salt and hash
  16. salt = bcrypt.gensalt()
  17. password_hash = bcrypt.hashpw(password.encode("utf-8"), salt)
  18. return password_hash.decode("utf-8"), salt.decode("utf-8")
  19. def main():
  20. """Create admin_users table and default admin user."""
  21. print("=" * 60)
  22. print("ADMIN USERS TABLE MIGRATION")
  23. print("=" * 60)
  24. engine = get_engine()
  25. session = get_session()
  26. try:
  27. inspector = inspect(engine)
  28. # Check if table already exists
  29. if "admin_users" in inspector.get_table_names():
  30. print("✓ Admin users table already exists")
  31. # Check if default admin user exists
  32. existing_admin = (
  33. session.query(AdminUser).filter_by(username="admin").first()
  34. )
  35. if existing_admin:
  36. print("✓ Default admin user already exists")
  37. return
  38. else:
  39. print("Creating default admin user...")
  40. else:
  41. print("Creating admin_users table...")
  42. # Create the table
  43. AdminUser.__table__.create(engine, checkfirst=True)
  44. print("✓ Admin users table created successfully")
  45. # Create default admin user with FIRST_PASSWORD
  46. first_password = os.getenv("FIRST_PASSWORD", "").strip()
  47. if not first_password:
  48. print("✗ FIRST_PASSWORD not set in .env file")
  49. print(
  50. " Please set FIRST_PASSWORD in your .env file and run migration again."
  51. )
  52. print(' Example: FIRST_PASSWORD="your_secure_password"')
  53. return
  54. # Hash the password
  55. password_hash, salt = hash_password(first_password)
  56. admin_user = AdminUser(
  57. username="admin",
  58. password_hash=password_hash,
  59. salt=salt,
  60. role="admin",
  61. is_active=1,
  62. )
  63. session.add(admin_user)
  64. session.commit()
  65. print("✓ Default admin user created successfully")
  66. print(" Username: admin")
  67. print(" Password: Set from FIRST_PASSWORD")
  68. print(" Use change_password.py to update the password after first login")
  69. print("\nTable structure:")
  70. print(" - id: Primary key (auto-increment)")
  71. print(" - username: Unique username (indexed)")
  72. print(" - password_hash: bcrypt hashed password")
  73. print(" - salt: Salt used for password hashing")
  74. print(" - role: User role (default: admin)")
  75. print(" - is_active: Account status (1 = active, 0 = inactive)")
  76. print(" - last_login: Last login timestamp")
  77. print(" - created_at: Account creation timestamp")
  78. print(" - updated_at: Last update timestamp")
  79. except Exception as e:
  80. session.rollback()
  81. print(f"✗ Error during migration: {e}")
  82. raise
  83. finally:
  84. session.close()
  85. if __name__ == "__main__":
  86. main()