Eluza133 commited on
Commit
df2caee
·
verified ·
1 Parent(s): a196b95

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -22
app.py CHANGED
@@ -1,4 +1,4 @@
1
- from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file
2
  from flask_caching import Cache
3
  import json
4
  import os
@@ -111,6 +111,7 @@ BASE_STYLE = '''
111
  --shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
112
  --glass-bg: rgba(255, 255, 255, 0.15);
113
  --transition: all 0.3s ease;
 
114
  }
115
  * { margin: 0; padding: 0; box-sizing: border-box; }
116
  body {
@@ -186,6 +187,13 @@ input:focus, textarea:focus {
186
  .download-btn:hover {
187
  background: #00b8c5;
188
  }
 
 
 
 
 
 
 
189
  .flash {
190
  color: var(--secondary);
191
  text-align: center;
@@ -302,8 +310,9 @@ def register():
302
  'files': []
303
  }
304
  save_data(data)
305
- flash('Регистрация успешна! Войдите в систему.')
306
- return redirect(url_for('login'))
 
307
 
308
  html = '''
309
  <!DOCTYPE html>
@@ -311,13 +320,13 @@ def register():
311
  <head>
312
  <meta charset="UTF-8">
313
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
314
- <title>Регистрация - Zues Cloud</title>
315
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
316
  <style>''' + BASE_STYLE + '''</style>
317
  </head>
318
  <body>
319
  <div class="container">
320
- <h1>Регистрация в Zues Cloud</h1>
321
  {% with messages = get_flashed_messages() %}
322
  {% if messages %}
323
  {% for message in messages %}
@@ -325,7 +334,7 @@ def register():
325
  {% endfor %}
326
  {% endif %}
327
  {% endwith %}
328
- <form method="POST">
329
  <input type="text" name="username" placeholder="Введите логин" required>
330
  <input type="password" name="password" placeholder="Введите пароль" required>
331
  <input type="text" name="code" placeholder="Введите регистрационный код" required>
@@ -347,9 +356,9 @@ def login():
347
 
348
  if username in data['users'] and data['users'][username]['password'] == password:
349
  session['username'] = username
350
- return redirect(url_for('dashboard'))
351
  else:
352
- flash('Неверный логин или пароль!')
353
 
354
  html = '''
355
  <!DOCTYPE html>
@@ -357,27 +366,73 @@ def login():
357
  <head>
358
  <meta charset="UTF-8">
359
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
360
- <title>Zues Cloud</title>
361
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
362
  <style>''' + BASE_STYLE + '''</style>
363
  </head>
364
  <body>
365
  <div class="container">
366
- <h1>Zues Cloud</h1>
367
- {% with messages = get_flashed_messages() %}
368
- {% if messages %}
369
- {% for message in messages %}
370
- <div class="flash">{{ message }}</div>
371
- {% endfor %}
372
- {% endif %}
373
- {% endwith %}
374
- <form method="POST">
 
 
375
  <input type="text" name="username" placeholder="Введите логин" required>
376
  <input type="password" name="password" placeholder="Введите пароль" required>
377
  <button type="submit" class="btn">Войти</button>
378
  </form>
379
  <p style="margin-top: 20px;">Нет аккаунта? <a href="{{ url_for('register') }}">Зарегистрируйтесь</a></p>
380
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
381
  </body>
382
  </html>
383
  '''
@@ -396,7 +451,6 @@ def dashboard():
396
  flash('Пользователь не найден!')
397
  return redirect(url_for('login'))
398
 
399
- # Сортировка файлов по убыванию даты загрузки
400
  user_files = sorted(data['users'][username]['files'], key=lambda x: x['upload_date'], reverse=True)
401
 
402
  if request.method == 'POST':
@@ -450,13 +504,13 @@ def dashboard():
450
  <head>
451
  <meta charset="UTF-8">
452
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
453
- <title>Dashboard - Zues Cloud</title>
454
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
455
  <style>''' + BASE_STYLE + '''</style>
456
  </head>
457
  <body>
458
  <div class="container">
459
- <h1>Zues Cloud Dashboard</h1>
460
  <p>Пользователь: {{ username }}</p>
461
  {% with messages = get_flashed_messages() %}
462
  {% if messages %}
@@ -487,13 +541,14 @@ def dashboard():
487
  {% endif %}
488
  <p>{{ file['upload_date'] }}</p>
489
  <a href="{{ url_for('download_file', file_path=file['path'], filename=file['filename']) }}" class="btn download-btn">Скачать</a>
 
490
  </div>
491
  {% endfor %}
492
  {% if not user_files %}
493
  <p>У вас пока нет загруженных файлов.</p>
