File size: 12,089 Bytes
e6660cd
 
 
 
 
 
 
 
 
5ec0721
 
e6660cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e06d98
 
e6660cd
 
 
4e06d98
 
e6660cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e06d98
e6660cd
 
 
 
 
 
 
59262ca
e6660cd
f523c9f
 
 
e6660cd
 
 
4e06d98
ea6ec06
e6660cd
 
 
 
 
97656a9
 
 
4e06d98
97656a9
 
4e06d98
97656a9
 
 
e6660cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97656a9
 
 
 
 
 
 
 
e6660cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59262ca
f523c9f
e6660cd
 
 
 
 
 
 
 
 
 
 
97656a9
 
 
 
 
 
 
 
 
 
 
 
 
 
ea6ec06
e6660cd
 
 
 
5ec0721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6660cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e06d98
e6660cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# -*- coding: utf-8 -*-
"""Microsoft Entra ID sign-in gate using Streamlit's native OIDC auth.

Replaces the Flask `@login_required` / identity.web flow from the PTT-SIGN-IN
app. Reuses the same Azure App Registration, configured in
`.streamlit/secrets.toml` under the [auth] table. Requires Streamlit >= 1.42.
"""
from __future__ import annotations

import os

import streamlit as st


# Self-contained styling for the login "access pass". Inherits the app's fonts
# and page gradient; defines its own card so the screen reads as one intentional
# object rather than a button on a panel.
_LOGIN_CSS = """
<style>
    /* The keyed container IS the pass card */
    .st-key-login_card {
        width: 100% !important;
        max-width: 430px !important;
        margin: clamp(2rem, 9vh, 6rem) auto 0 !important;
        padding: 0 !important;
        gap: 0 !important;
        background: #FFFFFF !important;
        border: 1px solid rgba(214, 128, 72, 0.18) !important;
        border-radius: 26px !important;
        overflow: hidden !important;
        box-shadow:
            0 24px 60px rgba(214, 120, 60, 0.22),
            inset 0 1px 0 rgba(255, 255, 255, 0.6) !important;
        animation: loginRise 0.7s cubic-bezier(0.16, 1, 0.3, 1) both;
    }

    /* ── Header stub: gradient band + perforated tear-line + punched notches ── */
    .login-stub {
        position: relative;
        background: linear-gradient(120deg, #F26A3A 0%, #E85D27 100%);
        padding: 1.5rem 1.7rem 1.7rem;
        text-align: center;
        color: #fff;
    }
    .login-eyebrow {
        font-size: 0.62rem; font-weight: 700; letter-spacing: 0.18em;
        text-transform: uppercase; color: rgba(255, 255, 255, 0.82);
        margin-bottom: 0.5rem;
    }
    .login-wordmark {
        font-family: 'Inter', sans-serif;
        font-size: 1.7rem; font-weight: 800; letter-spacing: -0.01em;
        line-height: 1; color: #fff;
        text-shadow: 0 2px 10px rgba(0, 0, 0, 0.25);
    }
    .login-perf {
        position: absolute; left: 18px; right: 18px; bottom: -1px; height: 3px;
        background-image: repeating-linear-gradient(to right,
            rgba(255, 255, 255, 0.55) 0, rgba(255, 255, 255, 0.55) 9px,
            transparent 9px, transparent 18px);
    }
    /* Notches sit on the tear-line; the card's overflow:hidden clips their outer
       half → a clean semicircle bite on each edge. Coloured as the body top so
       they read as holes punched out of the stub. */
    .login-notch {
        position: absolute; bottom: -11px; width: 22px; height: 22px;
        border-radius: 50%; background: #FFFFFF;
    }
    .login-notch-l { left: -11px; }
    .login-notch-r { right: -11px; }

    /* ── Body ── */
    .login-body { padding: 1.8rem 1.7rem 1rem; text-align: center; }
    .login-lock {
        width: 78px; height: 78px; border-radius: 22px; margin: 0 auto 0.95rem;
        display: flex; align-items: center; justify-content: center;
        background: rgba(242, 106, 58, 0.12);
        border: 1px solid rgba(242, 106, 58, 0.22);
        box-shadow: none;
        animation: loginPop 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) 0.15s both;
    }
    .login-title {
        font-size: 1.55rem; font-weight: 800; color: #3E2A1E;
        margin: 0; letter-spacing: -0.01em;
    }

    /* ── CTA button: give it side gutters since the card has no padding ── */
    .st-key-login_card [data-testid="stButton"] { padding: 0.5rem 1.7rem 0.15rem; }

    /* Shown when no auth provider is configured (graceful instead of a crash) */
    .login-warn {
        margin: 0.2rem 1.7rem 0.2rem; padding: 0.75rem 0.9rem;
        background: rgba(232, 93, 39, 0.10);
        border: 1px solid rgba(232, 93, 39, 0.35);
        border-radius: 12px;
        color: #C25A1E; font-size: 0.82rem; font-weight: 600;
        text-align: center; line-height: 1.5;
    }

    @keyframes loginRise {
        from { opacity: 0; transform: translateY(22px) scale(0.985); }
        to   { opacity: 1; transform: none; }
    }
    @keyframes loginPop {
        0%   { transform: scale(0.4); opacity: 0; }
        60%  { transform: scale(1.15); opacity: 1; }
        100% { transform: scale(1); }
    }
    @media (prefers-reduced-motion: reduce) {
        .st-key-login_card, .login-lock { animation: none !important; }
    }
</style>
"""


