"""Microsoft Azure AD / Entra ID authentication for Streamlit. Flow (OAuth2 Authorization Code): 1. User clicks "Sign in with Microsoft" 2. Redirected to Microsoft login (only company tenant allowed) 3. Microsoft redirects back with ?code=... 4. We exchange code for token, extract email from id_token 5. Verify email ends with ALLOWED_EMAIL_DOMAIN 6. Store user in st.session_state """ from __future__ import annotations from dataclasses import dataclass import msal import streamlit as st from app.core.config import settings SCOPES = ["User.Read"] @dataclass class User: email: str name: str is_admin: bool def _authority() -> str: return f"https://login.microsoftonline.com/{settings.ms_tenant_id}" def _msal_app() -> msal.ConfidentialClientApplication: return msal.ConfidentialClientApplication( client_id=settings.ms_client_id, client_credential=settings.ms_client_secret, authority=_authority(), ) def _is_allowed_email(email: str) -> bool: if not settings.allowed_email_domain: return True return email.lower().endswith("@" + settings.allowed_email_domain.lower()) def _is_admin(email: str) -> bool: return email.lower() in settings.admin_email_list def _config_ok() -> bool: return bool( settings.ms_tenant_id and settings.ms_client_id and settings.ms_client_secret ) def _login_screen(require_admin: bool) -> None: # Inject styles + branded login screen from app.ui._styles import inject_styles inject_styles() if not _config_ok(): missing = [] if not settings.ms_tenant_id: missing.append("MS_TENANT_ID") if not settings.ms_client_id: missing.append("MS_CLIENT_ID") if not settings.ms_client_secret: missing.append("MS_CLIENT_SECRET") st.error( f"⚠️ إعدادات Microsoft auth ناقصة. الـ secrets الناقصة: **{', '.join(missing)}**." ) st.stop() from app.ui._styles import logo_html st.markdown( f"""
{logo_html(size_px=96, with_bg=True)}
مؤسسة بنك تنمية المهارات
Qualification Development Bank
"Empowering certified technicians — تمكين الفنيين المعتمدين"
مساعد المعرفة الداخلي — Internal Knowledge Assistant
""", unsafe_allow_html=True, ) auth_url = _msal_app().get_authorization_request_url( SCOPES, redirect_uri=settings.ms_redirect_uri, prompt="select_account", ) col1, col2, col3 = st.columns([1, 2, 1]) with col2: st.link_button( "🔐 تسجيل الدخول بحساب Microsoft", auth_url, type="primary", use_container_width=True, ) st.markdown( f'
' f'الدخول مقصور على إيميلات @{settings.allowed_email_domain}
', unsafe_allow_html=True, ) if require_admin: st.markdown( '
' '🛡️ صفحة المشرفين — حسابك يجب أن يكون في قائمة المشرفين.
', unsafe_allow_html=True, ) # Feature highlights st.markdown('
', unsafe_allow_html=True) cols = st.columns(3) features = [ ("📚", "مراجع موثوقة", "إجابات من ملفات الشركة الرسمية فقط"), ("🔒", "آمن وخاص", "محمي بـ Microsoft SSO"), ("⚡", "سريع ودقيق", "استرجاع ذكي مع ذكر المصدر"), ] for col, (icon, title, desc) in zip(cols, features): with col: st.markdown( f'
' f'
{icon}
' f'
' f'
' f'
', unsafe_allow_html=True, ) st.stop() def _handle_callback() -> User | None: """If we just came back from Microsoft with ?code=..., exchange it for a token.""" code = st.query_params.get("code") if not code: return None result = _msal_app().acquire_token_by_authorization_code( code, scopes=SCOPES, redirect_uri=settings.ms_redirect_uri, ) if "error" in result: st.query_params.clear() st.error(f"فشل تسجيل الدخول: {result.get('error_description', result.get('error'))}") st.stop() claims = result.get("id_token_claims", {}) email = claims.get("preferred_username") or claims.get("email") or "" name = claims.get("name") or email if not email: st.query_params.clear() st.error("لم نستطع استخراج البريد الإلكتروني من حساب Microsoft.") st.stop() if not _is_allowed_email(email): st.query_params.clear() st.error( f"❌ هذا الحساب ({email}) غير مصرح له بالدخول. " f"الدخول مقصور على إيميلات `@{settings.allowed_email_domain}` فقط." ) st.stop() user = User(email=email, name=name, is_admin=_is_admin(email)) st.query_params.clear() return user def require_login(require_admin: bool = False) -> User: """Gate a Streamlit page. Returns the logged-in User; halts the script otherwise. Call this at the top of every page that needs auth. """ if "user" in st.session_state: user: User = st.session_state.user if require_admin and not user.is_admin: st.error(f"❌ {user.email} ليس مشرفاً. هذه الصفحة للمشرفين فقط.") if st.button("تسجيل الخروج"): logout() st.stop() return user user = _handle_callback() if user: st.session_state.user = user st.rerun() _login_screen(require_admin=require_admin) raise RuntimeError("unreachable") # st.stop() halts execution def logout() -> None: st.session_state.pop("user", None) st.session_state.pop("messages", None) logout_url = ( f"{_authority()}/oauth2/v2.0/logout" f"?post_logout_redirect_uri={settings.ms_redirect_uri}" ) st.markdown(f'', unsafe_allow_html=True) st.stop() def render_user_badge() -> None: """Sidebar widget showing who is logged in + logout button.""" user: User | None = st.session_state.get("user") if not user: return role = "🛡️ مشرف" if user.is_admin else "👤 مستخدم" st.markdown(f"**{user.name}**") st.caption(f"{user.email} — {role}") if st.button("🚪 تسجيل الخروج", use_container_width=True): logout()