kiwi-vpn/api/kiwi_vpn_api/config.py

73 lines
1.6 KiB
Python
Raw Normal View History

2022-03-16 00:23:57 +00:00
from enum import Enum
2022-03-18 18:22:17 +00:00
import json
2022-03-16 00:23:57 +00:00
from jose.constants import ALGORITHMS
from passlib.context import CryptContext
2022-03-18 18:22:17 +00:00
from pydantic import BaseModel, Field
2022-03-18 18:22:17 +00:00
from sqlalchemy.engine import Engine
from sqlalchemy import create_engine
2022-03-16 00:23:57 +00:00
2022-03-18 18:22:17 +00:00
CONFIG_FILE = "tmp/config.json"
2022-03-17 22:47:31 +00:00
2022-03-16 00:23:57 +00:00
class DBType(Enum):
sqlite = "sqlite"
mysql = "mysql"
class DBConfig(BaseModel):
db_type: DBType = DBType.sqlite
2022-03-16 00:23:57 +00:00
2022-03-18 18:22:17 +00:00
@property
def db_engine(self) -> Engine:
return create_engine(
"sqlite:///./tmp/vpn.db",
connect_args={"check_same_thread": False},
)
2022-03-16 00:23:57 +00:00
class JWTConfig(BaseModel):
2022-03-17 23:00:49 +00:00
secret: str | None = None
2022-03-16 00:23:57 +00:00
hash_algorithm: str = ALGORITHMS.HS256
expiry_minutes: int = 30
class CryptoConfig(BaseModel):
schemes: list[str] = ["bcrypt"]
2022-03-18 17:36:44 +00:00
@property
def crypt_context(self) -> CryptContext:
return CryptContext(
2022-03-18 18:22:17 +00:00
schemes=self.schemes,
2022-03-18 17:36:44 +00:00
deprecated="auto",
)
2022-03-18 18:22:17 +00:00
class BaseConfig(BaseModel):
db: DBConfig = Field(default_factory=DBConfig)
jwt: JWTConfig = Field(default_factory=JWTConfig)
crypto: CryptoConfig = Field(default_factory=CryptoConfig)
2022-03-18 17:36:44 +00:00
@property
2022-03-18 18:22:17 +00:00
def crypt_context(self) -> CryptContext:
return self.crypto.crypt_context
2022-03-17 22:47:31 +00:00
2022-03-18 18:22:17 +00:00
@property
def db_engine(self) -> Engine:
return self.db.db_engine
2022-03-17 22:47:31 +00:00
2022-03-18 18:22:17 +00:00
async def get() -> BaseConfig | None:
2022-03-17 22:47:31 +00:00
try:
2022-03-18 18:22:17 +00:00
with open(CONFIG_FILE, "r") as config_file:
return BaseConfig.parse_obj(json.load(config_file))
2022-03-17 22:47:31 +00:00
except FileNotFoundError:
2022-03-18 18:22:17 +00:00
return None
2022-03-17 22:47:31 +00:00
2022-03-18 18:22:17 +00:00
def set(config: BaseConfig) -> None:
with open(CONFIG_FILE, "w") as config_file:
config_file.write(config.json(indent=2))