fix(lint): resolver type narrowing, NoneType en auth y optimizar sync masivo de moodle en memoria
This commit is contained in:
+13
-13
@@ -86,7 +86,7 @@ def user_add():
|
||||
if not role_obj:
|
||||
errors.append(_('Debes seleccionar un rol válido.'))
|
||||
|
||||
if errors:
|
||||
if errors or not role_obj:
|
||||
for err in errors:
|
||||
flash(err, 'error')
|
||||
return render_template('admin/users/form.html', user=None, roles=roles)
|
||||
@@ -140,7 +140,7 @@ def user_edit(id):
|
||||
if user.id == current_user.id and not is_active:
|
||||
errors.append(_('No puedes desactivar tu propia cuenta mientras estás en sesión.'))
|
||||
|
||||
if errors:
|
||||
if errors or not role_obj:
|
||||
for err in errors:
|
||||
flash(err, 'error')
|
||||
return render_template('admin/users/form.html', user=user, roles=roles)
|
||||
@@ -989,9 +989,9 @@ def occupancy_metrics():
|
||||
from app.models.building import Building
|
||||
from app.models.reservation import Reservation, ReservationStatus
|
||||
import calendar
|
||||
from datetime import datetime, date, timedelta
|
||||
from datetime import datetime, date, timedelta, timezone
|
||||
|
||||
today = datetime.utcnow().date()
|
||||
today = datetime.now(timezone.utc).date()
|
||||
today_start = datetime.combine(today, datetime.min.time())
|
||||
today_end = datetime.combine(today, datetime.max.time())
|
||||
|
||||
@@ -1034,14 +1034,14 @@ def occupancy_metrics():
|
||||
c_res = [r for r in month_res if r.classroom_id == c.id]
|
||||
day_res = [r for r in c_res if today_start <= r.start_time <= today_end]
|
||||
day_mins = sum((min(r.end_time, today_end) - max(r.start_time, today_start)).total_seconds() / 60 for r in day_res)
|
||||
day_pct = min(100, int(round((day_mins / DAILY_OP_MINS) * 100)))
|
||||
day_pct = min(100, round((day_mins / DAILY_OP_MINS) * 100))
|
||||
|
||||
week_res = [r for r in c_res if week_start <= r.start_time <= week_end]
|
||||
week_mins = sum((min(r.end_time, week_end) - max(r.start_time, week_start)).total_seconds() / 60 for r in week_res)
|
||||
week_pct = min(100, int(round((week_mins / WEEKLY_OP_MINS) * 100)))
|
||||
week_pct = min(100, round((week_mins / WEEKLY_OP_MINS) * 100))
|
||||
|
||||
month_mins = sum((min(r.end_time, month_end) - max(r.start_time, month_start)).total_seconds() / 60 for r in c_res)
|
||||
month_pct = min(100, int(round((month_mins / MONTHLY_OP_MINS) * 100)))
|
||||
month_pct = min(100, round((month_mins / MONTHLY_OP_MINS) * 100))
|
||||
|
||||
room_metrics.append({
|
||||
'classroom': c,
|
||||
@@ -1058,9 +1058,9 @@ def occupancy_metrics():
|
||||
low_rooms = list(reversed(room_metrics))[:5]
|
||||
|
||||
# Global averages
|
||||
avg_day_pct = int(round(sum(rm['day_pct'] for rm in room_metrics) / len(room_metrics))) if room_metrics else 0
|
||||
avg_week_pct = int(round(sum(rm['week_pct'] for rm in room_metrics) / len(room_metrics))) if room_metrics else 0
|
||||
avg_month_pct = int(round(sum(rm['month_pct'] for rm in room_metrics) / len(room_metrics))) if room_metrics else 0
|
||||
avg_day_pct = round(sum(rm['day_pct'] for rm in room_metrics) / len(room_metrics)) if room_metrics else 0
|
||||
avg_week_pct = round(sum(rm['week_pct'] for rm in room_metrics) / len(room_metrics)) if room_metrics else 0
|
||||
avg_month_pct = round(sum(rm['month_pct'] for rm in room_metrics) / len(room_metrics)) if room_metrics else 0
|
||||
|
||||
# Virtual classes
|
||||
v_res = [r for r in month_res if vc and r.classroom_id == vc.id]
|
||||
@@ -1448,7 +1448,7 @@ def global_settings():
|
||||
settings = {
|
||||
'smtp': {
|
||||
'host': SystemSetting.get_value('smtp_host', 'smtp.gmail.com'),
|
||||
'port': int(SystemSetting.get_value('smtp_port', 587)),
|
||||
'port': int(SystemSetting.get_value('smtp_port', '587') or 587),
|
||||
'user': SystemSetting.get_value('smtp_user', ''),
|
||||
'password_masked': SystemSetting.get_masked_value('smtp_password', ''),
|
||||
'security': SystemSetting.get_value('smtp_security', 'tls'),
|
||||
@@ -1473,9 +1473,9 @@ def global_settings():
|
||||
'moodle': {
|
||||
'server_url': SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle'),
|
||||
'ws_token_masked': SystemSetting.get_masked_value('moodle_ws_token', ''),
|
||||
'timeout': int(SystemSetting.get_value('moodle_timeout', 10)),
|
||||
'timeout': int(SystemSetting.get_value('moodle_timeout', '10') or 10),
|
||||
'auto_sync_enabled': SystemSetting.get_value('moodle_auto_sync_enabled', 'true') in ['true', 'True', '1', True],
|
||||
'sync_interval_minutes': int(SystemSetting.get_value('moodle_sync_interval_minutes', 15))
|
||||
'sync_interval_minutes': int(SystemSetting.get_value('moodle_sync_interval_minutes', '15') or 15)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,11 +34,11 @@ def get_auth_providers():
|
||||
"""
|
||||
Public endpoint returning active authentication methods and Google client ID for the UI.
|
||||
"""
|
||||
local_val = SystemSetting.get_value('auth_local_enabled', 'true').lower() in ('true', '1')
|
||||
google_val = SystemSetting.get_value('auth_google_enabled', 'false').lower() in ('true', '1')
|
||||
moodle_val = SystemSetting.get_value('auth_moodle_enabled', 'false').lower() in ('true', '1')
|
||||
google_client_id = SystemSetting.get_value('google_client_id', '')
|
||||
demo_access_enabled = SystemSetting.get_value('demo_access_enabled', 'true').lower() in ('true', '1')
|
||||
local_val = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1')
|
||||
google_val = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1')
|
||||
moodle_val = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1')
|
||||
google_client_id = str(SystemSetting.get_value('google_client_id', '') or '')
|
||||
demo_access_enabled = str(SystemSetting.get_value('demo_access_enabled', 'true') or 'true').lower() in ('true', '1')
|
||||
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
@@ -66,7 +66,7 @@ def login():
|
||||
except ValidationError as e:
|
||||
return jsonify({'error': 'ValidationError', 'details': e.errors()}), 400
|
||||
|
||||
local_enabled = SystemSetting.get_value('auth_local_enabled', 'true').lower() in ('true', '1')
|
||||
local_enabled = str(SystemSetting.get_value('auth_local_enabled', 'true') or 'true').lower() in ('true', '1')
|
||||
|
||||
user = user_service.authenticate(dto.email, dto.password)
|
||||
if not user:
|
||||
@@ -133,7 +133,7 @@ def google_auth():
|
||||
Receives Google profile / token data, verifies domain whitelist (AlumnosLS architecture),
|
||||
creates/updates local user and issues JWT.
|
||||
"""
|
||||
google_enabled = SystemSetting.get_value('auth_google_enabled', 'false').lower() in ('true', '1')
|
||||
google_enabled = str(SystemSetting.get_value('auth_google_enabled', 'false') or 'false').lower() in ('true', '1')
|
||||
if not google_enabled:
|
||||
return jsonify({'error': 'Forbidden', 'message': 'El inicio de sesión con Google no está habilitado.'}), 403
|
||||
|
||||
@@ -147,7 +147,7 @@ def google_auth():
|
||||
return jsonify({'error': 'BadRequest', 'message': 'El email de Google es obligatorio.'}), 400
|
||||
|
||||
# Domain restriction check
|
||||
allowed_domains_str = SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar')
|
||||
allowed_domains_str = str(SystemSetting.get_value('google_allowed_domains', 'unicaba.edu.ar') or 'unicaba.edu.ar')
|
||||
allowed_domains = [d.strip().lower() for d in allowed_domains_str.split(',') if d.strip()]
|
||||
|
||||
if allowed_domains and domain.lower() not in allowed_domains:
|
||||
@@ -235,7 +235,7 @@ def moodle_auth():
|
||||
fetches Moodle profile, implements initial role mapping (if new user),
|
||||
and caches profile in Redis.
|
||||
"""
|
||||
moodle_enabled = SystemSetting.get_value('auth_moodle_enabled', 'false').lower() in ('true', '1')
|
||||
moodle_enabled = str(SystemSetting.get_value('auth_moodle_enabled', 'false') or 'false').lower() in ('true', '1')
|
||||
if not moodle_enabled:
|
||||
return jsonify({'error': 'Forbidden', 'message': 'El inicio de sesión con Moodle no está habilitado.'}), 403
|
||||
|
||||
@@ -246,7 +246,7 @@ def moodle_auth():
|
||||
if not username or not password:
|
||||
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('/')
|
||||
server_url = str(SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle') or 'http://10.0.0.207/moodle').rstrip('/')
|
||||
service_name = SystemSetting.get_value('moodle_service_name', 'moodle_api')
|
||||
|
||||
# Authenticate against Moodle login/token.php
|
||||
@@ -393,7 +393,10 @@ def refresh():
|
||||
|
||||
try:
|
||||
payload = JWTService.decode_token(refresh_token, expected_type='refresh')
|
||||
user_id = int(payload.get('sub'))
|
||||
sub = payload.get('sub')
|
||||
if sub is None:
|
||||
return jsonify({'error': 'Unauthorized', 'message': 'Token payload inválido.'}), 401
|
||||
user_id = int(sub)
|
||||
user = user_service.get_by_id(user_id)
|
||||
|
||||
if not user or not user.is_active:
|
||||
|
||||
@@ -42,8 +42,9 @@ class AuditService:
|
||||
|
||||
# 2. Determinar IP de origen
|
||||
if not ip_address and has_request_context():
|
||||
if request.headers.get('X-Forwarded-For'):
|
||||
ip_address = request.headers.get('X-Forwarded-For').split(',')[0].strip()
|
||||
xfwd = request.headers.get('X-Forwarded-For')
|
||||
if xfwd:
|
||||
ip_address = xfwd.split(',')[0].strip()
|
||||
else:
|
||||
ip_address = request.remote_addr
|
||||
|
||||
|
||||
@@ -294,6 +294,11 @@ class MoodleClient:
|
||||
})
|
||||
users_list = moodle_users.get('users', []) if isinstance(moodle_users, dict) else []
|
||||
|
||||
# Cargar todos los usuarios existentes en memoria indexados por email y DNI (O(1) lookup)
|
||||
all_existing_users = User.query.all()
|
||||
user_by_email = {u.email.lower(): u for u in all_existing_users if u.email}
|
||||
user_by_dni = {str(u.document_number): u for u in all_existing_users if u.document_number}
|
||||
|
||||
created_count = 0
|
||||
updated_count = 0
|
||||
|
||||
@@ -317,17 +322,14 @@ class MoodleClient:
|
||||
else:
|
||||
target_role = role_alumno
|
||||
|
||||
# Buscar usuario existente por email o DNI
|
||||
user = None
|
||||
if email:
|
||||
user = User.query.filter(User.email.ilike(email)).first()
|
||||
if not user and dni:
|
||||
user = User.query.filter(User.document_number == dni).first()
|
||||
# Buscar usuario existente en memoria por email o DNI
|
||||
user = user_by_email.get(email) or (user_by_dni.get(dni) if dni else None)
|
||||
|
||||
if user:
|
||||
changed = False
|
||||
if dni and not user.document_number:
|
||||
user.document_number = dni
|
||||
user_by_dni[dni] = user
|
||||
changed = True
|
||||
if firstname and not user.first_name:
|
||||
user.first_name = firstname
|
||||
@@ -356,6 +358,9 @@ class MoodleClient:
|
||||
)
|
||||
new_user.set_password(dni or username)
|
||||
db.session.add(new_user)
|
||||
user_by_email[email] = new_user
|
||||
if dni:
|
||||
user_by_dni[dni] = new_user
|
||||
created_count += 1
|
||||
|
||||
db.session.commit()
|
||||
|
||||
+5
-2
@@ -4,6 +4,9 @@
|
||||
"scripts"
|
||||
],
|
||||
"extraPaths": [
|
||||
"backend"
|
||||
]
|
||||
"backend",
|
||||
"backend/venv/Lib/site-packages"
|
||||
],
|
||||
"venvPath": "backend",
|
||||
"venv": "venv"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user