Skip to content

Commit

Permalink
Restructure Config Loader
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnGrubba committed Jul 26, 2024
1 parent e757a5b commit 80239a0
Show file tree
Hide file tree
Showing 18 changed files with 151 additions and 102 deletions.
2 changes: 1 addition & 1 deletion src/api/oauth_providers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from fastapi import APIRouter
from tools.conf import SignupConfig
from tools import SignupConfig

router = APIRouter(
prefix="/oauth",
Expand Down
2 changes: 1 addition & 1 deletion src/api/oauth_providers/github.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from fastapi import APIRouter, Request, BackgroundTasks, Response, HTTPException
from fastapi.responses import RedirectResponse
from tools.conf import SignupConfig, SessionConfig
from tools import SignupConfig, SessionConfig
import json
import requests
import re
Expand Down
2 changes: 1 addition & 1 deletion src/api/profile.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, Response
from tools.conf import AccountFeaturesConfig, SignupConfig
from tools import AccountFeaturesConfig, SignupConfig
from api.model import ResetPasswordRequest, ConfirmEmailRequest, DeleteAccountRequest
import json
import bcrypt
Expand Down
2 changes: 1 addition & 1 deletion src/crud/sessions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import uuid
from tools import sessions_collection, users_collection
import datetime
from tools.conf import SessionConfig
from tools import SessionConfig
from fastapi import Request
from user_agents import parse
from bson import ObjectId, errors
Expand Down
11 changes: 1 addition & 10 deletions src/tools/__init__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
from .db import users_collection, sessions_collection, bson_to_json, r
from .conf import (
SignupConfig,
EmailConfig,
SessionConfig,
InternalConfig,
AccountFeaturesConfig,
insecure_cols,
SecurityConfig,
default_signup_fields,
)
from .conf import *
from .mail import send_email, broadcast_emails
from .confirmation_codes import all_ids, regenerate_ids

Expand Down
86 changes: 0 additions & 86 deletions src/tools/conf.py

This file was deleted.

20 changes: 20 additions & 0 deletions src/tools/conf/AccountFeaturesConfig.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from .conf import config, not_updateable_cols_internal


class AccountFeaturesConfig:
enable_reset_pswd: bool = config["account_features"]["enable_reset_pswd"]
reset_pswd_conf_mail: bool = config["account_features"]["reset_pswd_conf_mail"]
enable_2fa: bool = config["account_features"]["2fa"]["enable"]
issuer_name_2fa: str = config["account_features"]["2fa"]["issuer_name"]
issuer_image_url_2fa: str = config["account_features"]["2fa"]["issuer_image_url"]
qr_code_endpoint_2fa: bool = config["account_features"]["2fa"]["qr_endpoint"]
allow_add_fields_on_signup: set[str] = set(
config["account_features"]["allow_add_fields_on_signup"]
) - set(not_updateable_cols_internal)
allow_add_fields_patch_user: set[str] = set(
config["account_features"]["allow_add_fields_patch_user"]
) - set(not_updateable_cols_internal)
allow_deletion: bool = config["account_features"]["allow_deletion"]
deletion_pending_minutes: int = config["account_features"][
"deletion_pending_minutes"
]
9 changes: 9 additions & 0 deletions src/tools/conf/EmailConfig.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from .conf import config


class EmailConfig:
login_usr: str = config["email"]["login_usr"]
login_pwd: str = config["email"]["login_pwd"]
sender_email: str = config["email"]["sender_email"]
smtp_host: str = config["email"]["smtp_host"]
smtp_port: int = config["email"]["smtp_port"]
16 changes: 16 additions & 0 deletions src/tools/conf/InternalConfig.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from .conf import config, insecure_cols, not_updateable_cols_internal
from collections import ChainMap


class InternalConfig:
internal_api_key: str = config["internal"]["internal_api_key"]
internal_columns: dict = dict(
ChainMap(*[{col: 0} for col in config["internal"]["internal_columns"]])
)
internal_columns.update(insecure_cols)
# Insecure Cols + Internal Cols can't be updated by the user
not_updateable_columns: list = (
config["internal"]["not_updateable_columns"]
+ list(internal_columns.keys())
+ not_updateable_cols_internal
)
9 changes: 9 additions & 0 deletions src/tools/conf/SecurityConfig.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from .conf import config


class SecurityConfig:
access_control_origins: set[str] = set(config["security"]["allow_origins"])
allow_headers: set[str] = set(config["security"]["allow_headers"])
max_login_attempts: int = config["security"]["max_login_attempts"]
login_timeout: int = config["security"]["login_timeout"]
expire_unfinished_timeout: int = config["security"]["expire_unfinished_timeout"]
10 changes: 10 additions & 0 deletions src/tools/conf/SessionConfig.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from .conf import config


class SessionConfig:
session_expiry_seconds: int = config["session"]["session_expiry_seconds"]
max_session_count: int = config["session"]["max_session_count"]
auto_cookie: bool = config["session"]["auto_cookie"]
auto_cookie_name: str = config["session"]["auto_cookie_name"]
cookie_samesite: str = config["session"]["cookie_samesite"]
cookie_secure: bool = config["session"]["cookie_secure"]
34 changes: 34 additions & 0 deletions src/tools/conf/SignupConfig.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from .conf import config


class SignupConfig:
enable_conf_email: bool = config["signup"]["enable_conf_email"]
conf_code_expiry: int = config["signup"]["conf_code_expiry"]
conf_code_complexity: int = config["signup"]["conf_code_complexity"]
enable_welcome_email: bool = config["signup"]["enable_welcome_email"]
oauth_providers: list[str] = config["signup"]["oauth"]["providers_enabled"]
oauth_base_url: str = str(config["signup"]["oauth"]["base_url"]).removesuffix("/")

def validate(self) -> bool:
"""This is to Type Check the Configuration
Raises:
ValueError: _description_
ValueError: _description_
Returns:
bool: _description_
"""
if type(self.enable_conf_email) != bool:
raise ValueError(
"signup.enable_conf_email must be a boolean (got type {})".format(
type(self.enable_conf_email)
)
)
if type(self.conf_code_expiry) != int:
raise ValueError(
"signup.conf_code_expiry must be an integer (got type {})".format(
type(self.conf_code_expiry)
)
)
pass
18 changes: 18 additions & 0 deletions src/tools/conf/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from .SignupConfig import SignupConfig
from .EmailConfig import EmailConfig
from .AccountFeaturesConfig import AccountFeaturesConfig
from .InternalConfig import InternalConfig
from .SecurityConfig import SecurityConfig
from .SessionConfig import SessionConfig
from .conf import insecure_cols, default_signup_fields

__all__ = [
"SignupConfig",
"EmailConfig",
"AccountFeaturesConfig",
"InternalConfig",
"SecurityConfig",
"SessionConfig",
"insecure_cols",
"default_signup_fields",
]
18 changes: 18 additions & 0 deletions src/tools/conf/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import json
import sys
import os

__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))

