1
0

setup_db.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import pymysql
  2. import getpass
  3. import os
  4. def run_db_setup():
  5. """
  6. This Python script prompts for passwords securely and executes CREATE USER / GRANT
  7. statements to provision the MySQL server dynamically without config files.
  8. """
  9. print("Welcome to Local Food AI Initial Setup.")
  10. print("WARNING: This will configure your MySQL server. You must know the MySQL root password.\n")
  11. # Automatically fetch passwords for secure CI/CD deployment or fallback for exam/local setup
  12. root_password = os.environ.get("MYSQL_ROOT_PASSWORD", "")
  13. owner_pass = os.environ.get("DB_OWNER_PASS", "BTSai123")
  14. reader_pass = os.environ.get("DB_READER_PASS", "BTSai123")
  15. loader_pass = os.environ.get("DB_LOADER_PASS", "BTSai123")
  16. app_auth_pass = os.environ.get("DB_AUTH_PASS", "BTSai123")
  17. print("\nConnecting as root to configure server...")
  18. try:
  19. # Connect using the local unix socket which allows seamless auth_socket root login on Ubuntu
  20. conn = pymysql.connect(
  21. unix_socket='/var/run/mysqld/mysqld.sock',
  22. user='root',
  23. password=root_password,
  24. autocommit=True
  25. )
  26. cursor = conn.cursor()
  27. except Exception as e:
  28. print(f"Failed to connect: {e}")
  29. return
  30. queries = [
  31. "CREATE DATABASE IF NOT EXISTS food_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;",
  32. # Owner User
  33. f"CREATE USER IF NOT EXISTS 'db_owner'@'%' IDENTIFIED BY '{owner_pass}';",
  34. "GRANT ALL PRIVILEGES ON food_db.* TO 'db_owner'@'%' WITH GRANT OPTION;",
  35. # Reader User
  36. f"CREATE USER IF NOT EXISTS 'db_reader'@'%' IDENTIFIED BY '{reader_pass}';",
  37. "GRANT USAGE ON *.* TO 'db_reader'@'%';",
  38. # Loader User
  39. f"CREATE USER IF NOT EXISTS 'db_loader'@'%' IDENTIFIED BY '{loader_pass}';",
  40. "GRANT USAGE ON *.* TO 'db_loader'@'%';",
  41. "GRANT FILE ON *.* TO 'db_loader'@'%';",
  42. # App Auth User (PoLP)
  43. f"CREATE USER IF NOT EXISTS 'db_app_auth'@'%' IDENTIFIED BY '{app_auth_pass}';",
  44. "GRANT USAGE ON *.* TO 'db_app_auth'@'%';",
  45. "FLUSH PRIVILEGES;"
  46. ]
  47. for q in queries:
  48. print(f"Executing: {q[:60]}...")
  49. cursor.execute(q)
  50. # Now create the table logic safely
  51. print("\nCreating Tables and Granting Table-Specific Access...")
  52. # 1. Users Table
  53. cursor.execute("""
  54. CREATE TABLE IF NOT EXISTS food_db.users (
  55. id INT AUTO_INCREMENT PRIMARY KEY,
  56. username VARCHAR(100) UNIQUE NOT NULL,
  57. password_hash VARCHAR(255) NOT NULL,
  58. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  59. ) ENGINE=InnoDB;
  60. """)
  61. # 2. Plates Table (For storing custom combos)
  62. cursor.execute("""
  63. CREATE TABLE IF NOT EXISTS food_db.plates (
  64. id INT AUTO_INCREMENT PRIMARY KEY,
  65. user_id INT NOT NULL,
  66. plate_name VARCHAR(255) NOT NULL,
  67. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  68. FOREIGN KEY (user_id) REFERENCES food_db.users(id) ON DELETE CASCADE
  69. ) ENGINE=InnoDB;
  70. """)
  71. # 3. Plate Items Table (Linking products to a plate natively)
  72. cursor.execute("""
  73. CREATE TABLE IF NOT EXISTS food_db.plate_items (
  74. id INT AUTO_INCREMENT PRIMARY KEY,
  75. plate_id INT NOT NULL,
  76. product_code VARCHAR(50) NOT NULL,
  77. quantity_grams DOUBLE NOT NULL,
  78. FOREIGN KEY (plate_id) REFERENCES food_db.plates(id) ON DELETE CASCADE
  79. ) ENGINE=InnoDB;
  80. """)
  81. # 4. Products Table (Dynamic Drop for Pandas logic)
  82. cursor.execute("DROP TABLE IF EXISTS food_db.products;")
  83. # Table Context Grants (PoLP)
  84. # The authenticated app process can handle credentials and now read/write custom plates!
  85. cursor.execute("GRANT SELECT, INSERT, UPDATE ON food_db.users TO 'db_app_auth'@'%';")
  86. cursor.execute("GRANT SELECT, INSERT, UPDATE, DELETE ON food_db.plates TO 'db_app_auth'@'%';")
  87. cursor.execute("GRANT SELECT, INSERT, UPDATE, DELETE ON food_db.plate_items TO 'db_app_auth'@'%';")
  88. cursor.execute("GRANT SELECT ON food_db.* TO 'db_reader'@'%';")
  89. cursor.execute("GRANT SELECT, INSERT, UPDATE, DELETE, DROP, CREATE, ALTER, INDEX ON food_db.* TO 'db_loader'@'%';")
  90. cursor.execute("FLUSH PRIVILEGES;")
  91. print("\n✅ Database, Users, and Tables created successfully!")
  92. cursor.close()
  93. conn.close()
  94. print("\n🎉 Setup Complete.")
  95. print("\n!!! IMPORTANT NEXT STEPS !!!")
  96. print("Now, use `mysql_config_editor` to store these passwords locally so the app can use them:")
  97. print(" mysql_config_editor set --login-path=app_reader --host=127.0.0.1 --user=db_reader --password")
  98. print(" mysql_config_editor set --login-path=app_auth --host=127.0.0.1 --user=db_app_auth --password")
  99. if __name__ == "__main__":
  100. run_db_setup()