-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.py
More file actions
142 lines (118 loc) · 4.51 KB
/
setup.py
File metadata and controls
142 lines (118 loc) · 4.51 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
import os
import sys
import subprocess
import platform
import time
import random
import string
import getpass
from dotenv import load_dotenv
def generate_secret_key(length=32):
"""Generate a random secret key"""
chars = string.ascii_letters + string.digits + '!@#$%^&*()_-+=<>?'
return ''.join(random.choice(chars) for _ in range(length))
def create_env_file():
"""Create .env file if it doesn't exist"""
if os.path.exists('.env'):
print("INFO: .env file already exists. Skipping creation.")
return
try:
secret_key = generate_secret_key()
jwt_secret = generate_secret_key()
with open('.env', 'w') as f:
f.write(f"SECRET_KEY={secret_key}\n")
f.write(f"JWT_SECRET_KEY={jwt_secret}\n")
f.write("DATABASE_URL=postgresql://postgres:postgres@localhost:5432/sas_db\n")
f.write("FLASK_ENV=development\n")
print("SUCCESS: .env file created with random secret keys.")
except Exception as e:
print(f"ERROR: Failed to create .env file: {e}")
def check_postgresql():
"""Check if PostgreSQL is running"""
print("Checking PostgreSQL connection...")
# Import here to avoid requiring it before it's installed
try:
import psycopg2
conn = psycopg2.connect(
host="localhost",
port="5432",
user="postgres",
password="postgres",
database="postgres"
)
conn.close()
print("SUCCESS: PostgreSQL is running and accessible.")
return True
except Exception as e:
print(f"WARNING: PostgreSQL connection failed: {e}")
print("You need to start your PostgreSQL portable server before proceeding.")
print("Once PostgreSQL is running, run 'python init_db.py' to create the database.")
return False
def install_dependencies():
"""Install Python dependencies"""
print("Installing Python dependencies...")
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
print("SUCCESS: Dependencies installed successfully.")
except Exception as e:
print(f"ERROR: Failed to install dependencies: {e}")
return False
return True
def create_admin_user():
"""Create admin user interactively"""
print("\nCreating admin user...")
# Get admin username
username = input("Admin username (default: admin): ").strip() or "admin"
# Get admin email
email = input("Admin email (default: admin@example.com): ").strip() or "admin@example.com"
# Get admin password
password = getpass.getpass("Admin password (min 8 chars, must include uppercase, lowercase, number, and special character): ")
if not password:
password = "Admin123!"
print("Using default password: Admin123!")
print("WARNING: Please change this password immediately after setup!")
# Create admin user
try:
subprocess.check_call([sys.executable, "create_admin.py", username, email, password])
print("SUCCESS: Admin user created.")
return True
except Exception as e:
print(f"ERROR: Failed to create admin user: {e}")
return False
def main():
"""Main setup function"""
print("="*50)
print("Secure Authentication System (SAS) Setup")
print("="*50)
# Create .env file
create_env_file()
# Install dependencies
if not install_dependencies():
return 1
# Check PostgreSQL
if not check_postgresql():
print("\nImportant: You need to start PostgreSQL before initializing the database.")
print("Once PostgreSQL is running, run the following commands:")
print("\n1. python init_db.py")
print("2. python create_admin.py <username> <email> <password>")
print("3. python app.py\n")
return 0
# Initialize database
print("\nInitializing database...")
try:
subprocess.check_call([sys.executable, "init_db.py"])
except Exception as e:
print(f"ERROR: Failed to initialize database: {e}")
return 1
# Ask if user wants to create admin user
create_admin = input("\nWould you like to create an admin user? (y/n): ").lower().strip() == 'y'
if create_admin:
create_admin_user()
print("\n" + "="*50)
print("Setup completed successfully!")
print("="*50)
print("\nTo start the application, run:")
print("python app.py")
return 0
if __name__ == "__main__":
sys.exit(main())