SFM/app/auth/service.py
2026-06-04 14:13:30 +03:00

51 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
from typing import Any
import jwt
import streamlit as st
from app.config import get_location, get_setting
from .providers import build_auth_provider
def clear_session() -> None:
for key in list(st.session_state.keys()):
del st.session_state[key]
class AuthService:
def run(self) -> bool:
if "user_profile" in st.session_state:
return True
token_data = build_auth_provider().get_token_data()
if not token_data:
return False
id_token = token_data.get("id_token")
if not id_token:
st.error("Не удалось получить id_token из ответа авторизации.")
return False
profile = self._decode_id_token(id_token)
st.session_state["token_data"] = token_data
st.session_state["user_profile"] = profile
return True
def _decode_id_token(self, id_token: str) -> dict[str, Any]:
if get_location() == "local":
return st.session_state.get("local_mock_profile", {"email": "local@local"})
jwks_client = jwt.PyJWKClient(get_setting("KEYCLOAK_JWKS_URL"))
signing_key = jwks_client.get_signing_key_from_jwt(id_token)
return jwt.decode(
id_token,
signing_key.key,
algorithms=[get_setting("KEYCLOAK_JWT_ALGORITHM")],
audience=get_setting("KEYCLOAK_CLIENT_ID"),
options={"verify_exp": True},
)