feat(moodle): conectar moodle_api bidireccional, habilitar login delegado y sincronizacion hacia la app
This commit is contained in:
@@ -2344,6 +2344,12 @@ def update_moodle_settings():
|
||||
SystemSetting.set_value('moodle_auto_sync_enabled', auto_sync, 'Habilitación de sincronización periódica automática', category='sso_moodle')
|
||||
SystemSetting.set_value('moodle_sync_interval_minutes', sync_interval, 'Intervalo en minutos para sincronización periódica', category='sso_moodle')
|
||||
|
||||
if 'auth_moodle_enabled' in data:
|
||||
auth_enabled = 'true' if data.get('auth_moodle_enabled') in [True, 'true', '1', 'on'] else 'false'
|
||||
SystemSetting.set_value('auth_moodle_enabled', auth_enabled, 'Habilitar autenticación delegada con Moodle', category='sso_moodle')
|
||||
if 'service_name' in data:
|
||||
SystemSetting.set_value('moodle_service_name', str(data['service_name']).strip(), 'Nombre del servicio WebService Moodle', category='sso_moodle')
|
||||
|
||||
try:
|
||||
audit = AuditLog(
|
||||
user_id=acting_user.id,
|
||||
@@ -2379,6 +2385,22 @@ def test_moodle_connection():
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@api_admin_bp.route('/moodle/sync-from-moodle', methods=['POST'])
|
||||
@jwt_required
|
||||
def sync_data_from_moodle():
|
||||
"""Sincroniza usuarios, roles y catálogo desde Moodle hacia Admin Edu Space."""
|
||||
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
|
||||
|
||||
from app.services.moodle_client import moodle_client
|
||||
try:
|
||||
res = moodle_client.sync_from_moodle_to_app()
|
||||
return jsonify(res), 200
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e), 'message': f"Error al sincronizar desde Moodle: {str(e)}"}), 500
|
||||
|
||||
|
||||
@api_admin_bp.route('/moodle/queue/stats', methods=['GET'])
|
||||
@jwt_required
|
||||
def get_moodle_queue_stats():
|
||||
|
||||
@@ -247,6 +247,7 @@ def moodle_auth():
|
||||
return jsonify({'error': 'BadRequest', 'message': 'Usuario y contraseña de Moodle son obligatorios.'}), 400
|
||||
|
||||
server_url = SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle').rstrip('/')
|
||||
service_name = SystemSetting.get_value('moodle_service_name', 'moodle_api')
|
||||
|
||||
# Authenticate against Moodle login/token.php
|
||||
token_url = f"{server_url}/login/token.php"
|
||||
@@ -254,9 +255,23 @@ def moodle_auth():
|
||||
resp = requests.post(token_url, data={
|
||||
'username': username,
|
||||
'password': password,
|
||||
'service': 'moodle_mobile_app'
|
||||
'service': service_name
|
||||
}, timeout=10)
|
||||
res_data = resp.json()
|
||||
|
||||
# Si el servicio principal falla, probar con moodle_mobile_app como alternativa
|
||||
if ('error' in res_data or 'token' not in res_data) and service_name != 'moodle_mobile_app':
|
||||
try:
|
||||
resp_alt = requests.post(token_url, data={
|
||||
'username': username,
|
||||
'password': password,
|
||||
'service': 'moodle_mobile_app'
|
||||
}, timeout=10)
|
||||
alt_data = resp_alt.json()
|
||||
if 'token' in alt_data:
|
||||
res_data = alt_data
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error(f"[MoodleAuth] Connection error to Moodle server: {e}")
|
||||
return jsonify({'error': 'ServiceUnavailable', 'message': 'No se pudo conectar con el servidor de Moodle. Intente más tarde.'}), 503
|
||||
@@ -292,8 +307,12 @@ def moodle_auth():
|
||||
firstname = moodle_profile.get('firstname', username) if moodle_profile else username
|
||||
lastname = moodle_profile.get('lastname', 'Moodle') if moodle_profile else 'Moodle'
|
||||
|
||||
# Local user lookup or creation
|
||||
user = User.query.filter((User.email.ilike(email)) | (User.email.ilike(f"{username}@%"))).first()
|
||||
# Local user lookup: match by email, institutional email prefix or document_number (DNI)
|
||||
user = User.query.filter(
|
||||
(User.email.ilike(email)) |
|
||||
(User.email.ilike(f"{username}@%")) |
|
||||
(User.document_number == username)
|
||||
).first()
|
||||
if not user:
|
||||
# Determine initial role: if username is admin or has manager role -> ADMIN, else Docente
|
||||
role_name = 'ADMIN' if username.lower() in ('admin', 'manager') else 'Docente'
|
||||
@@ -304,6 +323,8 @@ def moodle_auth():
|
||||
name=f"{firstname} {lastname}".strip(),
|
||||
first_name=firstname,
|
||||
last_name=lastname,
|
||||
document_type='DNI' if username.isdigit() else 'DNI',
|
||||
document_number=username if username.isdigit() else None,
|
||||
role=role_obj.name if role_obj else role_name,
|
||||
role_id=role_obj.id if role_obj else None,
|
||||
is_active=True
|
||||
|
||||
@@ -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.3"
|
||||
"version": "3.5.4"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user