# -*- 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 = """
"""
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(
"""
ระบบสร้างเอกสารจัดซื้อจัดจ้าง
PTT Auto Form
""",
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(
"⚠ ระบบเข้าสู่ระบบยังไม่ถูกตั้งค่า
"
"กรุณาติดต่อผู้ดูแลระบบ
",
unsafe_allow_html=True,
)
st.markdown("", 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"""
ระบบสร้างเอกสารจัดซื้อจัดจ้าง
PTT Auto Form
บัญชี {email or "(ไม่ทราบอีเมล)"}
ยังไม่ได้รับสิทธิ์ใช้งานระบบนี้
กรุณาติดต่อผู้ดูแลระบบเพื่อขอสิทธิ์
""",
unsafe_allow_html=True,
)
if st.button("ออกจากระบบ", type="secondary",
use_container_width=True, key="authz_logout_btn"):
st.logout()
st.markdown("", 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(
"""
""",
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"👤 {name}
",
unsafe_allow_html=True)
with c2:
if st.button("ออกจากระบบ", type="secondary",
use_container_width=True, key="auth_logout_btn"):
st.logout()