File size: 11,785 Bytes
e6660cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97656a9
 
 
 
 
 
 
 
 
 
3c3b156
 
 
 
 
 
 
e6660cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97656a9
 
 
 
 
 
 
 
e6660cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97656a9
 
 
 
 
 
 
 
3c3b156
 
 
 
 
 
 
 
 
 
97656a9
 
 
 
 
 
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
# -*- 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 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: linear-gradient(180deg, #161412 0%, #100D0B 100%) !important;
        border: 1px solid rgba(255, 255, 255, 0.10) !important;
        border-radius: 26px !important;
        overflow: hidden !important;
        box-shadow:
            0 24px 60px rgba(0, 0, 0, 0.45),
            inset 0 1px 0 rgba(255, 255, 255, 0.05) !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: #141110;
    }
    .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: 58px; height: 58px; border-radius: 17px; margin: 0 auto 0.95rem;
        display: flex; align-items: center; justify-content: center;
        background: linear-gradient(135deg, #F26A3A 0%, #E8915E 100%);
        border: 2px solid rgba(255, 255, 255, 0.10);
        box-shadow: 0 8px 20px rgba(242, 106, 58, 0.40);
        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: #F5F3F1;
        margin: 0 0 0.4rem; letter-spacing: -0.01em;
    }
    .login-sub {
        font-size: 0.92rem; line-height: 1.6; margin: 0;
        color: #9A8F86 !important;
    }

    /* ── 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; }

    /* ── Footer security lockup ── */
    .login-foot {
        display: flex; flex-direction: column; align-items: center; gap: 0.3rem;
        padding: 0.7rem 1.4rem 1.6rem; text-align: center;
    }
    .login-foot-ms {
        display: inline-flex; align-items: center; gap: 0.42rem;
        font-size: 0.74rem; font-weight: 600;
        color: #A89C92 !important;
    }
    .login-foot-note { font-size: 0.68rem; color: #7C726A !important; }

    /* 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.12);
        border: 1px solid rgba(232, 93, 39, 0.35);
        border-radius: 12px;
        color: #F0B79A; font-size: 0.82rem; font-weight: 600;
        text-align: center; line-height: 1.5;
    }

    /* Escape hatch for the embedded (iframe) case */
    .login-altlink {
        margin: 0.5rem 1.7rem 0; text-align: center;
        font-size: 0.72rem; color: #928981;
    }
    .login-altlink a { color: #F2B391 !important; text-decoration: underline; }

    @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="26" height="26" viewBox="0 0 24 24" fill="none"
                         stroke="#fff" 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>
                <p class="login-sub">
                    ลงชื่อเข้าใช้ด้วยบัญชี PTT<br>
                    เพื่อสร้างและดาวน์โหลดเอกสาร
                </p>
            </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("ไม่สามารถเริ่มการเข้าสู่ระบบได้ "
                             "กรุณาลองใหม่หรือติดต่อผู้ดูแลระบบ")
            # When opened embedded (the HF Space page runs the app in an iframe),
            # st.login()'s redirect is blocked by Microsoft's frame-busting and
            # "nothing happens". This escape hatch reopens the app top-level in a
            # new tab (href="/" is host-agnostic) where sign-in works.
            st.markdown(
                "<div class='login-altlink'>ปุ่มไม่ทำงาน? "
                "<a href='/' target='_blank' rel='noopener'>เปิดแบบเต็มหน้าจอ</a>"
                " แล้วลองอีกครั้ง</div>",
                unsafe_allow_html=True,
            )
        else:
            st.markdown(
                "<div class='login-warn'>⚠ ระบบเข้าสู่ระบบยังไม่ถูกตั้งค่า<br>"
                "กรุณาติดต่อผู้ดูแลระบบ</div>",
                unsafe_allow_html=True,
            )

        st.markdown(
            """
            <div class="login-foot">
                <div class="login-foot-ms">
                    <svg width="15" height="15" viewBox="0 0 23 23" aria-hidden="true">
                        <rect width="10" height="10" x="1"  y="1"  fill="#F25022"></rect>
                        <rect width="10" height="10" x="12" y="1"  fill="#7FBA00"></rect>
                        <rect width="10" height="10" x="1"  y="12" fill="#00A4EF"></rect>
                        <rect width="10" height="10" x="12" y="12" fill="#FFB900"></rect>
                    </svg>
                    <span>ปลอดภัยด้วย Microsoft Entra ID</span>
                </div>
                <div class="login-foot-note">เฉพาะบัญชีองค์กรที่ได้รับอนุญาต</div>
            </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: #CBC4BD; 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()