feat(security): implementar autenticacion por API Key institucional para Moodle, purga de tareas y hardening
This commit is contained in:
@@ -6,7 +6,7 @@ from flask_babel import Babel, gettext as _
|
||||
from config.config import Config
|
||||
|
||||
# Initialize extensions
|
||||
__version__ = "3.5.4"
|
||||
__version__ = "3.5.5"
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
cors = CORS()
|
||||
|
||||
@@ -2385,14 +2385,94 @@ def test_moodle_connection():
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@api_admin_bp.route('/moodle/sync-from-moodle', methods=['POST'])
|
||||
def _verify_moodle_api_key_or_admin() -> bool:
|
||||
"""Valida si la petición proviene de Moodle vía API Key autorizada o de un administrador."""
|
||||
from app.models.setting import SystemSetting
|
||||
import secrets
|
||||
|
||||
# Verificar Header de API Key (X-API-Key o Authorization: ApiKey ...)
|
||||
api_key_header = request.headers.get('X-API-Key') or request.headers.get('X-Moodle-Api-Key')
|
||||
if not api_key_header and request.headers.get('Authorization', '').startswith('ApiKey '):
|
||||
api_key_header = request.headers.get('Authorization', '').replace('ApiKey ', '').strip()
|
||||
|
||||
if api_key_header:
|
||||
saved_key = SystemSetting.get_decrypted_value('moodle_api_key', '')
|
||||
if saved_key and secrets.compare_digest(api_key_header.strip(), saved_key.strip()):
|
||||
return True
|
||||
|
||||
acting_user = getattr(g, 'jwt_user', None)
|
||||
if acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN'):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
@api_admin_bp.route('/settings/moodle/api-key', methods=['GET'])
|
||||
@jwt_required
|
||||
def sync_data_from_moodle():
|
||||
"""Sincroniza usuarios, roles y catálogo desde Moodle hacia Admin Edu Space."""
|
||||
def get_moodle_api_key():
|
||||
"""Retorna la clave API institucional configurada para Moodle."""
|
||||
acting_user = getattr(g, 'jwt_user', None)
|
||||
if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')):
|
||||
return jsonify({'error': 'Forbidden', 'message': 'Acceso no autorizado.'}), 403
|
||||
|
||||
import secrets
|
||||
from app.models.setting import SystemSetting
|
||||
api_key = SystemSetting.get_decrypted_value('moodle_api_key', '')
|
||||
if not api_key:
|
||||
api_key = secrets.token_hex(32)
|
||||
SystemSetting.set_encrypted_value('moodle_api_key', api_key, 'Clave API secreta para integración bidireccional segura con Moodle', category='sso_moodle')
|
||||
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'api_key': api_key,
|
||||
'header_name': 'X-API-Key',
|
||||
'sync_endpoint': '/api/v1/admin/settings/moodle/sync'
|
||||
}), 200
|
||||
|
||||
|
||||
@api_admin_bp.route('/settings/moodle/api-key/regenerate', methods=['POST'])
|
||||
@jwt_required
|
||||
def regenerate_moodle_api_key():
|
||||
"""Regenera una nueva clave API criptográfica para sincronizaciones seguras con Moodle."""
|
||||
acting_user = getattr(g, 'jwt_user', None)
|
||||
if not (acting_user and (acting_user.is_admin() or getattr(acting_user, 'role', '').upper() == 'ADMIN')):
|
||||
return jsonify({'error': 'Forbidden', 'message': 'Acceso no autorizado.'}), 403
|
||||
|
||||
import secrets
|
||||
from app.models.setting import SystemSetting
|
||||
new_key = secrets.token_hex(32)
|
||||
SystemSetting.set_encrypted_value('moodle_api_key', new_key, 'Clave API secreta para integración bidireccional segura con Moodle', category='sso_moodle')
|
||||
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'api_key': new_key,
|
||||
'message': 'Clave API de Moodle regenerada exitosamente.'
|
||||
}), 200
|
||||
|
||||
|
||||
@api_admin_bp.route('/moodle/sync-from-moodle', methods=['POST'])
|
||||
@api_admin_bp.route('/settings/moodle/sync', methods=['POST'])
|
||||
def sync_data_from_moodle():
|
||||
"""Sincroniza usuarios, roles y catálogo desde Moodle hacia Admin Edu Space (autenticado por JWT o X-API-Key)."""
|
||||
# Intentar cargar JWT si está presente
|
||||
auth_header = request.headers.get('Authorization', '')
|
||||
if auth_header.startswith('Bearer '):
|
||||
token = auth_header.replace('Bearer ', '').strip()
|
||||
try:
|
||||
from app.services.jwt_service import JWTService
|
||||
from app.services.user_service import user_service
|
||||
payload = JWTService.decode_token(token, expected_type='access')
|
||||
sub = payload.get('sub')
|
||||
if sub:
|
||||
user = user_service.get_by_id(int(sub))
|
||||
if user and user.is_active:
|
||||
g.jwt_user = user
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not _verify_moodle_api_key_or_admin():
|
||||
return jsonify({'error': 'Forbidden', 'message': 'Acceso no autorizado. Se requiere token JWT de ADMIN o header X-API-Key válido.'}), 403
|
||||
|
||||
from app.services.moodle_client import moodle_client
|
||||
try:
|
||||
res = moodle_client.sync_from_moodle_to_app()
|
||||
|
||||
@@ -7,7 +7,7 @@ OPENAPI_SPEC = {
|
||||
"info": {
|
||||
"title": "Edu-Space REST API",
|
||||
"description": "Enterprise Academic & Physical Space Management REST API with JWT Authentication and Role-Based Access Control.",
|
||||
"version": "3.5.4"
|
||||
"version": "3.5.5"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user