File size: 9,058 Bytes
12f0507 128f124 12f0507 128f124 12f0507 128f124 12f0507 | 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 | 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')
@admin_bp.route('/users', methods=['GET'])
@require_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]})
@admin_bp.route('/users', methods=['POST'])
@require_admin
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
@admin_bp.route('/users/batch-create', methods=['POST'])
@require_admin
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
@admin_bp.route('/users/<int:uid>/toggle', methods=['PUT'])
@require_admin
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})
@admin_bp.route('/users/<int:uid>/reset-password', methods=['POST'])
@require_admin
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
})
@admin_bp.route('/users/<int:uid>', methods=['PUT'])
@require_admin
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'})
@admin_bp.route('/users/<int:uid>', methods=['DELETE'])
@require_admin
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'})
@admin_bp.route('/sessions', methods=['GET'])
@require_admin
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]})
@admin_bp.route('/sessions/<int:sid>/kick', methods=['POST'])
@require_admin
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'})
@admin_bp.route('/logs', methods=['GET'])
@require_admin
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
})
@admin_bp.route('/stats', methods=['GET'])
@require_admin
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
})
|