def _is_logged_in() -> bool:
    try:
        return bool(st.user.is_logged_in)
    except Exception:
        # st.user raises if [auth] is missing/misconfigured in secrets.toml.
        return False


def _auth_configured() -> bool:
    """True if an [auth] provider is configured in secrets.toml."""
    try:
        return "auth" in st.secrets
    except Exception:
        return False


def require_login() -> None:
    """Block the app until the user signs in with their PTT (Entra) account.

    Call once, right after the page CSS is injected and before any app content.
    Renders a themed sign-in screen and st.stop()s when the user is not
    authenticated; returns normally once they are.
    """
    if _is_logged_in():
        return

    # ── Login screen ────────────────────────────────────────────────────────
    # Signature element: an "access pass" — a ticket card echoing the app's hero,
    # with a gradient stub, a perforated tear-line, and two punched notches. You
    # present a pass to enter the document system. Everything else stays quiet.
    st.markdown(_LOGIN_CSS, unsafe_allow_html=True)

    with st.container(key="login_card"):
        st.markdown(
            """
            <div class="login-stub">
                <div class="login-eyebrow">ระบบสร้างเอกสารจัดซื้อจัดจ้าง</div>
                <div class="login-wordmark">PTT Auto Form</div>
                <div class="login-perf"></div>
                <span class="login-notch login-notch-l"></span>
                <span class="login-notch login-notch-r"></span>
            </div>
            <div class="login-body">
                <div class="login-lock">
                    <svg width="36" height="36" viewBox="0 0 24 24" fill="none"
                         stroke="#F26A3A" stroke-width="2" stroke-linecap="round"
                         stroke-linejoin="round" aria-hidden="true">
                        <rect x="4" y="11" width="16" height="9" rx="2"></rect>
                        <path d="M8 11V8a4 4 0 0 1 8 0v3"></path>
                    </svg>
                </div>
                <div class="login-title">เข้าสู่ระบบ</div>
            </div>
            """,
            unsafe_allow_html=True,
        )

        if _auth_configured():
            if st.button(":material/login: เข้าสู่ระบบด้วย Microsoft",
                         type="primary", use_container_width=True):
                try:
                    st.login()
                except Exception:
                    st.error("ไม่สามารถเริ่มการเข้าสู่ระบบได้ "
                             "กรุณาลองใหม่หรือติดต่อผู้ดูแลระบบ")
        else:
            st.markdown(
                "<div class='login-warn'>⚠ ระบบเข้าสู่ระบบยังไม่ถูกตั้งค่า<br>"
                "กรุณาติดต่อผู้ดูแลระบบ</div>",
                unsafe_allow_html=True,
            )
        st.markdown("<div style='height:1.2rem'></div>", unsafe_allow_html=True)

    st.stop()