494
  {% endif %}
495
  </div>
496
- <a href="{{ url_for('logout') }}" class="btn" style="margin-top: 20px;">Выйти</a>
497
  </div>
498
  <div class="modal" id="mediaModal" onclick="closeModal(event)">
499
  <div id="modalContent"></div>
@@ -563,6 +618,13 @@ def dashboard():
563
 
564
  xhr.send(formData);
565
  });
 
 
 
 
 
 
 
566
  </script>
567
  </body>
568
  </html>
@@ -602,6 +664,44 @@ def download_file(file_path, filename):
602
  flash('Ошибка при скачивании файла!')
603
  return redirect(url_for('dashboard'))
604
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
605
  @app.route('/logout')
606
  def logout():
607
  session.pop('username', None)
 
1
+ from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify
2
  from flask_caching import Cache
3
  import json
4
  import os
 
111
  --shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
112
  --glass-bg: rgba(255, 255, 255, 0.15);
113
  --transition: all 0.3s ease;
114
+ --delete-color: #ff4444;
115
  }
116
  * { margin: 0; padding: 0; box-sizing: border-box; }
117
  body {
 
187
  .download-btn:hover {
188
  background: #00b8c5;
189
  }
190
+ .delete-btn {
191
+ background: var(--delete-color);
192
+ margin-top: 10px;
193
+ }
194
+ .delete-btn:hover {
195
+ background: #cc3333;
196
+ }
197
  .flash {
198
  color: var(--secondary);
199
  text-align: center;
 
310
  'files': []
311
  }
312
  save_data(data)
313
+ session['username'] = username
314
+ flash('Регистрация успешна!')
315
+ return redirect(url_for('dashboard'))
316
 
317
  html = '''
318
  <!DOCTYPE html>
 
320
  <head>
321
  <meta charset="UTF-8">
322
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
323
+ <title>Регистрация - Zeus Cloud</title>
324
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
325
  <style>''' + BASE_STYLE + '''</style>
326
  </head>
327
  <body>
328
  <div class="container">
329
+ <h1>Регистрация в Zeus Cloud</h1>
330
  {% with messages = get_flashed_messages() %}
331
  {% if messages %}
332
  {% for message in messages %}
 
334
  {% endfor %}
335
  {% endif %}
336
  {% endwith %}
337
+ <form method="POST" id="register-form">
338
  <input type="text" name="username" placeholder="Введите логин" required>
339
  <input type="password" name="password" placeholder="Введите пароль" required>
340
  <input type="text" name="code" placeholder="Введите регистрационный код" required>
 
356
 
357
  if username in data['users'] and data['users'][username]['password'] == password:
358
  session['username'] = username
359
+ return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
360
  else:
361
+ return jsonify({'status': 'error', 'message': 'Неверный логин или пароль!'})
362
 
363
  html = '''
364
  <!DOCTYPE html>
 
366
  <head>
367
  <meta charset="UTF-8">
368
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
369
+ <title>Zeus Cloud</title>
370
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
371
  <style>''' + BASE_STYLE + '''</style>
372
  </head>
373
  <body>
374
  <div class="container">
375
+ <h1>Zeus Cloud</h1>
376
+ <div id="flash-messages">
377
+ {% with messages = get_flashed_messages() %}
378
+ {% if messages %}
379
+ {% for message in messages %}
380
+ <div class="flash">{{ message }}</div>
381
+ {% endfor %}
382
+ {% endif %}
383
+ {% endwith %}
384
+ </div>
385
+ <form method="POST" id="login-form">
386
  <input type="text" name="username" placeholder="Введите логин" required>
387
  <input type="password" name="password" placeholder="Введите пароль" required>
388
  <button type="submit" class="btn">Войти</button>
389
  </form>
390
  <p style="margin-top: 20px;">Нет аккаунта? <a href="{{ url_for('register') }}">Зарегистрируйтесь</a></p>
391
  </div>
392
+ <script>
393
+ // Проверка localStorage и автоматический вход
394
+ const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
395
+ if (savedCredentials) {
396
+ fetch('/', {
397
+ method: 'POST',
398
+ headers: {
399
+ 'Content-Type': 'application/x-www-form-urlencoded',
400
+ },
401
+ body: `username=${encodeURIComponent(savedCredentials.username)}&password=${encodeURIComponent(savedCredentials.password)}`
402
+ })
403
+ .then(response => response.json())
404
+ .then(data => {
405
+ if (data.status === 'success') {
406
+ window.location.href = data.redirect;
407
+ }
408
+ })
409
+ .catch(error => console.error('Ошибка автоматического входа:', error));
410
+ }
411
+
412
+ // Обработка формы входа
413
+ document.getElementById('login-form').addEventListener('submit', function(e) {
414
+ e.preventDefault();
415
+ const formData = new FormData(this);
416
+ fetch('/', {
417
+ method: 'POST',
418
+ body: formData
419
+ })
420
+ .then(response => response.json())
421
+ .then(data => {
422
+ if (data.status === 'success') {
423
+ const username = formData.get('username');
424
+ const password = formData.get('password');
425
+ localStorage.setItem('zeusCredentials', JSON.stringify({ username, password }));
426
+ window.location.href = data.redirect;
427
+ } else {
428
+ document.getElementById('flash-messages').innerHTML = `<div class="flash">${data.message}</div>`;
429
+ }
430
+ })
431
+ .catch(error => {
432
+ document.getElementById('flash-messages').innerHTML = `<div class="flash">Ошибка соединения!</div>`;
433
+ });
434
+ });
435
+ </script>
436
  </body>
437
  </html>
438
  '''
 
451
  flash('Пользователь не найден!')
452
  return redirect(url_for('login'))
453
 
 
454
  user_files = sorted(data['users'][username]['files'], key=lambda x: x['upload_date'], reverse=True)
455
 
456
  if request.method == 'POST':
 
504
  <head>
505
  <meta charset="UTF-8">
506
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
507
+ <title>Dashboard - Zeus Cloud</title>
508
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
509
  <style>''' + BASE_STYLE + '''</style>
510
  </head>
511
  <body>
512
  <div class="container">
513
+ <h1>Zeus Cloud Dashboard</h1>
514
  <p>Пользователь: {{ username }}</p>
515
  {% with messages = get_flashed_messages() %}
516
  {% if messages %}
 
541
  {% endif %}
542
  <p>{{ file['upload_date'] }}</p>
543
  <a href="{{ url_for('download_file', file_path=file['path'], filename=file['filename']) }}" class="btn download-btn">Скачать</a>
544
+ <a href="{{ url_for('delete_file', file_path=file['path']) }}" class="btn delete-btn" onclick="return confirm('Вы уверены, что хотите удалить этот файл?');">Удалить</a>
545
  </div>
546
  {% endfor %}
547
  {% if not user_files %}
548
  <p>У вас пока нет загруженных файлов.</p>
549
  {% endif %}
550
  </div>
551
+ <a href="{{ url_for('logout') }}" class="btn" style="margin-top: 20px;" id="logout-btn">Выйти</a>
552
  </div>
553
  <div class="modal" id="mediaModal" onclick="closeModal(event)">
554
  <div id="modalContent"></div>
 
618
 
619
  xhr.send(formData);
620
  });
621
+
622
+ // Обработка выхода
623
+ document.getElementById('logout-btn').addEventListener('click', function(e) {
624
+ e.preventDefault();
625
+ localStorage.removeItem('zeusCredentials');
626
+ window.location.href = '/logout';
627
+ });
628
  </script>
629
  </body>
630
  </html>
 
664
  flash('Ошибка при скачивании файла!')
665
  return redirect(url_for('dashboard'))
666
 
667
+ @app.route('/delete/<path:file_path>')
668
+ def delete_file(file_path):
669
+ if 'username' not in session:
670
+ flash('Пожалуйста, войдите!')
671
+ return redirect(url_for('login'))
672
+
673
+ username = session['username']
674
+ data = load_data()
675
+ if username not in data['users']:
676
+ session.pop('username', None)
677
+ flash('Пользователь не найден!')
678
+ return redirect(url_for('login'))
679
+
680
+ user_files = data['users'][username]['files']
681
+ file_to_delete = next((file for file in user_files if file['path'] == file_path), None)
682
+
683
+ if not file_to_delete:
684
+ flash('Файл не найден!')
685
+ return redirect(url_for('dashboard'))
686
+
687
+ try:
688
+ api = HfApi()
689
+ api.delete_file(
690
+ path_in_repo=file_path,
691
+ repo_id=REPO_ID,
692
+ repo_type="dataset",
693
+ token=HF_TOKEN_WRITE,
694
+ commit_message=f"Удален файл {file_path} для {username}"
695
+ )
696
+ data['users'][username]['files'] = [f for f in user_files if f['path'] != file_path]
697
+ save_data(data)
698
+ flash('Файл успешно удален!')
699
+ except Exception as e:
700
+ logging.error(f"Ошибка при удалении файла: {e}")
701
+ flash('Ошибка при удалении файла!')
702
+
703
+ return redirect(url_for('dashboard'))
704
+
705
  @app.route('/logout')
706
  def logout():
707
  session.pop('username', None)