[rewrite] Added a security module from a fastapi example

This commit is contained in:
Thastertyn committed 2025-02-24 22:32:49 +01:00
1 parent 9e56eeca3f
commit c7e20fc935
9 files changed
+143 -250

No files matched your search

+8 -3
View File
@@ -155,22 +155,27 @@ class EnvConfigField():
value=value)
class EnvConfig:
"""Singleton configuration loader for environment variables."""
class EnvConfig():
_instance = None
_initialized = False
def __new__(cls):
"""Ensures only one instance of EnvConfig is created."""
print("Called __new__")
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
if EnvConfig._initialized:
return
self.logger = logging.getLogger(__name__)
self.fields = {}
EnvConfig._initialized = True
def add_field(self, name: str, field: EnvConfigField):
if name in self.fields:
return
+30
View File
@@ -0,0 +1,30 @@
from datetime import datetime, timedelta, timezone
from typing import Any
import jwt
from passlib.context import CryptContext
from app.core.config import EnvConfig
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
ALGORITHM = "HS256"
def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
config = EnvConfig()
expire = datetime.now(timezone.utc) + expires_delta
to_encode = {"exp": expire, "sub": str(subject)}
encoded_jwt = jwt.encode(to_encode, config["secret_key"], algorithm=ALGORITHM)
return encoded_jwt
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
+3
View File
@@ -19,6 +19,9 @@ config.add_field("mysql_password", EnvConfigField("MYSQL_PASSWORD", required=Tru
config.load_config()
config2 = EnvConfig()
DatabaseManager(
mysql_user=config["mysql_user"],
mysql_password=config["mysql_password"],
-73
View File
@@ -1,73 +0,0 @@
from datetime import datetime, timedelta, timezone
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jwt.exceptions import JWTException
from passlib.context import CryptContext
from app.models.user_model import User
from app.database.manager import DatabaseManager
# Security settings
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# Password hashing setup
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# OAuth2 for token-based authentication
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_password_hash(password: str) -> str:
"""Hashes a password using bcrypt."""
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verifies that a given password matches the stored hashed password."""
return pwd_context.verify(plain_password, hashed_password)
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
"""Generates a JWT token."""
to_encode = data.copy()
expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=15))
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def get_user_by_username(username: str) -> User | None:
"""Retrieves a user from the database by username."""
with DatabaseManager.get_session() as session:
return session.query(User).filter(User.username == username).first()
def authenticate_user(username: str, password: str) -> User | bool:
"""Authenticates a user by verifying their credentials."""
user = get_user_by_username(username)
if not user or not verify_password(password, user.password):
return False
return user
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
"""Retrieves the current authenticated user based on the token."""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTException:
raise credentials_exception
user = get_user_by_username(username)
if user is None:
raise credentials_exception
return user
+1 -1
View File
@@ -3,11 +3,11 @@ from app.models.user_model import User
from app.schemas.user_schemas import UserRegisterSchema
from app.services.auth_service import get_password_hash
def create_user(user_data: UserRegisterSchema):
print("Creating user")
return
with DatabaseManager.get_session() as session:
user = User(
username=user_data.username,