import gradio as gr from utils.logger import Logger from utils.database import get_db from data.repository.annotator_repo import AnnotatorRepo from utils.security import verify_password log = Logger() class AuthService: """ Authenticate users against DB and drive Gradio UI states. """ # --------------- LOGIN --------------- # @staticmethod def login(username: str, password: str, session: dict): log.info(f"Login attempt: username={username}") with get_db() as db: repo = AnnotatorRepo(db) user = repo.get_user_by_username(username) if user is None or not user.is_active: log.warning( f"Failed login for username='{username}' (not found / inactive)." ) return ( "❌ Wrong username or password!", gr.update(), gr.update(visible=False), gr.update(value=""), ) if not verify_password(password, user.password): log.warning(f"Failed login; bad password for '{username}'.") return ( "❌ Wrong username or password!", gr.update(), gr.update(visible=False), gr.update(value=""), ) session["user_id"] = user.id session["username"] = user.name log.info(f"User '{username}' logged in successfully.") return ( None, gr.update(visible=False), gr.update(visible=True), gr.update(value=f"👋 Welcome, {user.name}!"), ) # --------------- LOGOUT --------------- # @staticmethod def logout(session: dict): username = session.get("username", "unknown") session.clear() log.info(f"User '{username}' logged out.") return ( gr.update(visible=True), gr.update(visible=False), gr.update(value=""), gr.update(value=""), )