File size: 7,806 Bytes
02c0be9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fa7d18
 
 
02c0be9
 
2ec983f
 
 
 
 
 
 
02c0be9
1fa7d18
02c0be9
 
 
e5f7025
1fa7d18
e5f7025
1fa7d18
e5f7025
7b490a0
 
454fde3
 
 
7b490a0
 
 
1fa7d18
 
 
 
 
02c0be9
 
 
 
 
1fa7d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02c0be9
1fa7d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02c0be9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
"""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"""
        <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()