Download api/admin.py from QBANK/OFTQUEST: direct link, hf CLI and curl.
- Browser
- Download file 9.06 kB
-
https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/api/admin.py
- Command line
-
hf download hf://spaces/QBANK/OFTQUEST/api/admin.py
-
curl -L -o admin.py https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/api/admin.py
9.06 kB
| import json | |
| import random | |
| import string | |
| from flask import Blueprint, request, jsonify | |
| from werkzeug.security import generate_password_hash | |
| from models.database import get_db | |
| from auth.middleware import require_admin | |
| from auth.session_manager import invalidate_user_sessions | |
| def _generate_random_password(length=8): | |
| """Generate a random password with letters and digits.""" | |
| chars = string.ascii_letters + string.digits | |
| return ''.join(random.choices(chars, k=length)) | |
| admin_bp = Blueprint('admin', __name__, url_prefix='/api/admin') | |
| def list_users(): | |
| db = get_db() | |
| users = db.execute(""" | |
| SELECT u.id, u.email, u.display_name, u.role, u.is_active, u.created_at, | |
| (SELECT COUNT(*) FROM session_log WHERE user_id = u.id) as total_sessions, | |
| (SELECT SUM(duration_seconds) FROM session_log WHERE user_id = u.id) as total_time, | |
| (SELECT MAX(login_time) FROM session_log WHERE user_id = u.id) as last_login | |
| FROM users u | |
| ORDER BY u.created_at DESC | |
| """).fetchall() | |
| return jsonify({'users': [dict(u) for u in users]}) | |
| def create_user(): | |
| data = request.get_json() | |
| if not data or not data.get('email') or not data.get('password'): | |
| return jsonify({'error': 'Email e senha são obrigatórios'}), 400 | |
| email = data['email'].strip().lower() | |
| password = data['password'] | |
| display_name = data.get('display_name', '') | |
| role = data.get('role', 'user') | |
| if role not in ('user', 'admin'): | |
| return jsonify({'error': 'Role inválida'}), 400 | |
| db = get_db() | |
| existing = db.execute("SELECT id FROM users WHERE email = ?", (email,)).fetchone() | |
| if existing: | |
| return jsonify({'error': 'Email já cadastrado'}), 409 | |
| db.execute( | |
| "INSERT INTO users (email, password_hash, display_name, role) VALUES (?, ?, ?, ?)", | |
| (email, generate_password_hash(password), display_name, role) | |
| ) | |
| db.commit() | |
| return jsonify({'message': f'Usuário {email} criado com sucesso'}), 201 | |
| def batch_create_users(): | |
| data = request.get_json() | |
| if not data or not data.get('users'): | |
| return jsonify({'error': 'Lista de usuários é obrigatória'}), 400 | |
| user_list = data['users'] | |
| if not isinstance(user_list, list) or len(user_list) == 0: | |
| return jsonify({'error': 'Lista vazia'}), 400 | |
| if len(user_list) > 100: | |
| return jsonify({'error': 'Máximo de 100 usuários por lote'}), 400 | |
| db = get_db() | |
| results = [] | |
| errors = [] | |
| for item in user_list: | |
| email = (item.get('email') or '').strip().lower() | |
| name = (item.get('name') or '').strip() | |
| if not email: | |
| errors.append({'email': email, 'error': 'Email vazio'}) | |
| continue | |
| existing = db.execute("SELECT id FROM users WHERE email = ?", (email,)).fetchone() | |
| if existing: | |
| errors.append({'email': email, 'error': 'Email já cadastrado'}) | |
| continue | |
| password = _generate_random_password() | |
| db.execute( | |
| "INSERT INTO users (email, password_hash, display_name, role) VALUES (?, ?, ?, ?)", | |
| (email, generate_password_hash(password), name, 'user') | |
| ) | |
| results.append({'email': email, 'name': name, 'password': password}) | |
| db.commit() | |
| return jsonify({ | |
| 'created': results, | |
| 'errors': errors, | |
| 'total_created': len(results), | |
| 'total_errors': len(errors) | |
| }), 201 | |
| def toggle_user(uid): | |
| db = get_db() | |
| user = db.execute("SELECT id, is_active, role FROM users WHERE id = ?", (uid,)).fetchone() | |
| if not user: | |
| return jsonify({'error': 'Usuário não encontrado'}), 404 | |
| new_status = 0 if user['is_active'] else 1 | |
| db.execute("UPDATE users SET is_active = ? WHERE id = ?", (new_status, uid)) | |
| db.commit() | |
| if new_status == 0: | |
| invalidate_user_sessions(uid, 'admin_deactivated') | |
| label = 'ativado' if new_status else 'desativado' | |
| return jsonify({'message': f'Usuário {label}', 'is_active': new_status}) | |
| def reset_user_password(uid): | |
| db = get_db() | |
| user = db.execute("SELECT id, email FROM users WHERE id = ?", (uid,)).fetchone() | |
| if not user: | |
| return jsonify({'error': 'Usuário não encontrado'}), 404 | |
| new_password = _generate_random_password() | |
| db.execute( | |
| "UPDATE users SET password_hash = ? WHERE id = ?", | |
| (generate_password_hash(new_password), uid) | |
| ) | |
| db.commit() | |
| return jsonify({ | |
| 'message': f'Senha de {user["email"]} redefinida', | |
| 'email': user['email'], | |
| 'new_password': new_password | |
| }) | |
| def update_user(uid): | |
| data = request.get_json() | |
| db = get_db() | |
| user = db.execute("SELECT * FROM users WHERE id = ?", (uid,)).fetchone() | |
| if not user: | |
| return jsonify({'error': 'Usuário não encontrado'}), 404 | |
| updates = [] | |
| params = [] | |
| if 'display_name' in data: | |
| updates.append("display_name = ?") | |
| params.append(data['display_name']) | |
| if 'is_active' in data: | |
| updates.append("is_active = ?") | |
| params.append(1 if data['is_active'] else 0) | |
| if not data['is_active']: | |
| invalidate_user_sessions(uid, 'admin_deactivated') | |
| if 'password' in data and data['password']: | |
| updates.append("password_hash = ?") | |
| params.append(generate_password_hash(data['password'])) | |
| if 'role' in data and data['role'] in ('user', 'admin'): | |
| updates.append("role = ?") | |
| params.append(data['role']) | |
| if updates: | |
| params.append(uid) | |
| db.execute(f"UPDATE users SET {', '.join(updates)} WHERE id = ?", params) | |
| db.commit() | |
| return jsonify({'message': 'Usuário atualizado'}) | |
| def deactivate_user(uid): | |
| db = get_db() | |
| db.execute("UPDATE users SET is_active = 0 WHERE id = ?", (uid,)) | |
| db.commit() | |
| invalidate_user_sessions(uid, 'admin_deactivated') | |
| return jsonify({'message': 'Usuário desativado'}) | |
| def active_sessions(): | |
| db = get_db() | |
| sessions = db.execute(""" | |
| SELECT s.id, s.user_id, u.email, u.display_name, s.ip_address, | |
| s.device_info, s.login_time, s.last_heartbeat | |
| FROM sessions s | |
| JOIN users u ON s.user_id = u.id | |
| WHERE s.is_active = 1 | |
| ORDER BY s.login_time DESC | |
| """).fetchall() | |
| return jsonify({'sessions': [dict(s) for s in sessions]}) | |
| def kick_session(sid): | |
| db = get_db() | |
| session = db.execute("SELECT token, user_id FROM sessions WHERE id = ? AND is_active = 1", (sid,)).fetchone() | |
| if not session: | |
| return jsonify({'error': 'Sessão não encontrada'}), 404 | |
| from auth.session_manager import invalidate_session | |
| invalidate_session(session['token'], 'admin_kick') | |
| from sockets.heartbeat import notify_session_kicked | |
| notify_session_kicked(session['token']) | |
| return jsonify({'message': 'Sessão encerrada'}) | |
| def session_logs(): | |
| page = request.args.get('page', 1, type=int) | |
| per_page = request.args.get('per_page', 50, type=int) | |
| user_filter = request.args.get('user_id', None, type=int) | |
| offset = (page - 1) * per_page | |
| db = get_db() | |
| where = "" | |
| params = [] | |
| if user_filter: | |
| where = "WHERE user_id = ?" | |
| params.append(user_filter) | |
| total = db.execute(f"SELECT COUNT(*) as c FROM session_log {where}", params).fetchone()['c'] | |
| params.extend([per_page, offset]) | |
| logs = db.execute(f""" | |
| SELECT * FROM session_log {where} | |
| ORDER BY login_time DESC | |
| LIMIT ? OFFSET ? | |
| """, params).fetchall() | |
| return jsonify({ | |
| 'logs': [dict(l) for l in logs], | |
| 'total': total, | |
| 'page': page, | |
| 'per_page': per_page | |
| }) | |
| def dashboard_stats(): | |
| db = get_db() | |
| total_users = db.execute("SELECT COUNT(*) as c FROM users WHERE is_active = 1").fetchone()['c'] | |
| total_questions = db.execute("SELECT COUNT(*) as c FROM questions").fetchone()['c'] | |
| active_sessions = db.execute("SELECT COUNT(*) as c FROM sessions WHERE is_active = 1").fetchone()['c'] | |
| total_topics = db.execute("SELECT COUNT(DISTINCT track_slug) as c FROM questions").fetchone()['c'] | |
| return jsonify({ | |
| 'total_users': total_users, | |
| 'total_questions': total_questions, | |
| 'active_sessions': active_sessions, | |
| 'total_topics': total_topics | |
| }) | |