def _allowed_users() -> set[str]:
    """Emails allowed to use the app, from the ALLOWED_USERS Space secret
    (comma-separated, case-insensitive). Empty/unset → everyone who can sign in."""
    raw = os.environ.get("ALLOWED_USERS", "")
    return {e.strip().lower() for e in raw.split(",") if e.strip()}


def require_authorized() -> None:
    """Server-side authorization check — call right after require_login().

    Signing in proves WHO the user is (any account in the tenant); this gate
    decides whether that user MAY use the app. Enforced in the Streamlit
    script (the backend), not by hiding UI: an unauthorized user is stopped
    here no matter what they request. No-op while ALLOWED_USERS is unset, so
    the app never locks itself out before the secret exists."""
    allowed = _allowed_users()
    if not allowed:
        return
    try:
        email = (getattr(st.user, "email", "") or "").strip().lower()
    except Exception:                            # st.user unavailable → treat as unknown
        email = ""
    if email in allowed:
        return

    st.markdown(_LOGIN_CSS, unsafe_allow_html=True)
    with st.container(key="login_card"):
        st.markdown(
            f"""
            <div class="login-stub">
                <div class="login-eyebrow">ระบบสร้างเอกสารจัดซื้อจัดจ้าง</div>
                <div class="login-wordmark">PTT Auto Form</div>
                <div class="login-perf"></div>
                <span class="login-notch login-notch-l"></span>
                <span class="login-notch login-notch-r"></span>
            </div>
            <div class="login-body">
                <div class="login-lock">
                    <svg width="36" height="36" viewBox="0 0 24 24" fill="none"
                         stroke="#F26A3A" stroke-width="2" stroke-linecap="round"
                         stroke-linejoin="round" aria-hidden="true">
                        <rect x="4" y="11" width="16" height="9" rx="2"></rect>
                        <path d="M8 11V8a4 4 0 0 1 8 0v3"></path>
                        <line x1="4" y1="4" x2="20" y2="20"></line>
                    </svg>
                </div>
                <div class="login-title">ไม่มีสิทธิ์ใช้งาน</div>
            </div>
            <div class="login-warn">บัญชี <b>{email or "(ไม่ทราบอีเมล)"}</b>
            ยังไม่ได้รับสิทธิ์ใช้งานระบบนี้<br>กรุณาติดต่อผู้ดูแลระบบเพื่อขอสิทธิ์</div>
            """,
            unsafe_allow_html=True,
        )
        if st.button("ออกจากระบบ", type="secondary",
                     use_container_width=True, key="authz_logout_btn"):
            st.logout()
        st.markdown("<div style='height:1.2rem'></div>", unsafe_allow_html=True)
    st.stop()


def render_topbar() -> None:
    """Show the signed-in user + a logout button, stripped of the card chrome
    that the app's CSS applies to top-level columns."""
    st.markdown(
        """
        <style>
        /* Strip the panel styling from this one row's columns */
        .st-key-auth_topbar [data-testid="stColumn"] {
            background: transparent !important;
            border: none !important;
            box-shadow: none !important;
            padding: 0 !important;
        }
        .auth-userchip {
            display: inline-flex; align-items: center; gap: 0.45rem;
            color: #6E5848; font-size: 0.9rem; font-weight: 600;
        }
        </style>
        """,
        unsafe_allow_html=True,
    )
    with st.container(key="auth_topbar"):
        c1, c2 = st.columns([7, 2], vertical_alignment="center")
        with c1:
            name = (getattr(st.user, "name", None)
                    or getattr(st.user, "email", "")
                    or "ผู้ใช้งาน")
            st.markdown(f"<div class='auth-userchip'>👤 {name}</div>",
                        unsafe_allow_html=True)
        with c2:
            if st.button("ออกจากระบบ", type="secondary",
                         use_container_width=True, key="auth_logout_btn"):
                st.logout()