|
|
import os |
|
|
import yaml |
|
|
import streamlit as st |
|
|
from typing import Optional, Dict, Any |
|
|
import streamlit_authenticator as stauth |
|
|
|
|
|
class AuthManager: |
|
|
"""Gestiona la autenticación de usuarios con Google OAuth""" |
|
|
|
|
|
def __init__(self): |
|
|
self.config_path = "auth_config.yaml" |
|
|
self.authenticator = None |
|
|
self.load_config() |
|
|
|
|
|
def load_config(self): |
|
|
"""Carga la configuración de autenticación""" |
|
|
try: |
|
|
with open(self.config_path, 'r', encoding='utf-8') as file: |
|
|
self.config = yaml.safe_load(file) |
|
|
except FileNotFoundError: |
|
|
|
|
|
self.config = { |
|
|
'credentials': { |
|
|
'usernames': { |
|
|
'google_oauth_user': { |
|
|
'email': 'google_oauth_user', |
|
|
'name': 'Google User', |
|
|
'password': 'oauth_password' |
|
|
} |
|
|
} |
|
|
}, |
|
|
'cookie': { |
|
|
'expiry_days': 30, |
|
|
'key': 'veureu_auth_cookie_key_change_in_production', |
|
|
'name': 'veureu_auth_cookie' |
|
|
}, |
|
|
'preauthorized': {'emails': []} |
|
|
} |
|
|
self.save_config() |
|
|
|
|
|
def save_config(self): |
|
|
"""Guarda la configuración de autenticación""" |
|
|
with open(self.config_path, 'w', encoding='utf-8') as file: |
|
|
yaml.dump(self.config, file, default_flow_style=False) |
|
|
|
|
|
def initialize_authenticator(self): |
|
|
"""Inicializa el autenticador de Streamlit""" |
|
|
if self.authenticator is None: |
|
|
self.authenticator = stauth.Authenticate( |
|
|
self.config['credentials'], |
|
|
self.config['cookie']['name'], |
|
|
self.config['cookie']['key'], |
|
|
self.config['cookie']['expiry_days'] |
|
|
) |
|
|
return self.authenticator |
|
|
|
|
|
def show_login_section(self, consent_text: str) -> Optional[str]: |
|
|
""" |
|
|
Muestra sección de login con consentimientos |
|
|
|
|
|
Args: |
|
|
consent_text: Texto con los términos y condiciones |
|
|
|
|
|
Returns: |
|
|
Email del usuario autenticado o None |
|
|
""" |
|
|
authenticator = self.initialize_authenticator() |
|
|
|
|
|
|
|
|
st.markdown("### 📋 Antes de subir tu vídeo") |
|
|
|
|
|
|
|
|
with st.expander("📜 Términos y Condiciones", expanded=True): |
|
|
st.markdown(consent_text) |
|
|
|
|
|
st.markdown("#### 🎯 Para continuar, por favor identifícate:") |
|
|
|
|
|
|
|
|
st.info("🔧 **Login con Google OAuth** - En producción esto conectará con tu cuenta Google") |
|
|
st.info("💡 **Modo demostración** - Usa las credenciales siguientes:") |
|
|
|
|
|
col1, col2 = st.columns(2) |
|
|
with col1: |
|
|
st.code("Usuario: google_oauth_user") |
|
|
with col2: |
|
|
st.code("Contraseña: oauth_password") |
|
|
|
|
|
|
|
|
name, authentication_status, username = authenticator.login( |
|
|
'Login para acceder al servicio', 'main' |
|
|
) |
|
|
|
|
|
if authentication_status: |
|
|
st.success(f"✅ Bienvenido/a, {name}!") |
|
|
st.success("🎉 **Identificación completada** - Has aceptado los términos y condiciones mediante tu login.") |
|
|
st.balloons() |
|
|
return username |
|
|
elif authentication_status == False: |
|
|
st.error('❌ Credenciales incorrectos. Por favor inténtalo de nuevo.') |
|
|
st.warning("💡 Usa: google_oauth_user / oauth_password") |
|
|
else: |
|
|
st.warning('⚠️ Por favor introduce tus credenciales para continuar') |
|
|
|
|
|
return None |
|
|
|
|
|
def logout(self): |
|
|
"""Cierra la sesión del usuario""" |
|
|
if self.authenticator: |
|
|
self.authenticator.logout('Logout', 'main') |
|
|
|
|
|
def is_authenticated(self) -> bool: |
|
|
"""Verifica si el usuario está autenticado""" |
|
|
return 'authentication_status' in st.session_state and st.session_state.authentication_status |
|
|
|
|
|
def get_current_user(self) -> Optional[str]: |
|
|
"""Obtiene el email del usuario actual""" |
|
|
if self.is_authenticated(): |
|
|
return st.session_state.get('username') |
|
|
return None |
|
|
|
|
|
|
|
|
auth_manager = AuthManager() |
|
|
|