refactor(#11): Integra listagem de usuários no dashboard
This commit is contained in:
134
app.py
134
app.py
@@ -251,7 +251,9 @@ def create_app():
|
||||
session['is_admin'] = user.is_admin
|
||||
print(f"Login realizado: user_id={user.id}, username={user.username}, is_admin={user.is_admin}")
|
||||
|
||||
# Redirecionar para home
|
||||
# Redirecionar para admin.dashboard se for admin, senão para home
|
||||
if user.is_admin:
|
||||
return redirect(url_for("admin.dashboard"))
|
||||
return redirect(url_for("home"))
|
||||
finally:
|
||||
db.close()
|
||||
@@ -1649,136 +1651,6 @@ def create_app():
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@app.route('/dashboard_admin')
|
||||
@login_required
|
||||
def dashboard_admin():
|
||||
"""Rota para o dashboard administrativo"""
|
||||
if not current_user.is_admin:
|
||||
flash('Você não tem permissão para acessar esta página.', 'danger')
|
||||
return redirect(url_for('home'))
|
||||
|
||||
db = get_db_connection()
|
||||
try:
|
||||
# Busca usuários
|
||||
usuarios = db.query(Usuario).all()
|
||||
|
||||
usuarios_data = []
|
||||
for usuario in usuarios:
|
||||
user_data = {
|
||||
'id': usuario.id,
|
||||
'username': usuario.username,
|
||||
'email': usuario.email,
|
||||
'nome': usuario.username, # Usar username como fallback
|
||||
'ativo': usuario.ativo,
|
||||
'is_admin': usuario.is_admin,
|
||||
'last_login': usuario.ultimo_login.strftime('%d/%m/%Y %H:%M') if usuario.ultimo_login else 'Nunca',
|
||||
'nivel': 'Administrador' if usuario.is_admin else 'Usuário'
|
||||
}
|
||||
usuarios_data.append(user_data)
|
||||
|
||||
return render_template(
|
||||
'dashboard_admin.html',
|
||||
usuarios=usuarios_data
|
||||
)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
print(f"Erro no dashboard_admin: {traceback.format_exc()}")
|
||||
flash('Erro ao carregar dados dos usuários. Por favor, tente novamente.', 'danger')
|
||||
return redirect(url_for('home'))
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@app.route('/reset_otp/<int:user_id>', methods=['POST'])
|
||||
@login_required
|
||||
def reset_otp(user_id):
|
||||
if not current_user.is_admin:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Você não tem permissão para resetar OTP.'
|
||||
}), 403
|
||||
|
||||
db = get_db_connection()
|
||||
try:
|
||||
usuario = db.query(Usuario).get(user_id)
|
||||
if not usuario:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Usuário não encontrado.'
|
||||
}), 404
|
||||
|
||||
usuario.otp_secret = pyotp.random_base32()
|
||||
db.commit()
|
||||
|
||||
return jsonify({
|
||||
'success': True
|
||||
})
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}), 500
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@app.route('/reset_password/<int:user_id>', methods=['POST'])
|
||||
@login_required
|
||||
def reset_password(user_id):
|
||||
if not current_user.is_admin:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Você não tem permissão para resetar senhas.'
|
||||
}), 403
|
||||
|
||||
db = get_db_connection()
|
||||
try:
|
||||
usuario = db.query(Usuario).get(user_id)
|
||||
if not usuario:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Usuário não encontrado.'
|
||||
}), 404
|
||||
|
||||
nova_senha = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
|
||||
usuario.set_password(nova_senha)
|
||||
|
||||
try:
|
||||
msg = Message(
|
||||
'Nova Senha - Sistema de Controles',
|
||||
recipients=[usuario.email]
|
||||
)
|
||||
msg.body = f'''Olá {usuario.nome},
|
||||
|
||||
Sua senha foi resetada por um administrador. Sua nova senha é:
|
||||
|
||||
{nova_senha}
|
||||
|
||||
Por favor, altere esta senha no seu próximo login.
|
||||
|
||||
Atenciosamente,
|
||||
Sistema de Controles'''
|
||||
|
||||
mail.send(msg)
|
||||
except Exception as e:
|
||||
print(f"Erro ao enviar email: {str(e)}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Erro ao enviar email com a nova senha.'
|
||||
}), 500
|
||||
|
||||
db.commit()
|
||||
return jsonify({
|
||||
'success': True
|
||||
})
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}), 500
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
return app
|
||||
|
||||
def init_system():
|
||||
|
||||
5
pytest.ini
Normal file
5
pytest.ini
Normal file
@@ -0,0 +1,5 @@
|
||||
[pytest]
|
||||
pythonpath = .
|
||||
testpaths = tests
|
||||
python_files = test_*.py
|
||||
addopts = -v --cov=. --cov-report=term-missing
|
||||
@@ -6,14 +6,28 @@ from sqlalchemy.orm import joinedload
|
||||
import pyotp
|
||||
from werkzeug.security import generate_password_hash
|
||||
import secrets
|
||||
from functools import wraps
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
admin_bp = Blueprint('admin', __name__, url_prefix='/admin')
|
||||
|
||||
def admin_required(f):
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if not current_user.is_admin:
|
||||
flash('Acesso não autorizado.', 'danger')
|
||||
return redirect(url_for('main.index'))
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
@admin_bp.route('/')
|
||||
@login_required
|
||||
@require_role('ADMIN')
|
||||
@admin_required
|
||||
def dashboard():
|
||||
"""Dashboard principal da área administrativa"""
|
||||
"""Dashboard principal da área administrativa com lista de usuários"""
|
||||
db = get_db_connection()
|
||||
try:
|
||||
# Carregar estatísticas relevantes
|
||||
@@ -21,27 +35,27 @@ def dashboard():
|
||||
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:
|
||||
# Carregar lista de usuários
|
||||
users = db.query(Usuario).options(
|
||||
joinedload(Usuario.roles),
|
||||
joinedload(Usuario.militante)
|
||||
).all()
|
||||
return render_template('admin/users.html', users=users)
|
||||
|
||||
return render_template(
|
||||
'admin/dashboard.html',
|
||||
total_users=total_users,
|
||||
active_users=active_users,
|
||||
inactive_users=inactive_users,
|
||||
users=users
|
||||
)
|
||||
except SQLAlchemyError as e:
|
||||
logger.error(f"Erro ao buscar dados do dashboard: {str(e)}")
|
||||
flash('Erro ao carregar dados. Por favor, tente novamente.', 'danger')
|
||||
return render_template('admin/dashboard.html',
|
||||
total_users=0,
|
||||
active_users=0,
|
||||
inactive_users=0,
|
||||
users=[])
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -55,14 +69,14 @@ def reset_user_otp(user_id):
|
||||
user = db.query(Usuario).get(user_id)
|
||||
if not user:
|
||||
flash('Usuário não encontrado.', 'danger')
|
||||
return redirect(url_for('admin.list_users'))
|
||||
return redirect(url_for('admin.dashboard'))
|
||||
|
||||
# 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'))
|
||||
return redirect(url_for('admin.dashboard'))
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -76,7 +90,7 @@ def reset_user_password(user_id):
|
||||
user = db.query(Usuario).get(user_id)
|
||||
if not user:
|
||||
flash('Usuário não encontrado.', 'danger')
|
||||
return redirect(url_for('admin.list_users'))
|
||||
return redirect(url_for('admin.dashboard'))
|
||||
|
||||
# Gerar nova senha aleatória
|
||||
new_password = secrets.token_urlsafe(8)
|
||||
@@ -84,7 +98,7 @@ def reset_user_password(user_id):
|
||||
db.commit()
|
||||
|
||||
flash(f'Senha resetada com sucesso. Nova senha: {new_password}', 'success')
|
||||
return redirect(url_for('admin.list_users'))
|
||||
return redirect(url_for('admin.dashboard'))
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
17
run_tests.sh
Executable file
17
run_tests.sh
Executable file
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Criar e ativar ambiente virtual
|
||||
python -m venv venv
|
||||
source venv/bin/activate
|
||||
|
||||
# Instalar dependências de teste
|
||||
pip install -r tests/requirements-test.txt
|
||||
|
||||
# Instalar o projeto em modo de desenvolvimento
|
||||
pip install -e .
|
||||
|
||||
# Executar testes
|
||||
python -m pytest
|
||||
|
||||
# Desativar ambiente virtual
|
||||
deactivate
|
||||
18
setup.py
Normal file
18
setup.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="controles",
|
||||
version="0.1",
|
||||
packages=find_packages(),
|
||||
include_package_data=True,
|
||||
install_requires=[
|
||||
'flask',
|
||||
'flask-login',
|
||||
'flask-sqlalchemy',
|
||||
'flask-wtf',
|
||||
'flask-mail',
|
||||
'python-dotenv',
|
||||
'pyotp',
|
||||
'qrcode',
|
||||
],
|
||||
)
|
||||
@@ -98,3 +98,5 @@ main {
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_scripts %}{% endblock %}
|
||||
@@ -1,79 +1,117 @@
|
||||
{% extends "admin/base.html" %}
|
||||
|
||||
{% block admin_title %}Dashboard Administrativo{% endblock %}
|
||||
{% block 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">
|
||||
{% block content %}
|
||||
<div class="row mb-4">
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<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>
|
||||
<h5 class="card-title">Total de Usuários</h5>
|
||||
<p class="card-text display-4">{{ total_users }}</p>
|
||||
<i class="fas fa-users fa-2x text-primary"></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="col-md-4">
|
||||
<div class="card">
|
||||
<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>
|
||||
<h5 class="card-title">Usuários Ativos</h5>
|
||||
<p class="card-text display-4">{{ active_users }}</p>
|
||||
<i class="fas fa-user-check fa-2x text-success"></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="col-md-4">
|
||||
<div class="card">
|
||||
<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>
|
||||
<h5 class="card-title">Usuários Inativos</h5>
|
||||
<p class="card-text display-4">{{ inactive_users }}</p>
|
||||
<i class="fas fa-user-times fa-2x text-danger"></i>
|
||||
</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 class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0">Gerenciamento de Usuários</h5>
|
||||
</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 class="table-responsive">
|
||||
<table id="users-table" class="table table-striped">
|
||||
<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.name }}</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.last_login.strftime('%d/%m/%Y %H:%M') if user.last_login else 'Nunca' }}</td>
|
||||
<td>
|
||||
<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" onclick="return confirm('Confirma o reset do OTP deste usuário?')">
|
||||
<i class="fas fa-key"></i> Reset OTP
|
||||
</button>
|
||||
</form>
|
||||
<form action="{{ url_for('admin.reset_user_password', user_id=user.id) }}" method="post" class="d-inline">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button type="submit" class="btn btn-info btn-sm" onclick="return confirm('Confirma o reset da senha deste usuário?')">
|
||||
<i class="fas fa-lock"></i> Reset Senha
|
||||
</button>
|
||||
</form>
|
||||
<button onclick="toggleUserStatus({{ user.id }})" class="btn btn-{% if user.is_active %}danger{% else %}success{% endif %} btn-sm">
|
||||
<i class="fas fa-{% if user.is_active %}user-times{% else %}user-check{% endif %}"></i>
|
||||
{{ "Desativar" if user.is_active else "Ativar" }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script>
|
||||
function toggleUserStatus(userId) {
|
||||
if (confirm('Deseja alterar o status deste usuário?')) {
|
||||
fetch(`/admin/users/${userId}/toggle-status`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': '{{ csrf_token() }}'
|
||||
}
|
||||
}).then(response => {
|
||||
if (response.ok) {
|
||||
window.location.reload();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
$(document).ready(function() {
|
||||
$('#users-table').DataTable({
|
||||
language: {
|
||||
url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/pt-BR.json'
|
||||
},
|
||||
order: [[1, 'asc']]
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,108 +0,0 @@
|
||||
{% 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 %}
|
||||
@@ -600,7 +600,7 @@
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="dropdown-item" href="{{ url_for('dashboard_admin') }}">
|
||||
<a class="dropdown-item" href="{{ url_for('admin.dashboard') }}">
|
||||
<i class="fas fa-cog fa fa-cog fa-solid fa-cog" style="display: inline-block !important; visibility: visible !important;"></i>Administração
|
||||
</a>
|
||||
</li>
|
||||
|
||||
33
tests/conftest.py
Normal file
33
tests/conftest.py
Normal file
@@ -0,0 +1,33 @@
|
||||
import pytest
|
||||
from app import create_app
|
||||
from functions.database import init_database, get_db_connection
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
"""Cria uma instância do app para testes"""
|
||||
app = create_app()
|
||||
app.config['TESTING'] = True
|
||||
app.config['WTF_CSRF_ENABLED'] = False
|
||||
|
||||
# Inicializar banco de dados de teste
|
||||
init_database()
|
||||
|
||||
yield app
|
||||
|
||||
# Limpar banco após os testes
|
||||
db = get_db_connection()
|
||||
try:
|
||||
db.execute('DROP TABLE IF EXISTS usuarios CASCADE')
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@pytest.fixture
|
||||
def client(app):
|
||||
"""Cria um cliente de teste"""
|
||||
return app.test_client()
|
||||
|
||||
@pytest.fixture
|
||||
def runner(app):
|
||||
"""Cria um runner de CLI para testes"""
|
||||
return app.test_cli_runner()
|
||||
4
tests/requirements-test.txt
Normal file
4
tests/requirements-test.txt
Normal file
@@ -0,0 +1,4 @@
|
||||
pytest==7.4.3
|
||||
pytest-cov==4.1.0
|
||||
pytest-flask==1.3.0
|
||||
coverage==7.3.2
|
||||
100
tests/test_admin_routes.py
Normal file
100
tests/test_admin_routes.py
Normal file
@@ -0,0 +1,100 @@
|
||||
import pytest
|
||||
from flask import url_for
|
||||
from functions.database import Usuario, get_db_connection
|
||||
from werkzeug.security import generate_password_hash
|
||||
import json
|
||||
|
||||
@pytest.fixture
|
||||
def admin_user(client):
|
||||
"""Fixture que cria um usuário admin para testes"""
|
||||
db = get_db_connection()
|
||||
try:
|
||||
admin = Usuario(
|
||||
username='admin_test',
|
||||
email='admin@test.com',
|
||||
password_hash=generate_password_hash('admin123'),
|
||||
is_admin=True,
|
||||
is_active=True
|
||||
)
|
||||
db.add(admin)
|
||||
db.commit()
|
||||
return admin
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@pytest.fixture
|
||||
def auth_admin_client(client, admin_user):
|
||||
"""Fixture que retorna um cliente autenticado como admin"""
|
||||
client.post('/login', data={
|
||||
'email': 'admin@test.com',
|
||||
'password': 'admin123'
|
||||
})
|
||||
return client
|
||||
|
||||
def test_dashboard_access_sem_login(client):
|
||||
"""Testa acesso ao dashboard sem login"""
|
||||
response = client.get('/admin/')
|
||||
assert response.status_code == 302
|
||||
assert '/login' in response.headers['Location']
|
||||
|
||||
def test_dashboard_access_com_login(auth_admin_client):
|
||||
"""Testa acesso ao dashboard com login de admin"""
|
||||
response = auth_admin_client.get('/admin/')
|
||||
assert response.status_code == 200
|
||||
assert b'Dashboard Administrativo' in response.data
|
||||
|
||||
def test_lista_usuarios(auth_admin_client):
|
||||
"""Testa listagem de usuários"""
|
||||
response = auth_admin_client.get('/admin/users')
|
||||
assert response.status_code == 200
|
||||
assert b'Lista de' in response.data
|
||||
assert b'admin_test' in response.data
|
||||
|
||||
def test_reset_otp(auth_admin_client, admin_user):
|
||||
"""Testa reset de OTP"""
|
||||
response = auth_admin_client.post(f'/admin/users/{admin_user.id}/reset-otp')
|
||||
assert response.status_code == 302
|
||||
assert 'success' in response.headers['Location']
|
||||
|
||||
def test_reset_password(auth_admin_client, admin_user):
|
||||
"""Testa reset de senha"""
|
||||
response = auth_admin_client.post(f'/admin/users/{admin_user.id}/reset-password')
|
||||
assert response.status_code == 302
|
||||
assert 'success' in response.headers['Location']
|
||||
|
||||
def test_toggle_status(auth_admin_client, admin_user):
|
||||
"""Testa alteração de status do usuário"""
|
||||
response = auth_admin_client.post(
|
||||
f'/admin/users/{admin_user.id}/toggle-status',
|
||||
headers={'Content-Type': 'application/json'}
|
||||
)
|
||||
data = json.loads(response.data)
|
||||
assert response.status_code == 200
|
||||
assert data['success'] is True
|
||||
|
||||
def test_acesso_nao_admin(client):
|
||||
"""Testa acesso de usuário não admin"""
|
||||
db = get_db_connection()
|
||||
try:
|
||||
# Criar usuário normal
|
||||
user = Usuario(
|
||||
username='normal_user',
|
||||
email='user@test.com',
|
||||
password_hash=generate_password_hash('user123'),
|
||||
is_admin=False,
|
||||
is_active=True
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
|
||||
# Login
|
||||
client.post('/login', data={
|
||||
'email': 'user@test.com',
|
||||
'password': 'user123'
|
||||
})
|
||||
|
||||
# Tentar acessar área admin
|
||||
response = client.get('/admin/')
|
||||
assert response.status_code == 403
|
||||
finally:
|
||||
db.close()
|
||||
Reference in New Issue
Block a user