if "pytest" in sys.modules:
# Running Tests (Load Testing Config)
config = json.load(open(os.path.join(__location__, "testing_config.json"), "rb"))
else:
# Normal Startup
config = json.load(open("/src/app/config/config.json", "rb"))

# Columns that should never leave EZAuth (maybe get more in the future)
default_signup_fields = {"username", "email", "password"}
insecure_cols = {"password": 0, "2fa_secret": 0, "google_uid": 0, "github_uid": 0}
not_updateable_cols_internal = ["email", "createdAt", "expireAt"]
# Columns that can leave EZAuth but should only be used internally can be defined in config
File renamed without changes.
2 changes: 1 addition & 1 deletion src/tools/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os
import bson.json_util
import json
from tools.conf import SessionConfig
from .conf import SessionConfig
import redis
import logging
import sys
Expand Down
2 changes: 1 addition & 1 deletion src/tools/mail.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from . import EmailConfig
from .conf import EmailConfig
import logging
from threading import Lock
from tools import users_collection, InternalConfig
Expand Down
10 changes: 10 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Sos:
saus: bool

def validate(self):
if type(self.saus) != bool:
raise ValueError("Sausage must be a boolean")


Sos.saus = True
Sos().validate()

0 comments on commit 80239a0

Please sign in to comment.