oidc-fastapi-test/src/oidc_test/settings.py

77 lines
1.9 KiB
Python
Raw Normal View History

from os import environ
2025-01-02 11:23:53 +01:00
import string
import random
from typing import Type, Tuple
from pathlib import Path
2025-01-02 11:23:53 +01:00
from pydantic import BaseModel, computed_field
from pydantic_settings import (
BaseSettings,
2025-01-10 19:18:57 +01:00
SettingsConfigDict,
2025-01-02 11:23:53 +01:00
PydanticBaseSettingsSource,
YamlConfigSettingsSource,
)
class OIDCProvider(BaseModel):
2025-01-10 00:09:12 +01:00
id: str
name: str
url: str
client_id: str
2025-01-02 11:23:53 +01:00
client_secret: str = ""
2025-01-10 23:40:24 +01:00
hint: str = "Use your own credentials"
2025-01-02 11:23:53 +01:00
@computed_field
@property
2025-01-09 23:41:32 +01:00
def openid_configuration(self) -> str:
2025-01-02 11:23:53 +01:00
return self.url + "/.well-known/openid-configuration"
@computed_field
@property
def token_url(self) -> str:
return "auth/" + self.name
class OIDCSettings(BaseModel):
show_session_details: bool = False
providers: list[OIDCProvider] = []
swagger_provider: str = ""
class Settings(BaseSettings):
"""Settings wil be read from an .env file"""
oidc: OIDCSettings = OIDCSettings()
secret_key: str = "".join(random.choice(string.ascii_letters) for _ in range(16))
2025-01-10 19:18:57 +01:00
model_config = SettingsConfigDict(env_nested_delimiter="__")
2025-01-02 11:23:53 +01:00
@classmethod
def settings_customise_sources(
cls,
settings_cls: Type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
file_secret_settings: PydanticBaseSettingsSource,
) -> Tuple[PydanticBaseSettingsSource, ...]:
return (
init_settings,
env_settings,
file_secret_settings,
YamlConfigSettingsSource(
settings_cls,
Path(
Path(
environ.get(
"OIDC_TEST_SETTINGS_FILE", Path.cwd() / "settings.yaml"
),
)
),
),
2025-01-02 11:23:53 +01:00
dotenv_settings,
)
settings = Settings()