Repository navigation
Expand file tree
/
Copy pathinstaller.py
More file actions
468 lines (359 loc) · 14 KB
/
Copy pathinstaller.py
File metadata and controls
468 lines (359 loc) · 14 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
"""
BytePanel Installer - Flask app for initial setup
Allows users to configure admin username and password before first run
Runs on port 1209 by default
"""
import os
import json
from pathlib import Path
from datetime import datetime
from flask import Flask, render_template, request, jsonify, redirect, url_for, session, flash
from werkzeug.security import generate_password_hash, check_password_hash
from functools import wraps
app = Flask(__name__)
app.secret_key = os.urandom(32)
# Configuration
INSTANCE_DIR = Path("instance")
DATA_FILE = INSTANCE_DIR / "data.json"
CONFIG_FILE = INSTANCE_DIR / "installer_config.json"
PANEL_PORT = 1209
def is_installed():
"""Check if BytePanel has been installed/configured"""
return DATA_FILE.exists() and (INSTANCE_DIR / "installed").exists()
def load_config():
"""Load installer configuration"""
if CONFIG_FILE.exists():
with open(CONFIG_FILE, "r") as f:
return json.load(f)
return {}
def save_config(config):
"""Save installer configuration"""
INSTANCE_DIR.mkdir(exist_ok=True)
with open(CONFIG_FILE, "w") as f:
json.dump(config, f, indent=2)
def load_data():
"""Load data from JSON file"""
if not DATA_FILE.exists():
return {"users": [], "servers": [], "audit_log": [], "installed": False}
try:
with open(DATA_FILE, "r") as f:
return json.load(f)
except:
return {"users": [], "servers": [], "audit_log": [], "installed": False}
def save_data(data):
"""Save data to JSON file"""
INSTANCE_DIR.mkdir(exist_ok=True)
with open(DATA_FILE, "w") as f:
json.dump(data, f, indent=2)
def initialize_panel(username, password, email=""):
"""Initialize BytePanel with admin user"""
INSTANCE_DIR.mkdir(exist_ok=True)
# Create initial data structure
data = {
"users": [
{
"id": 1,
"username": username,
"password_hash": generate_password_hash(password),
"is_admin": True,
"email": email,
"created_at": datetime.now().isoformat()
}
],
"servers": [],
"audit_log": [
{
"level": "info",
"event": "panel.init",
"message": f"BytePanel initialized with admin user: {username}",
"timestamp": datetime.now().isoformat()
}
]
}
# Save data file
save_data(data)
# Mark as installed
(INSTANCE_DIR / "installed").touch()
return True
def admin_required(f):
"""Decorator to require admin login"""
@wraps(f)
def decorated_function(*args, **kwargs):
if "username" not in session:
flash("Please login first", "error")
return redirect(url_for("login"))
# Load data to check if user is admin
data = load_data()
user = None
for u in data.get("users", []):
if u["username"] == session["username"]:
user = u
break
if not user or not user.get("is_admin"):
flash("Admin access required", "error")
return redirect(url_for("index"))
return f(*args, **kwargs)
return decorated_function
def login_required(f):
"""Decorator to require login"""
@wraps(f)
def decorated_function(*args, **kwargs):
if "username" not in session:
flash("Please login first", "error")
return redirect(url_for("login"))
return f(*args, **kwargs)
return decorated_function
@app.route("/")
def index():
"""Main installer page"""
if is_installed():
if "username" in session:
return redirect(url_for("dashboard"))
return redirect(url_for("login"))
return render_template("installer.html")
@app.route("/install", methods=["GET", "POST"])
def install():
"""Installation wizard"""
if is_installed():
return redirect(url_for("login"))
if request.method == "POST":
username = (request.form.get("username") or "").strip()
password = request.form.get("password", "")
confirm_password = request.form.get("confirm_password", "")
email = (request.form.get("email") or "").strip()
errors = []
if not username or len(username) < 3:
errors.append("Username must be at least 3 characters")
if not password or len(password) < 6:
errors.append("Password must be at least 6 characters")
if password != confirm_password:
errors.append("Passwords do not match")
if email and "@" not in email:
errors.append("Invalid email format")
if errors:
for error in errors:
flash(error, "error")
else:
initialize_panel(username, password, email)
flash("Installation complete! Please login.", "success")
return redirect(url_for("login"))
return render_template("installer.html")
@app.route("/api/setup", methods=["POST"])
def setup_admin():
"""API endpoint to setup admin user"""
if is_installed():
return jsonify({"ok": False, "error": "BytePanel is already installed"}), 409
data_req = request.json
username = (data_req.get("username") or "").strip()
password = data_req.get("password", "")
confirm_password = data_req.get("confirm_password", "")
email = (data_req.get("email") or "").strip()
# Validation
if not username:
return jsonify({"ok": False, "error": "Username is required"}), 400
if len(username) < 3:
return jsonify({"ok": False, "error": "Username must be at least 3 characters"}), 400
if not password:
return jsonify({"ok": False, "error": "Password is required"}), 400
if len(password) < 6:
return jsonify({"ok": False, "error": "Password must be at least 6 characters"}), 400
if password != confirm_password:
return jsonify({"ok": False, "error": "Passwords do not match"}), 400
if email and "@" not in email:
return jsonify({"ok": False, "error": "Invalid email format"}), 400
try:
initialize_panel(username, password, email)
return jsonify({
"ok": True,
"message": "BytePanel installed successfully!",
"username": username,
"next_step": "Start BytePanel with: python run.py"
}), 201
except Exception as e:
return jsonify({"ok": False, "error": f"Installation failed: {str(e)}"}), 500
@app.route("/login", methods=["GET", "POST"])
def login():
"""Login page"""
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
data = load_data()
user = None
for u in data.get("users", []):
if u["username"] == username:
user = u
break
if user and check_password_hash(user.get("password_hash", ""), password):
session["username"] = username
session["is_admin"] = user.get("is_admin", False)
flash(f"Welcome back, {username}!", "success")
return redirect(url_for("dashboard"))
else:
flash("Invalid credentials", "error")
return render_template("login.html")
@app.route("/logout")
def logout():
"""Logout"""
username = session.get("username")
session.clear()
if username:
flash(f"Goodbye, {username}!", "success")
return redirect(url_for("login"))
@app.route("/admin/register", methods=["GET", "POST"])
def admin_register():
"""Admin registration - only first user can register as admin"""
# Load current data
data = load_data()
admin_count = sum(1 for u in data.get("users", []) if u.get("is_admin"))
# If admin already exists and user is not logged in as admin, deny access
if admin_count > 0:
if "username" not in session:
flash("Admin already registered. Please login.", "error")
return redirect(url_for("login"))
# Check if current user is admin
current_user = None
for u in data.get("users", []):
if u["username"] == session["username"]:
current_user = u
break
if not current_user or not current_user.get("is_admin"):
flash("Only the first user can be admin. Admin already exists.", "error")
return redirect(url_for("login"))
if request.method == "POST":
username = (request.form.get("username") or "").strip()
password = request.form.get("password", "")
confirm_password = request.form.get("confirm_password", "")
email = (request.form.get("email") or "").strip()
# Validation
errors = []
if not username:
errors.append("Username is required")
elif len(username) < 3:
errors.append("Username must be at least 3 characters")
# Check if username already exists
if any(u["username"] == username for u in data.get("users", [])):
errors.append("Username already taken")
if not password:
errors.append("Password is required")
elif len(password) < 6:
errors.append("Password must be at least 6 characters")
if password != confirm_password:
errors.append("Passwords do not match")
if email and "@" not in email:
errors.append("Invalid email format")
if errors:
for error in errors:
flash(error, "error")
return redirect(url_for("admin_register"))
# Create admin user
new_user = {
"id": len(data.get("users", [])) + 1,
"username": username,
"password_hash": generate_password_hash(password),
"email": email,
"is_admin": True,
"created_at": datetime.now().isoformat()
}
data.setdefault("users", []).append(new_user)
# Save updated data
save_data(data)
flash("Admin registered successfully! Please login with your credentials.", "success")
return redirect(url_for("login"))
# Check if this is first registration or admin editing
is_first_admin = admin_count == 0
return render_template("admin_register.html", is_first_admin=is_first_admin)
@app.route("/dashboard")
@login_required
def dashboard():
"""Main dashboard"""
data = load_data()
user = None
for u in data.get("users", []):
if u["username"] == session["username"]:
user = u
break
return render_template("dashboard.html",
username=session["username"],
is_admin=session.get("is_admin"),
user=user)
@app.route("/admin")
@admin_required
def admin_panel():
"""Admin panel"""
data = load_data()
users = data.get("users", [])
audit_log = data.get("audit_log", [])[-50:] # Last 50 entries
return render_template("admin_panel.html",
users=users,
audit_log=audit_log)
@app.route("/settings")
@login_required
def settings():
"""User settings"""
data = load_data()
user = None
for u in data.get("users", []):
if u["username"] == session["username"]:
user = u
break
return render_template("settings.html", user=user)
@app.route("/api/settings/password", methods=["POST"])
@login_required
def api_change_password():
"""API: Change password"""
data_req = request.json
old_password = data_req.get("old_password", "")
new_password = data_req.get("new_password", "")
confirm_password = data_req.get("confirm_password", "")
data = load_data()
user = None
for u in data.get("users", []):
if u["username"] == session["username"]:
user = u
break
if not user:
return jsonify({"ok": False, "error": "User not found"}), 404
if not check_password_hash(user.get("password_hash", ""), old_password):
return jsonify({"ok": False, "error": "Current password is incorrect"}), 401
if len(new_password) < 6:
return jsonify({"ok": False, "error": "New password must be at least 6 characters"}), 400
if new_password != confirm_password:
return jsonify({"ok": False, "error": "Passwords do not match"}), 400
user["password_hash"] = generate_password_hash(new_password)
save_data(data)
return jsonify({"ok": True, "message": "Password changed successfully"})
@app.route("/status")
def status():
"""Check installation status"""
return jsonify({
"installed": is_installed(),
"instance_dir": str(INSTANCE_DIR),
"data_file": str(DATA_FILE),
"port": PANEL_PORT
})
@app.errorhandler(404)
def not_found(error):
"""Handle 404 errors"""
return render_template("404.html"), 404
@app.errorhandler(500)
def server_error(error):
"""Handle 500 errors"""
return render_template("500.html"), 500
if __name__ == "__main__":
INSTANCE_DIR.mkdir(exist_ok=True)
print("=" * 60)
print("🚀 BytePanel - Professional Server Management")
print("=" * 60)
print(f"📍 Starting on http://localhost:{PANEL_PORT}")
print(f"📁 Data directory: {INSTANCE_DIR}")
print("")
if not is_installed():
print("⚠️ First run detected - Setup wizard will start")
print(f"🌐 Open http://localhost:{PANEL_PORT}/install")
else:
print("✅ Panel is already installed")
print(f"🌐 Open http://localhost:{PANEL_PORT}/login")
print(f"📝 Admin Register: http://localhost:{PANEL_PORT}/admin/register")
print("=" * 60)
print("")
app.run(host="0.0.0.0", port=PANEL_PORT, debug=False)