[rewrite] Added a security module from a fastapi example
This commit is contained in:
1 parent
9e56eeca3f
commit
c7e20fc935
9 files changed
+143
-250
No files matched your search
@@ -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
|
||||
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user