аутентификация к веб админке
This commit is contained in:
parent
595c9419f4
commit
e6967db17d
6 changed files with 282 additions and 2 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -44,6 +44,9 @@ logs/
|
|||
.env.local
|
||||
.env.backup
|
||||
|
||||
# Auth config (contains passwords)
|
||||
LichessWebView/auth_config.json
|
||||
|
||||
|
||||
# Node modules (если будут использоваться)
|
||||
node_modules/
|
||||
|
|
|
|||
|
|
@ -1,14 +1,29 @@
|
|||
from flask import Flask, jsonify, render_template
|
||||
from flask import Flask, jsonify, render_template, request, session, redirect, url_for
|
||||
from flask_cors import CORS
|
||||
import sqlite3
|
||||
from datetime import datetime, date
|
||||
from functools import wraps
|
||||
import os
|
||||
import auth_config
|
||||
|
||||
app = Flask(__name__)
|
||||
# Secret key для сессий (в продакшене лучше использовать переменную окружения)
|
||||
app.secret_key = os.environ.get('FLASK_SECRET_KEY', 'your-secret-key-change-in-production-please')
|
||||
CORS(app)
|
||||
|
||||
# Путь к базе данных бота
|
||||
DB_PATH = "/app/data/lichess_bot.db"
|
||||
|
||||
|
||||
def login_required(f):
|
||||
"""Декоратор для защиты роутов, требующих аутентификации"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if 'authenticated' not in session or not session['authenticated']:
|
||||
return redirect(url_for('login'))
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
def get_message_counters_stats(db_path):
|
||||
"""Get message counters statistics directly from database"""
|
||||
try:
|
||||
|
|
@ -97,12 +112,45 @@ def get_message_counters_stats(db_path):
|
|||
'by_command': {}
|
||||
}
|
||||
|
||||
@app.route('/login', methods=['GET', 'POST'])
|
||||
def login():
|
||||
"""Страница входа"""
|
||||
if request.method == 'POST':
|
||||
username = request.form.get('username', '').strip()
|
||||
password = request.form.get('password', '')
|
||||
|
||||
if auth_config.validate_credentials(username, password):
|
||||
session['authenticated'] = True
|
||||
session['username'] = username
|
||||
return redirect(url_for('index'))
|
||||
else:
|
||||
error_msg = 'Неверный логин или пароль'
|
||||
return redirect(url_for('login', error=error_msg))
|
||||
|
||||
# GET запрос - показать форму логина
|
||||
error = request.args.get('error', '')
|
||||
# Если уже авторизован, перенаправляем на главную
|
||||
if 'authenticated' in session and session.get('authenticated'):
|
||||
return redirect(url_for('index'))
|
||||
return render_template('login.html', error=error)
|
||||
|
||||
|
||||
@app.route('/logout')
|
||||
def logout():
|
||||
"""Выход из системы"""
|
||||
session.pop('authenticated', None)
|
||||
session.pop('username', None)
|
||||
return redirect(url_for('login'))
|
||||
|
||||
|
||||
@app.route('/')
|
||||
@login_required
|
||||
def index():
|
||||
"""Главная страница"""
|
||||
return render_template('index.html')
|
||||
|
||||
@app.route('/api/users')
|
||||
@login_required
|
||||
def get_users():
|
||||
"""Получить всех пользователей"""
|
||||
try:
|
||||
|
|
@ -217,6 +265,7 @@ def get_users():
|
|||
}), 500
|
||||
|
||||
@app.route('/api/users/<int:user_id>/gamers')
|
||||
@login_required
|
||||
def get_user_gamers(user_id):
|
||||
"""Получить игроков конкретного пользователя"""
|
||||
try:
|
||||
|
|
|
|||
13
LichessWebView/auth_config.example.json
Normal file
13
LichessWebView/auth_config.example.json
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"users": [
|
||||
{
|
||||
"username": "admin",
|
||||
"password": "change_me_123"
|
||||
},
|
||||
{
|
||||
"username": "user2",
|
||||
"password": "another_password"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
60
LichessWebView/auth_config.py
Normal file
60
LichessWebView/auth_config.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
"""Модуль для загрузки конфигурации аутентификации"""
|
||||
import json
|
||||
import os
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
AUTH_CONFIG_PATH = "/app/auth_config.json"
|
||||
AUTH_CONFIG_EXAMPLE_PATH = "/app/auth_config.example.json"
|
||||
|
||||
|
||||
def load_auth_config() -> Optional[Dict]:
|
||||
"""
|
||||
Загружает конфигурацию аутентификации из файла.
|
||||
Возвращает None, если файл не найден.
|
||||
"""
|
||||
config_path = AUTH_CONFIG_PATH
|
||||
|
||||
# Если файл не существует, пробуем example
|
||||
if not os.path.exists(config_path):
|
||||
if os.path.exists(AUTH_CONFIG_EXAMPLE_PATH):
|
||||
print(f"Warning: {config_path} not found, using example config")
|
||||
config_path = AUTH_CONFIG_EXAMPLE_PATH
|
||||
else:
|
||||
print(f"Error: Neither {AUTH_CONFIG_PATH} nor {AUTH_CONFIG_EXAMPLE_PATH} found")
|
||||
return None
|
||||
|
||||
try:
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
return config
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error parsing auth config: {e}")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"Error loading auth config: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def get_users() -> List[Dict[str, str]]:
|
||||
"""
|
||||
Возвращает список пользователей из конфига.
|
||||
"""
|
||||
config = load_auth_config()
|
||||
if not config:
|
||||
return []
|
||||
|
||||
return config.get('users', [])
|
||||
|
||||
|
||||
def validate_credentials(username: str, password: str) -> bool:
|
||||
"""
|
||||
Проверяет правильность логина и пароля.
|
||||
"""
|
||||
users = get_users()
|
||||
|
||||
for user in users:
|
||||
if user.get('username') == username and user.get('password') == password:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
|
@ -282,7 +282,10 @@
|
|||
<div class="container">
|
||||
<!-- Левая панель: Пользователи -->
|
||||
<div class="panel users-panel">
|
||||
<h1>👥 Пользователи</h1>
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
|
||||
<h1 style="margin: 0;">👥 Пользователи</h1>
|
||||
<a href="/logout" style="padding: 8px 16px; background: #8B6F47; color: white; text-decoration: none; border-radius: 8px; font-size: 14px; transition: background 0.3s;" onmouseover="this.style.background='#6B5432'" onmouseout="this.style.background='#8B6F47'">Выход</a>
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
Всего пользователей: <strong id="total-users">0</strong> (сегодня: <strong id="users-today">0</strong>)<br>
|
||||
|
|
|
|||
152
LichessWebView/templates/login.html
Normal file
152
LichessWebView/templates/login.html
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Вход в админ-панель</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
background: #D2B48C;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.login-container {
|
||||
background: #F5E6D3;
|
||||
border-radius: 15px;
|
||||
padding: 40px;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
|
||||
max-width: 400px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #5C4033;
|
||||
margin-bottom: 30px;
|
||||
text-align: center;
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
color: #5C4033;
|
||||
margin-bottom: 8px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
input[type="text"],
|
||||
input[type="password"] {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
transition: border-color 0.3s;
|
||||
}
|
||||
|
||||
input[type="text"]:focus,
|
||||
input[type="password"]:focus {
|
||||
outline: none;
|
||||
border-color: #8B6F47;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
background: #f8d7da;
|
||||
color: #721c24;
|
||||
padding: 12px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 20px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.error-message.show {
|
||||
display: block;
|
||||
}
|
||||
|
||||
button {
|
||||
width: 100%;
|
||||
padding: 14px;
|
||||
background: #8B6F47;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.3s;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: #6B5432;
|
||||
}
|
||||
|
||||
button:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="login-container">
|
||||
<h1>🔐 Вход в админ-панель</h1>
|
||||
|
||||
<div class="error-message" id="error-message"></div>
|
||||
|
||||
<form method="POST" action="/login" id="login-form">
|
||||
{% if error %}
|
||||
<div class="error-message show">{{ error }}</div>
|
||||
{% endif %}
|
||||
<div class="form-group">
|
||||
<label for="username">Логин:</label>
|
||||
<input type="text" id="username" name="username" required autofocus>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="password">Пароль:</label>
|
||||
<input type="password" id="password" name="password" required>
|
||||
</div>
|
||||
|
||||
<button type="submit">Войти</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Показываем ошибку, если она есть в URL
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const error = urlParams.get('error');
|
||||
if (error) {
|
||||
const errorDiv = document.getElementById('error-message');
|
||||
errorDiv.textContent = decodeURIComponent(error);
|
||||
errorDiv.classList.add('show');
|
||||
}
|
||||
|
||||
// Обработка отправки формы
|
||||
document.getElementById('login-form').addEventListener('submit', function(e) {
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
if (!username || !password) {
|
||||
e.preventDefault();
|
||||
const errorDiv = document.getElementById('error-message');
|
||||
errorDiv.textContent = 'Пожалуйста, заполните все поля';
|
||||
errorDiv.classList.add('show');
|
||||
return false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue