Spaces:
Sleeping
Sleeping
File size: 2,273 Bytes
231ac24 |
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 |
# common.py
import extra_streamlit_components as stx
import streamlit as st
import logging
import os
from time import time
from requests_oauthlib import OAuth2Session
from streamlit import runtime
from streamlit.runtime.scriptrunner import get_script_run_ctx
import ipaddress
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("__name__")
logger.debug("調査用ログ")
# 接続元制御
ALLOW_IP_ADDRESS = os.environ["ALLOW_IP_ADDRESS"]
# Azure AD app registration details
CLIENT_ID = os.environ["CLIENT_ID"]
TENANT_ID = os.environ["TENANT_ID"]
# Azure API
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"
REDIRECT_PATH = os.environ["REDIRECT_PATH"]
AUTHORIZATION_URL = f"{AUTHORITY}/oauth2/v2.0/authorize"
SCOPES = ["openid", "profile", "User.Read"]
# 認証用URL取得
def authorization_request():
oauth = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_PATH, scope=SCOPES)
authorization_url, state = oauth.authorization_url(AUTHORIZATION_URL)
return authorization_url, state
# 接続元IP取得
def get_remote_ip():
ctx = get_script_run_ctx()
session_info = runtime.get_instance().get_client(ctx.session_id)
return session_info.request.remote_ip
# 接続元IP許可判定
def is_allow_ip_address():
remote_ip = get_remote_ip()
logger.info("remote_ip")
logger.info(remote_ip)
# localhost
if remote_ip == "::1":
return True
# プライベートIP
ipaddr = ipaddress.IPv4Address(remote_ip)
logger.info("ipaddr")
logger.info(ipaddr)
if ipaddr.is_private:
return True
# その他(許可リスト判定)
return remote_ip in ALLOW_IP_ADDRESS
#ログインの確認
def check_login():
# 接続元IP許可判定
if not is_allow_ip_address():
st.title("HTTP 403 Forbidden")
return
if "token" not in st.session_state or st.session_state["token"] is None or float(st.session_state["token_expires"]) <= time():
# 認証用リンク表示
authorization_url, st.session_state["authorization_state"] = authorization_request()
st.markdown(f'[Click here to log in]({authorization_url})', unsafe_allow_html=True)
st.stop()
|