File size: 4,571 Bytes
1a61999
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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:
            # Configuración por defecto si no existe el archivo
            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()
        
        # Crear sección de login
        st.markdown("### 📋 Antes de subir tu vídeo")
        
        # Mostrar términos y condiciones
        with st.expander("📜 Términos y Condiciones", expanded=True):
            st.markdown(consent_text)
        
        st.markdown("#### 🎯 Para continuar, por favor identifícate:")
        
        # Información sobre Google OAuth
        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")
        
        # Intentar autenticación
        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

# Instancia global del gestor de autenticación
auth_manager = AuthManager()