Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
146 lines (126 loc) · 5.4 KB
/
Copy pathsetup.py
File metadata and controls
146 lines (126 loc) · 5.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import os
import sys
import subprocess
import secrets
def print_header(title):
print("=" * 60)
print(f" {title.center(58)} ")
print("=" * 60)
def check_python_dependencies():
print_header("1. Install Backend Dependencies")
choice = input("Do you want to install Python dependencies from requirements.txt? (y/n): ").strip().lower()
if choice == 'y':
print("Installing packages... This might take a moment.")
try:
subprocess.run([sys.executable, "-m", "pip", "install", "-r", "backend/requirements.txt"], check=True)
print("Successfully installed backend dependencies.")
except subprocess.CalledProcessError as e:
print(f"Failed to install packages: {e}")
sys.exit(1)
else:
print("Skipping package installation.")
def generate_env_file():
print_header("2. Configure Environment settings (.env)")
env_path = ".env"
if os.path.exists(env_path):
print(".env file already exists. Skipping generation.")
return
print("Generating new .env configuration file...")
secret_key = secrets.token_hex(32)
print("\nSelect Database type:")
print("1) SQLite (Local file, recommended for development/testing)")
print("2) MariaDB / MySQL (Production grade)")
db_choice = input("Select database type (1/2) [Default 1]: ").strip()
if db_choice == '2':
db_user = input("MariaDB Username: ").strip()
db_pass = input("MariaDB Password: ").strip()
db_host = input("MariaDB Host [localhost]: ").strip() or "localhost"
db_port = input("MariaDB Port [3306]: ").strip() or "3306"
db_name = input("MariaDB Database Name: ").strip()
db_url = f"mysql+pymysql://{db_user}:{db_pass}@{db_host}:{db_port}/{db_name}"
else:
db_url = "sqlite:///./bms.db"
env_content = f"""# BMS Configuration
SECRET_KEY={secret_key}
DATABASE_URL={db_url}
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60
"""
with open(env_path, "w") as f:
f.write(env_content)
print(f"Successfully generated {env_path} file.")
def initialize_database_and_admin():
print_header("3. Initialize Database & Create Admin Account")
# Load .env variables manually for setup script execution context
from dotenv import load_dotenv
load_dotenv()
# Import SQLAlchemy engine and models to perform creation
try:
from backend.app.core.database import engine, Base, SessionLocal
from backend.app.models import User, UserRole
from backend.app.core.security import get_password_hash
except ImportError as e:
print(f"Could not import required libraries: {e}")
print("Please install requirements first (Step 1).")
return
print("Creating database tables if they do not exist...")
Base.metadata.create_all(bind=engine)
print("Database tables initialized successfully.")
db = SessionLocal()
try:
user_count = db.query(User).count()
if user_count > 0:
print("Users already exist in database. Skipping admin bootstrapping.")
return
print("\nNo users found. Let's register your first administrator account.")
admin_user = input("Choose Admin username [admin]: ").strip() or "admin"
while True:
admin_pass = input("Choose Admin password (min 6 chars): ").strip()
if len(admin_pass) >= 6:
break
print("Password is too short.")
hashed_pwd = get_password_hash(admin_pass)
new_admin = User(
username=admin_user,
hashed_password=hashed_pwd,
role=UserRole.ADMIN.value
)
db.add(new_admin)
db.commit()
print(f"Successfully created administrator user: '{admin_user}' (Role: Admin)")
except Exception as e:
print(f"Failed to setup database / admin user: {e}")
finally:
db.close()
def configure_frontend():
print_header("4. Configure Frontend Dependencies")
choice = input("Do you want to install Node/npm packages inside frontend/? (y/n): ").strip().lower()
if choice == 'y':
print("Checking for Node.js...")
try:
subprocess.run("npm --version", shell=True, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("npm detected. Installing frontend modules (npm install)...")
frontend_dir = os.path.abspath("frontend")
subprocess.run(["npm", "install"], cwd=frontend_dir, shell=True, check=True)
print("Successfully installed frontend dependencies.")
except (subprocess.CalledProcessError, FileNotFoundError):
print("Warning: npm command not found or frontend install failed. Ensure Node.js is installed.")
else:
print("Skipping frontend installation.")
def main():
print("=" * 60)
print(" WELCOME TO THE BACKUP MANAGEMENT SYSTEM (BMS) SETUP ")
print("=" * 60)
check_python_dependencies()
generate_env_file()
initialize_database_and_admin()
configure_frontend()
print_header("Setup Finished Successfully!")
print("To start the backend API server, run:")
print(" py -m uvicorn backend.app.main:app --reload")
print("\nTo start the React frontend web application, run:")
print(" cd frontend")
print(" npm run dev")
print("=" * 60)
if __name__ == "__main__":
main()