-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings.py
More file actions
212 lines (181 loc) · 7.99 KB
/
settings.py
File metadata and controls
212 lines (181 loc) · 7.99 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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"""Settings, configuration loading, and first-run wizard for MariaDB REST API."""
import configparser
import logging
import os
from logging.handlers import RotatingFileHandler
import mariadb
# Load configuration (if present)
config = configparser.ConfigParser()
config.read("config.ini")
def _db_config_present(cfg: configparser.ConfigParser) -> bool:
"""Check whether DB config is present, or environment variables override it."""
# Environment variables take precedence; if they are set, consider config present
if any(os.getenv(k) for k in ["DB_HOST", "DB_USER", "DB_PASSWORD", "DB_NAME"]):
return True
if not cfg.has_section("database"):
return False
host = cfg.get("database", "host", fallback="").strip()
user = cfg.get("database", "user", fallback="").strip()
password = cfg.get("database", "password", fallback="").strip()
dbname = cfg.get("database", "database", fallback="").strip()
if not host or not user or not dbname:
return False
# Treat obvious placeholders as missing
if "your_password_here" in password or "your_database_name_here" in dbname:
return False
return True
def _run_initial_setup_wizard() -> None:
"""Interactive wizard to configure DB and create required tables + initial admin.
Runs only in interactive (TTY) environments. In non-interactive mode it does nothing.
"""
import sys
from passlib.context import CryptContext
if not sys.stdin.isatty():
# Non-interactive environment (e.g. service / uvicorn) – skip wizard.
return
print("=== MariaDB REST API – First time setup ===")
print("No valid database configuration found in config.ini and no DB_* environment variables set.")
print("This wizard will help you configure the MariaDB connection and create required tables.\n")
host = input("MariaDB host [localhost]: ").strip() or "localhost"
port_input = input("MariaDB port [3306]: ").strip() or "3306"
try:
port = int(port_input)
except ValueError:
port = 3306
user = input("MariaDB user [root]: ").strip() or "root"
password = input("MariaDB password (can be empty): ").strip()
dbname = input("Database name to use/create [mariadb_api]: ").strip() or "mariadb_api"
print("\nConnecting to MariaDB...")
try:
root_conn = mariadb.connect(host=host, port=port, user=user, password=password)
except mariadb.Error as e:
print(f"ERROR: Could not connect to MariaDB with these credentials: {e}")
print("Please edit config.ini or set DB_* environment variables and restart.")
sys.exit(1)
try:
cur = root_conn.cursor()
cur.execute(
f"CREATE DATABASE IF NOT EXISTS `{dbname}` "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
)
root_conn.commit()
except mariadb.Error as e:
print(f"ERROR: Failed to create or verify database '{dbname}': {e}")
sys.exit(1)
finally:
root_conn.close()
print(f"Database '{dbname}' is ready.")
# Connect to created DB and create tables
try:
conn = mariadb.connect(host=host, port=port, user=user, password=password, database=dbname)
except mariadb.Error as e:
print(f"ERROR: Could not connect to database '{dbname}': {e}")
sys.exit(1)
try:
cur = conn.cursor()
# users table
cur.execute(
"""CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
role VARCHAR(20) NOT NULL
)"""
)
# audit_log table
cur.execute(
"""CREATE TABLE IF NOT EXISTS audit_log (
id INT AUTO_INCREMENT PRIMARY KEY,
actor VARCHAR(255) NOT NULL,
action VARCHAR(100) NOT NULL,
table_name VARCHAR(255) NOT NULL,
row_id INT NULL,
details TEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)"""
)
conn.commit()
except mariadb.Error as e:
print(f"ERROR: Failed to create required tables: {e}")
sys.exit(1)
# Create initial admin
print("\nCreate initial admin user for the API.")
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
while True:
admin_username = input("Admin username [admin]: ").strip() or "admin"
admin_password = input("Admin password: ").strip()
admin_password2 = input("Repeat admin password: ").strip()
if not admin_password:
print("Password cannot be empty.")
continue
if admin_password != admin_password2:
print("Passwords do not match, please try again.")
continue
break
admin_hash = pwd_context.hash(admin_password)
try:
cur = conn.cursor()
cur.execute(
"INSERT INTO users (username, password_hash, role) VALUES (%s, %s, %s)",
(admin_username, admin_hash, "admin"),
)
conn.commit()
except mariadb.Error as e:
print(f"ERROR: Failed to create initial admin user: {e}")
sys.exit(1)
finally:
conn.close()
# Ensure sections and store values in config
if not config.has_section("server"):
config["server"] = {"host": "0.0.0.0", "port": "8000"}
if not config.has_section("database"):
config["database"] = {}
config["database"]["host"] = host
config["database"]["port"] = str(port)
config["database"]["user"] = user
config["database"]["password"] = password
config["database"]["database"] = dbname
if not config.has_section("security"):
config["security"] = {}
if not config["security"].get("secret_key"):
import secrets
config["security"]["secret_key"] = secrets.token_hex(32)
if not config["security"].get("access_token_expire_minutes"):
config["security"]["access_token_expire_minutes"] = "60"
if not config.has_section("logging"):
config["logging"] = {"file": "app.log", "level": "INFO"}
with open("config.ini", "w") as f:
config.write(f)
print("\nSetup complete. Configuration saved to config.ini.")
print("You can now restart or continue running the application.")
# Run first-time setup wizard if DB config is missing and no env overrides
if not _db_config_present(config):
_run_initial_setup_wizard()
# Re-read in case the wizard updated the file on disk
config.read("config.ini")
# Now that config is guaranteed to exist, compute runtime settings
SERVER_HOST = config.get("server", "host", fallback="0.0.0.0")
SERVER_PORT = config.getint("server", "port", fallback=8000)
# Database connection settings
DB_HOST = os.getenv("DB_HOST", config.get("database", "host", fallback="localhost"))
DB_PORT = int(os.getenv("DB_PORT", str(config.getint("database", "port", fallback=3306))))
DB_USER = os.getenv("DB_USER", config.get("database", "user", fallback="root"))
DB_PASSWORD = os.getenv("DB_PASSWORD", config.get("database", "password", fallback=""))
DB_NAME = os.getenv("DB_NAME", config.get("database", "database", fallback="test"))
SECRET_KEY = config.get("security", "secret_key", fallback="CHANGE_ME_SECRET_KEY")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = config.getint("security", "access_token_expire_minutes", fallback=30)
LOG_FILE = config.get("logging", "file", fallback="app.log")
LOG_LEVEL = config.get("logging", "level", fallback="INFO").upper()
# Logging setup
logger = logging.getLogger("mariadb_api")
if not logger.handlers:
logger.setLevel(LOG_LEVEL)
file_handler = RotatingFileHandler(LOG_FILE, maxBytes=1_000_000, backupCount=3)
formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s - %(message)s")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Also log to stderr
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)