-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
494 lines (435 loc) · 20.8 KB
/
app.py
File metadata and controls
494 lines (435 loc) · 20.8 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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
from flask import Flask, request, send_from_directory, render_template_string, redirect, url_for, abort, Response, session, flash
import os
import shutil
import zipfile
import hashlib
import secrets
from io import BytesIO
from urllib.parse import unquote
app = Flask(__name__)
app.secret_key = secrets.token_hex(32) # برای session و flash
# فایل برای ذخیره هش پسورد
PASSWORD_FILE = 'password.hash'
def hash_password(password):
"""هش امن پسورد با salt تصادفی"""
salt = secrets.token_hex(16)
pwd_hash = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt.encode('utf-8'), 100000)
return salt + ':' + pwd_hash.hex()
def verify_password(stored_hash, provided_password):
"""بررسی پسورد با هش ذخیره شده"""
if ':' not in stored_hash:
return False
salt, hash_val = stored_hash.split(':')
pwd_hash = hashlib.pbkdf2_hmac('sha256', provided_password.encode('utf-8'), salt.encode('utf-8'), 100000)
return secrets.compare_digest(pwd_hash.hex(), hash_val)
def is_authenticated():
return session.get('authenticated', False)
def require_auth(f):
"""دکوراتور برای نیاز به احراز هویت"""
from functools import wraps
@wraps(f)
def decorated(*args, **kwargs):
if not is_authenticated():
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated
# ------------------- صفحات احراز هویت -------------------
@app.route('/login', methods=['GET', 'POST'])
def login():
password_exists = os.path.exists(PASSWORD_FILE)
if request.method == 'POST':
password = request.form.get('password', '')
if password_exists:
with open(PASSWORD_FILE, 'r') as f:
stored_hash = f.read().strip()
if verify_password(stored_hash, password):
session['authenticated'] = True
flash('Login successful!', 'success')
return redirect(url_for('dir_listing'))
else:
flash('Incorrect password!', 'danger')
else:
# اولین بار — تنظیم پسورد
if password:
with open(PASSWORD_FILE, 'w') as f:
f.write(hash_password(password))
session['authenticated'] = True
flash('Password set successfully! You are now logged in.', 'success')
return redirect(url_for('dir_listing'))
else:
flash('Please enter a password.', 'warning')
template = '''
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% if password_exists %}Login{% else %}Set Password (First Time){% endif %} - File Manager</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-4">
<div class="card shadow">
<div class="card-body">
<h3 class="card-title text-center mb-4">
{% if password_exists %}Login{% else %}Set Password (First Time){% endif %}
</h3>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
<form method="post">
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" name="password" id="password" required autofocus>
</div>
<button type="submit" class="btn btn-primary w-100">
{% if password_exists %}Login{% else %}Set Password{% endif %}
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
'''
return render_template_string(template, password_exists=password_exists)
@app.route('/change_password', methods=['GET', 'POST'])
@require_auth
def change_password():
if request.method == 'POST':
old_password = request.form.get('old_password', '')
new_password = request.form.get('new_password', '')
confirm_password = request.form.get('confirm_password', '')
if not os.path.exists(PASSWORD_FILE):
flash('No existing password found.', 'danger')
return redirect(url_for('change_password'))
with open(PASSWORD_FILE, 'r') as f:
stored_hash = f.read().strip()
if not verify_password(stored_hash, old_password):
flash('Old password is incorrect.', 'danger')
elif new_password != confirm_password:
flash('New passwords do not match.', 'danger')
elif not new_password:
flash('New password cannot be empty.', 'danger')
else:
with open(PASSWORD_FILE, 'w') as f:
f.write(hash_password(new_password))
flash('Password changed successfully!', 'success')
return redirect(url_for('dir_listing'))
# تمپلیت درست با render_template_string و پاس دادن متغیرها
template = '''
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Change Password - File Manager</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-5">
<div class="card shadow">
<div class="card-body">
<h3 class="card-title text-center mb-4">Change Password</h3>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
<form method="post">
<div class="mb-3">
<label class="form-label">Current Password</label>
<input type="password" class="form-control" name="old_password" required autofocus>
</div>
<div class="mb-3">
<label class="form-label">New Password</label>
<input type="password" class="form-control" name="new_password" required>
</div>
<div class="mb-3">
<label class="form-label">Confirm New Password</label>
<input type="password" class="form-control" name="confirm_password" required>
</div>
<div class="d-grid gap-2">
<button type="submit" class="btn btn-primary">Change Password</button>
<a href="{{ url_for('dir_listing') }}" class="btn btn-secondary">Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
'''
return render_template_string(template)
@app.route('/logout')
def logout():
session.pop('authenticated', None)
flash('Logged out successfully.', 'info')
return redirect(url_for('login'))
# ------------------- بقیه کد فایل منیجر با احراز هویت -------------------
def get_drives():
drives = []
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
drive = f"{letter}:\\"
if os.path.exists(drive):
drives.append(f"{letter}:")
return drives
def get_file_icon(filename):
_, ext = os.path.splitext(filename.lower())
icons = {
'.pdf': 'file-earmark-pdf', '.doc': 'file-earmark-word', '.docx': 'file-earmark-word',
'.xls': 'file-earmark-excel', '.xlsx': 'file-earmark-excel',
'.ppt': 'file-earmark-ppt', '.pptx': 'file-earmark-ppt',
'.txt': 'file-earmark-text', '.py': 'file-earmark-code',
'.jpg': 'file-earmark-image', '.jpeg': 'file-earmark-image', '.png': 'file-earmark-image', '.gif': 'file-earmark-image',
'.mp3': 'file-earmark-music', '.wav': 'file-earmark-music',
'.mp4': 'file-earmark-play', '.avi': 'file-earmark-play', '.mkv': 'file-earmark-play',
'.zip': 'file-earmark-zip', '.rar': 'file-earmark-zip',
'.exe': 'file-earmark-binary',
}
return icons.get(ext, 'file-earmark' if ext else 'folder')
@app.route('/', defaults={'req_path': ''})
@app.route('/<path:req_path>')
@require_auth
def dir_listing(req_path):
# ... (کد قبلی dir_listing بدون تغییر، فقط @require_auth اضافه شد)
# برای اختصار اینجا کپی نکردم، اما دقیقاً همان کد قبلی است
# فقط parent logic رو با فیکس قبلی نگه داشتی
req_path = unquote(req_path).rstrip('/')
if not req_path:
files = []
for d in get_drives():
files.append({
'name': d,
'display_name': d + '/',
'is_dir': True,
'path': d + '/',
'icon': 'folder',
'is_drive': True
})
current_path = "Root (Drives)"
parent = None
show_delete = False
normalized_path = ''
else:
if os.name == 'nt':
if len(req_path) == 2 and req_path[1] == ':':
abs_path = req_path + "\\"
display_path = req_path + "/"
normalized_path = req_path + "/"
else:
abs_path = req_path.replace('/', '\\')
display_path = req_path.rstrip('/') + '/'
normalized_path = req_path.rstrip('/') + '/'
else:
abs_path = '/' + req_path
display_path = req_path.rstrip('/') + '/'
normalized_path = req_path.rstrip('/') + '/'
if not os.path.exists(abs_path):
abort(404, "Path not found")
if os.path.isfile(abs_path):
return send_from_directory(os.path.dirname(abs_path), os.path.basename(abs_path))
try:
entries = os.listdir(abs_path)
except PermissionError:
abort(403, "Permission denied")
files = []
is_drive_root = (len(req_path) == 2 and req_path[1] == ':')
show_delete = not is_drive_root
for entry in sorted(entries, key=lambda x: (not os.path.isdir(os.path.join(abs_path, x)), x.lower())):
full_path = os.path.join(abs_path, entry)
rel_path = normalized_path + entry
rel_path = rel_path.replace('\\', '/')
is_dir = os.path.isdir(full_path)
icon = 'folder' if is_dir else get_file_icon(entry)
files.append({
'name': entry,
'display_name': entry + ('/' if is_dir else ''),
'is_dir': is_dir,
'path': rel_path,
'icon': icon,
'is_drive': False
})
current_path = display_path
if is_drive_root:
parent = ''
else:
parent_path = os.path.dirname(req_path.rstrip('/')).replace('\\', '/')
parent = parent_path + '/' if parent_path else None
# اضافه کردن لینک Logout در تمپلیت
template = '''
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>File Manager</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<style>
body { background-color: #f8f9fa; }
.icon { font-size: 1.5rem; margin-right: 10px; }
.dir-link { font-weight: 500; color: #0d6efd; }
</style>
</head>
<body>
<div class="container mt-5">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="text-primary">File Manager - {{ current_path }}</h1>
<div>
<a href="/change_password" class="btn btn-outline-warning btn-sm me-2">Change Password</a>
<a href="/logout" class="btn btn-outline-danger btn-sm">Logout</a>
</div>
</div>
{% if parent is not none %}
<a href="{{ url_for('dir_listing', req_path=parent) }}" class="btn btn-outline-secondary mb-3">
<i class="bi bi-arrow-up"></i> Go Up
</a>
{% endif %}
<!-- بقیه تمپلیت مثل قبل -->
<div class="card shadow-sm mb-4">
<div class="list-group list-group-flush">
{% for file in files %}
<div class="list-group-item d-flex justify-content-between align-items-center">
<div class="d-flex align-items-center">
<i class="bi bi-{{ file.icon }} icon text-primary"></i>
<a href="{{ url_for('dir_listing' if file.is_dir else 'download', req_path=file.path) }}"
class="dir-link {% if file.is_dir %}fw-bold{% endif %}">
{{ file.display_name }}
</a>
</div>
<div>
{% if file.is_dir and not file.is_drive %}
<a href="{{ url_for('download_zip', req_path=file.path) }}" class="btn btn-outline-info btn-sm me-2">
<i class="bi bi-download"></i> Download ZIP
</a>
{% endif %}
{% if show_delete and not file.is_drive %}
<form action="{{ url_for('delete', req_path=file.path) }}" method="post" style="display:inline;">
<button type="submit" class="btn btn-danger btn-sm"
onclick="return confirm('Are you sure you want to delete this?');">
<i class="bi bi-trash"></i> Delete
</button>
</form>
{% endif %}
</div>
</div>
{% endfor %}
</div>
</div>
<hr class="my-5">
<h3 class="mb-3">Upload Files (Multiple allowed)</h3>
<form action="{{ url_for('upload', req_path=normalized_path) }}" method="post" enctype="multipart/form-data" class="mb-4">
<div class="input-group">
<input type="file" name="files" class="form-control" multiple>
<button type="submit" class="btn btn-success">Upload</button>
</div>
</form>
<h3 class="mb-3">Create New Folder</h3>
<form action="{{ url_for('create_folder', req_path=normalized_path) }}" method="post">
<div class="input-group mb-3">
<input type="text" name="folder_name" class="form-control" placeholder="Folder name" required>
<button type="submit" class="btn btn-primary">Create</button>
</div>
</form>
</div>
</body>
</html>
'''
return render_template_string(template,
files=files,
current_path=current_path or "Root",
parent=parent,
show_delete=show_delete,
normalized_path=normalized_path or '')
@app.route('/download/<path:req_path>')
def download(req_path):
req_path = unquote(req_path)
abs_path = req_path.replace('/', '\\') if os.name == 'nt' else '/' + req_path
if not os.path.exists(abs_path) or os.path.isdir(abs_path):
abort(404)
return send_from_directory(os.path.dirname(abs_path), os.path.basename(abs_path), as_attachment=True)
@app.route('/download_zip/<path:req_path>')
def download_zip(req_path):
req_path = unquote(req_path).rstrip('/')
abs_path = req_path.replace('/', '\\') if os.name == 'nt' else '/' + req_path
if not os.path.exists(abs_path) or not os.path.isdir(abs_path):
abort(404)
memory_file = BytesIO()
with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zf:
for root, dirs, files in os.walk(abs_path):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, os.path.dirname(abs_path) if os.name == 'nt' else abs_path)
zf.write(file_path, arcname)
memory_file.seek(0)
return Response(memory_file, mimetype='application/zip',
headers={"Content-Disposition": f"attachment;filename={os.path.basename(abs_path)}.zip"})
@app.route('/upload/', methods=['POST'])
@app.route('/upload/<path:req_path>', methods=['POST'])
def upload(req_path=''):
req_path = unquote(req_path).rstrip('/')
if not req_path:
return "Please select a drive first.", 400
abs_path = req_path.replace('/', '\\') if os.name == 'nt' else '/' + req_path
if len(req_path) == 2 and req_path[1] == ':':
abs_path = req_path + '\\'
files = request.files.getlist('files')
if not files or all(f.filename == '' for f in files):
return "No files selected", 400
for file in files:
if file.filename:
try:
file.save(os.path.join(abs_path, file.filename))
except Exception as e:
return f"Upload error: {e}", 500
return redirect(url_for('dir_listing', req_path=req_path + '/'))
@app.route('/create_folder/', methods=['POST'])
@app.route('/create_folder/<path:req_path>', methods=['POST'])
def create_folder(req_path=''):
req_path = unquote(req_path).rstrip('/')
if not req_path:
return "Please select a drive first.", 400
abs_path = req_path.replace('/', '\\') if os.name == 'nt' else '/' + req_path
if len(req_path) == 2 and req_path[1] == ':':
abs_path = req_path + '\\'
folder_name = request.form.get('folder_name')
if not folder_name:
return "Folder name required", 400
try:
os.mkdir(os.path.join(abs_path, folder_name))
except Exception as e:
return f"Error creating folder: {e}", 500
return redirect(url_for('dir_listing', req_path=req_path + '/'))
@app.route('/delete/<path:req_path>', methods=['POST'])
def delete(req_path):
req_path = unquote(req_path).rstrip('/')
abs_path = req_path.replace('/', '\\') if os.name == 'nt' else '/' + req_path
try:
if os.path.isfile(abs_path):
os.remove(abs_path)
elif os.path.isdir(abs_path):
shutil.rmtree(abs_path)
except Exception as e:
return f"Delete error: {e}", 500
parent = os.path.dirname(req_path).replace('\\', '/')
return redirect(url_for('dir_listing', req_path=parent + '/' if parent else ''))
if __name__ == '__main__':
print("WARNING: This file manager gives full read/write access to the entire filesystem!")
print("Use only locally and with extreme caution.")
print("Server running at http://localhost:2121")
app.run(host='0.0.0.0', port=2121, debug=False)