Spaces:
Sleeping
Sleeping
Download app/core/auth.py from QDB95/qdb-knowledge-bot: direct link, hf CLI and curl.
- Browser
- Download file 7.81 kB
-
https://huggingface.co/spaces/QDB95/qdb-knowledge-bot/resolve/main/app/core/auth.py
- Command line
-
hf download hf://spaces/QDB95/qdb-knowledge-bot/app/core/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/QDB95/qdb-knowledge-bot/resolve/main/app/core/auth.py
7.81 kB
| """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"] | |
| 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""" | |
| <div class="qdb-login-hero"> | |
| <div style="margin-bottom:1.5rem;">{logo_html(size_px=96, with_bg=True)}</div> | |
| <div class="qdb-login-title">مؤسسة بنك تنمية المهارات</div> | |
| <div class="qdb-login-subtitle">Qualification Development Bank</div> | |
| <div style="margin-top: 12px; font-style: italic; font-size: 13px; color: rgba(255,255,255,0.75);"> | |
| "Empowering certified technicians — تمكين الفنيين المعتمدين" | |
| </div> | |
| <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid rgba(255,255,255,0.15); font-size: 14px; color: rgba(255,255,255,0.9); font-weight: 500;"> | |
| مساعد المعرفة الداخلي — Internal Knowledge Assistant | |
| </div> | |
| </div> | |
| """, | |
| 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'<div style="text-align:center; color:#6B7280; font-size:12px; margin-top:8px;">' | |
| f'الدخول مقصور على إيميلات <b>@{settings.allowed_email_domain}</b></div>', | |
| unsafe_allow_html=True, | |
| ) | |
| if require_admin: | |
| st.markdown( | |
| '<div style="background:#FEF3C7; border-left:3px solid #F59E0B; padding:12px 16px; ' | |
| 'border-radius:8px; margin-top:1.5rem; font-size:13px;">' | |
| '🛡️ <b>صفحة المشرفين</b> — حسابك يجب أن يكون في قائمة المشرفين.</div>', | |
| unsafe_allow_html=True, | |
| ) | |
| # Feature highlights | |
| st.markdown('<div style="margin-top: 2.5rem;"></div>', 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'<div class="qdb-login-feature">' | |
| f'<div class="qdb-login-feature-icon">{icon}</div>' | |
| f'<div><div class="qdb-login-feature-title">{title}</div>' | |
| f'<div class="qdb-login-feature-desc">{desc}</div></div>' | |
| f'</div>', | |
| 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'<meta http-equiv="refresh" content="0; url={logout_url}">', 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() | |