feat(#11): Implementa estrutura inicial da área administrativa - Cria blueprint administrativo com rotas básicas - Implementa templates base para área administrativa - Adiciona dashboard administrativo - Implementa gerenciamento de usuários - Organiza rotas em pacote separado
This commit is contained in:
4
app.py
4
app.py
@@ -51,6 +51,7 @@ from sqlalchemy.sql import func
|
|||||||
from flask_wtf.csrf import CSRFProtect
|
from flask_wtf.csrf import CSRFProtect
|
||||||
import json
|
import json
|
||||||
from utils.date_utils import validar_data, converter_data, validar_sequencia_datas, calcular_idade
|
from utils.date_utils import validar_data, converter_data, validar_sequencia_datas, calcular_idade
|
||||||
|
from routes.admin import admin_bp # Importar o blueprint administrativo
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
@@ -59,6 +60,9 @@ def create_app():
|
|||||||
app.secret_key = os.getenv('SECRET_KEY', secrets.token_hex(16))
|
app.secret_key = os.getenv('SECRET_KEY', secrets.token_hex(16))
|
||||||
bootstrap = Bootstrap5(app)
|
bootstrap = Bootstrap5(app)
|
||||||
|
|
||||||
|
# Registrar o blueprint administrativo
|
||||||
|
app.register_blueprint(admin_bp)
|
||||||
|
|
||||||
# Configurar CSRF Protection
|
# Configurar CSRF Protection
|
||||||
csrf = CSRFProtect()
|
csrf = CSRFProtect()
|
||||||
csrf.init_app(app)
|
csrf.init_app(app)
|
||||||
|
|||||||
2
routes/__init__.py
Normal file
2
routes/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
# Este arquivo está intencionalmente vazio
|
||||||
|
# Ele é usado para marcar o diretório como um pacote Python
|
||||||
112
routes/admin.py
Normal file
112
routes/admin.py
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
from flask import Blueprint, render_template, flash, redirect, url_for, request, jsonify
|
||||||
|
from functions.database import Usuario, get_db_connection
|
||||||
|
from functions.decorators import require_permission, require_role, require_minimum_role
|
||||||
|
from flask_login import login_required, current_user
|
||||||
|
from sqlalchemy.orm import joinedload
|
||||||
|
import pyotp
|
||||||
|
from werkzeug.security import generate_password_hash
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
admin_bp = Blueprint('admin', __name__, url_prefix='/admin')
|
||||||
|
|
||||||
|
@admin_bp.route('/')
|
||||||
|
@login_required
|
||||||
|
@require_role('ADMIN')
|
||||||
|
def dashboard():
|
||||||
|
"""Dashboard principal da área administrativa"""
|
||||||
|
db = get_db_connection()
|
||||||
|
try:
|
||||||
|
# Carregar estatísticas relevantes
|
||||||
|
total_users = db.query(Usuario).count()
|
||||||
|
active_users = db.query(Usuario).filter(Usuario.is_active == True).count()
|
||||||
|
inactive_users = total_users - active_users
|
||||||
|
|
||||||
|
return render_template(
|
||||||
|
'admin/dashboard.html',
|
||||||
|
total_users=total_users,
|
||||||
|
active_users=active_users,
|
||||||
|
inactive_users=inactive_users
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
@admin_bp.route('/users')
|
||||||
|
@login_required
|
||||||
|
@require_role('ADMIN')
|
||||||
|
def list_users():
|
||||||
|
"""Lista todos os usuários do sistema"""
|
||||||
|
db = get_db_connection()
|
||||||
|
try:
|
||||||
|
users = db.query(Usuario).options(
|
||||||
|
joinedload(Usuario.roles),
|
||||||
|
joinedload(Usuario.militante)
|
||||||
|
).all()
|
||||||
|
return render_template('admin/users.html', users=users)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:user_id>/reset-otp', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@require_role('ADMIN')
|
||||||
|
def reset_user_otp(user_id):
|
||||||
|
"""Reseta o OTP de um usuário"""
|
||||||
|
db = get_db_connection()
|
||||||
|
try:
|
||||||
|
user = db.query(Usuario).get(user_id)
|
||||||
|
if not user:
|
||||||
|
flash('Usuário não encontrado.', 'danger')
|
||||||
|
return redirect(url_for('admin.list_users'))
|
||||||
|
|
||||||
|
# Gerar novo segredo OTP
|
||||||
|
user.otp_secret = pyotp.random_base32()
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
flash(f'OTP resetado com sucesso para {user.email}.', 'success')
|
||||||
|
return redirect(url_for('admin.list_users'))
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:user_id>/reset-password', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@require_role('ADMIN')
|
||||||
|
def reset_user_password(user_id):
|
||||||
|
"""Reseta a senha de um usuário"""
|
||||||
|
db = get_db_connection()
|
||||||
|
try:
|
||||||
|
user = db.query(Usuario).get(user_id)
|
||||||
|
if not user:
|
||||||
|
flash('Usuário não encontrado.', 'danger')
|
||||||
|
return redirect(url_for('admin.list_users'))
|
||||||
|
|
||||||
|
# Gerar nova senha aleatória
|
||||||
|
new_password = secrets.token_urlsafe(8)
|
||||||
|
user.password = generate_password_hash(new_password)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
flash(f'Senha resetada com sucesso. Nova senha: {new_password}', 'success')
|
||||||
|
return redirect(url_for('admin.list_users'))
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:user_id>/toggle-status', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
@require_role('ADMIN')
|
||||||
|
def toggle_user_status(user_id):
|
||||||
|
"""Ativa/desativa um usuário"""
|
||||||
|
db = get_db_connection()
|
||||||
|
try:
|
||||||
|
user = db.query(Usuario).get(user_id)
|
||||||
|
if not user:
|
||||||
|
return jsonify({'success': False, 'message': 'Usuário não encontrado.'})
|
||||||
|
|
||||||
|
user.is_active = not user.is_active
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
status = 'ativado' if user.is_active else 'desativado'
|
||||||
|
return jsonify({
|
||||||
|
'success': True,
|
||||||
|
'message': f'Usuário {status} com sucesso.',
|
||||||
|
'new_status': user.is_active
|
||||||
|
})
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
100
templates/admin/base.html
Normal file
100
templates/admin/base.html
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}Área Administrativa{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container-fluid">
|
||||||
|
<div class="row">
|
||||||
|
<!-- Sidebar -->
|
||||||
|
<nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar">
|
||||||
|
<div class="position-sticky pt-3">
|
||||||
|
<ul class="nav flex-column">
|
||||||
|
<li class="nav-item">
|
||||||
|
<a class="nav-link {% if request.endpoint == 'admin.dashboard' %}active{% endif %}"
|
||||||
|
href="{{ url_for('admin.dashboard') }}">
|
||||||
|
<i class="fas fa-tachometer-alt me-2"></i>
|
||||||
|
Dashboard
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
<li class="nav-item">
|
||||||
|
<a class="nav-link {% if request.endpoint == 'admin.list_users' %}active{% endif %}"
|
||||||
|
href="{{ url_for('admin.list_users') }}">
|
||||||
|
<i class="fas fa-users me-2"></i>
|
||||||
|
Usuários
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
<li class="nav-item">
|
||||||
|
<a class="nav-link" href="{{ url_for('home') }}">
|
||||||
|
<i class="fas fa-arrow-left me-2"></i>
|
||||||
|
Voltar ao Sistema
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<!-- Main content -->
|
||||||
|
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
|
||||||
|
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
|
||||||
|
<h1 class="h2">{% block admin_title %}{% endblock %}</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||||
|
{% if messages %}
|
||||||
|
{% for category, message in messages %}
|
||||||
|
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
|
||||||
|
{{ message }}
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
{% endwith %}
|
||||||
|
|
||||||
|
{% block admin_content %}{% endblock %}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block extra_css %}
|
||||||
|
<style>
|
||||||
|
.sidebar {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
z-index: 100;
|
||||||
|
padding: 48px 0 0;
|
||||||
|
box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar .nav-link {
|
||||||
|
font-weight: 500;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar .nav-link.active {
|
||||||
|
color: #2470dc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar-heading {
|
||||||
|
font-size: .75rem;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
padding-top: 48px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767.98px) {
|
||||||
|
.sidebar {
|
||||||
|
position: static;
|
||||||
|
padding-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
padding-top: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
{% endblock %}
|
||||||
79
templates/admin/dashboard.html
Normal file
79
templates/admin/dashboard.html
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
{% extends "admin/base.html" %}
|
||||||
|
|
||||||
|
{% block admin_title %}Dashboard Administrativo{% endblock %}
|
||||||
|
|
||||||
|
{% block admin_content %}
|
||||||
|
<div class="row">
|
||||||
|
<!-- Card de Total de Usuários -->
|
||||||
|
<div class="col-xl-3 col-md-6 mb-4">
|
||||||
|
<div class="card border-left-primary shadow h-100 py-2">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="row no-gutters align-items-center">
|
||||||
|
<div class="col mr-2">
|
||||||
|
<div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
|
||||||
|
Total de Usuários</div>
|
||||||
|
<div class="h5 mb-0 font-weight-bold text-gray-800">{{ total_users }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-auto">
|
||||||
|
<i class="fas fa-users fa-2x text-gray-300"></i>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Card de Usuários Ativos -->
|
||||||
|
<div class="col-xl-3 col-md-6 mb-4">
|
||||||
|
<div class="card border-left-success shadow h-100 py-2">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="row no-gutters align-items-center">
|
||||||
|
<div class="col mr-2">
|
||||||
|
<div class="text-xs font-weight-bold text-success text-uppercase mb-1">
|
||||||
|
Usuários Ativos</div>
|
||||||
|
<div class="h5 mb-0 font-weight-bold text-gray-800">{{ active_users }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-auto">
|
||||||
|
<i class="fas fa-user-check fa-2x text-gray-300"></i>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Card de Usuários Inativos -->
|
||||||
|
<div class="col-xl-3 col-md-6 mb-4">
|
||||||
|
<div class="card border-left-warning shadow h-100 py-2">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="row no-gutters align-items-center">
|
||||||
|
<div class="col mr-2">
|
||||||
|
<div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
|
||||||
|
Usuários Inativos</div>
|
||||||
|
<div class="h5 mb-0 font-weight-bold text-gray-800">{{ inactive_users }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-auto">
|
||||||
|
<i class="fas fa-user-times fa-2x text-gray-300"></i>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Ações Rápidas -->
|
||||||
|
<div class="row mt-4">
|
||||||
|
<div class="col-12">
|
||||||
|
<div class="card shadow mb-4">
|
||||||
|
<div class="card-header py-3">
|
||||||
|
<h6 class="m-0 font-weight-bold text-primary">Ações Rápidas</h6>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<a href="{{ url_for('admin.list_users') }}" class="btn btn-primary me-2">
|
||||||
|
<i class="fas fa-users me-1"></i>
|
||||||
|
Gerenciar Usuários
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% endblock %}
|
||||||
108
templates/admin/users.html
Normal file
108
templates/admin/users.html
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
{% extends "admin/base.html" %}
|
||||||
|
|
||||||
|
{% block admin_title %}Gerenciamento de Usuários{% endblock %}
|
||||||
|
|
||||||
|
{% block admin_content %}
|
||||||
|
<div class="card shadow mb-4">
|
||||||
|
<div class="card-header py-3">
|
||||||
|
<h6 class="m-0 font-weight-bold text-primary">Lista de Usuários</h6>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-bordered" id="usersTable" width="100%" cellspacing="0">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Email</th>
|
||||||
|
<th>Nome</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th>Último Login</th>
|
||||||
|
<th>Ações</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for user in users %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ user.email }}</td>
|
||||||
|
<td>{{ user.militante.nome if user.militante else 'N/A' }}</td>
|
||||||
|
<td>
|
||||||
|
<span class="badge {% if user.is_active %}bg-success{% else %}bg-danger{% endif %}">
|
||||||
|
{{ 'Ativo' if user.is_active else 'Inativo' }}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td>{{ user.ultimo_login.strftime('%d/%m/%Y %H:%M') if user.ultimo_login else 'Nunca' }}</td>
|
||||||
|
<td>
|
||||||
|
<div class="btn-group" role="group">
|
||||||
|
<!-- Botão de Reset OTP -->
|
||||||
|
<form action="{{ url_for('admin.reset_user_otp', user_id=user.id) }}" method="POST" class="d-inline">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<button type="submit" class="btn btn-warning btn-sm" title="Resetar OTP"
|
||||||
|
onclick="return confirm('Tem certeza que deseja resetar o OTP deste usuário?')">
|
||||||
|
<i class="fas fa-key"></i>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<!-- Botão de Reset Senha -->
|
||||||
|
<form action="{{ url_for('admin.reset_user_password', user_id=user.id) }}" method="POST" class="d-inline ms-1">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<button type="submit" class="btn btn-danger btn-sm" title="Resetar Senha"
|
||||||
|
onclick="return confirm('Tem certeza que deseja resetar a senha deste usuário?')">
|
||||||
|
<i class="fas fa-lock"></i>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<!-- Botão de Ativar/Desativar -->
|
||||||
|
<button class="btn btn-primary btn-sm ms-1" title="{{ 'Desativar' if user.is_active else 'Ativar' }} Usuário"
|
||||||
|
onclick="toggleUserStatus({{ user.id }})">
|
||||||
|
<i class="fas {% if user.is_active %}fa-user-times{% else %}fa-user-check{% endif %}"></i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block extra_js %}
|
||||||
|
<script>
|
||||||
|
function toggleUserStatus(userId) {
|
||||||
|
if (!confirm('Tem certeza que deseja alterar o status deste usuário?')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetch(`/admin/users/${userId}/toggle-status`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRFToken': '{{ csrf_token() }}'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data.success) {
|
||||||
|
// Recarregar a página para mostrar as mudanças
|
||||||
|
location.reload();
|
||||||
|
} else {
|
||||||
|
alert(data.message || 'Erro ao alterar status do usuário');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Error:', error);
|
||||||
|
alert('Erro ao alterar status do usuário');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inicializar DataTable
|
||||||
|
$(document).ready(function() {
|
||||||
|
$('#usersTable').DataTable({
|
||||||
|
language: {
|
||||||
|
url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Portuguese-Brasil.json'
|
||||||
|
},
|
||||||
|
order: [[1, 'asc']]
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
Reference in New Issue
Block a user