[rewrite] Work on user registration, slightly polished schemas structure
This commit is contained in:
1 parent
5d12391635
commit
9e56eeca3f
12 files changed
+381
-39
No files matched your search
@@ -35,7 +35,7 @@ class EnvConfigField():
|
||||
regex: Optional[str] = None,
|
||||
parser: Optional[Callable[[str], Any]] = None,
|
||||
):
|
||||
self.value = None
|
||||
self.env_value = None
|
||||
self.env_name = env_name
|
||||
self.data_type = data_type
|
||||
self.default = default
|
||||
@@ -56,7 +56,7 @@ class EnvConfigField():
|
||||
env_name=self.env_name,
|
||||
)
|
||||
|
||||
self.value = self.validate(raw_value)
|
||||
self.env_value = self.validate(raw_value)
|
||||
|
||||
def validate(self, value: Any) -> Any:
|
||||
"""Validates the value based on provided constraints."""
|
||||
@@ -90,7 +90,7 @@ class EnvConfigField():
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
return self.value
|
||||
return self.env_value
|
||||
|
||||
@value.setter
|
||||
def value(self, new):
|
||||
@@ -155,7 +155,17 @@ class EnvConfigField():
|
||||
value=value)
|
||||
|
||||
|
||||
class EnvConfig():
|
||||
class EnvConfig:
|
||||
"""Singleton configuration loader for environment variables."""
|
||||
|
||||
_instance = None
|
||||
|
||||
def __new__(cls):
|
||||
"""Ensures only one instance of EnvConfig is created."""
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -172,13 +182,13 @@ class EnvConfig():
|
||||
|
||||
for field in self.fields.values():
|
||||
try:
|
||||
field.load
|
||||
field.load()
|
||||
except ConfigError as e:
|
||||
self.logger.error("Configuration error: %s", e)
|
||||
raise
|
||||
|
||||
def __getitem__(self, key: str):
|
||||
return self.fields["key"].value
|
||||
return self.fields[key].value
|
||||
|
||||
def __contains__(self, key: str) -> bool:
|
||||
return key in self.fields
|
||||
|
||||
@@ -12,20 +12,20 @@ class DatabaseManager():
|
||||
|
||||
_instance: 'DatabaseManager' = None
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
def __new__(cls, mysql_user: str, mysql_password: str, mysql_host: str, mysql_port: int, mysql_db_name: str):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
|
||||
def __init__(self, mysql_user: str, mysql_password: str, mysql_host: str, mysql_port: str, mysql_db_name: str) -> None:
|
||||
def __init__(self, mysql_user: str, mysql_password: str, mysql_host: str, mysql_port: int, mysql_db_name: str) -> None:
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.logger.info("Reading database config")
|
||||
self.engine = create_engine('mysql+mysqlconnector://%s:%s@%s:%s/%s' % (
|
||||
mysql_user,
|
||||
mysql_password,
|
||||
mysql_host,
|
||||
mysql_port,
|
||||
str(mysql_port),
|
||||
mysql_db_name),
|
||||
pool_pre_ping=True)
|
||||
self.test_connection()
|
||||
|
||||
@@ -3,6 +3,30 @@ from app.routes.cart_routes import router as cart_router
|
||||
from app.routes.user_routes import router as user_router
|
||||
from app.routes.shop_routes import router as shop_router
|
||||
|
||||
from app.core.config import EnvConfig, EnvConfigField
|
||||
|
||||
from app.database.manager import DatabaseManager
|
||||
|
||||
|
||||
config = EnvConfig()
|
||||
|
||||
config.add_field("mysql_user", EnvConfigField("MYSQL_USER", required=True))
|
||||
config.add_field("mysql_database", EnvConfigField("MYSQL_DATABASE", required=True))
|
||||
config.add_field("mysql_host", EnvConfigField("MYSQL_HOST", required=True))
|
||||
config.add_field("mysql_port", EnvConfigField("MYSQL_PORT", default=3306, data_type=int, required=False))
|
||||
config.add_field("mysql_password", EnvConfigField("MYSQL_PASSWORD", required=True))
|
||||
|
||||
config.load_config()
|
||||
|
||||
|
||||
DatabaseManager(
|
||||
mysql_user=config["mysql_user"],
|
||||
mysql_password=config["mysql_password"],
|
||||
mysql_host=config["mysql_host"],
|
||||
mysql_port=config["mysql_port"],
|
||||
mysql_db_name=config["mysql_database"],
|
||||
)
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="SWAG Shop",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from fastapi import APIRouter, Body
|
||||
|
||||
from app.schemas.user_register_schema import UserRegisterSchema
|
||||
from app.schemas.user_schemas import UserRegisterSchema, UserLoginSchema
|
||||
|
||||
from app.services.user_service import create_user
|
||||
|
||||
@@ -16,9 +16,20 @@ async def delete_user():
|
||||
|
||||
|
||||
@router.post("/login", summary="User login")
|
||||
async def login(data: dict = Body(...)):
|
||||
async def login(login_data: UserLoginSchema):
|
||||
raise NotImplementedError("login() needs to be implemented.")
|
||||
|
||||
# user = authenticate_user(form_data.username, form_data.password)
|
||||
# if not user:
|
||||
# raise HTTPException(
|
||||
# status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
# detail="Incorrect username or password",
|
||||
# headers={"WWW-Authenticate": "Bearer"},
|
||||
# )
|
||||
# access_token_expires = timedelta(minutes=30)
|
||||
# access_token = create_access_token(
|
||||
# data={"sub": user.username}, expires_delta=access_token_expires
|
||||
# )
|
||||
# return Token(access_token=access_token, token_type="bearer")
|
||||
|
||||
@router.delete("/logout", summary="User logout")
|
||||
async def logout():
|
||||
@@ -28,6 +39,7 @@ async def logout():
|
||||
@router.post("/register", summary="Register new user")
|
||||
async def register(user_data: UserRegisterSchema):
|
||||
create_user(user_data)
|
||||
return {"message": "User registered successfully"}
|
||||
|
||||
|
||||
@router.put("/update", summary="Update user details")
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
|
||||
|
||||
class UserRegisterSchema(BaseModel):
|
||||
username: str = Field(..., min_length=3, max_length=64)
|
||||
email: EmailStr = Field(...)
|
||||
phone_number: str = Field(..., min_length=10, max_length=15, pattern=r'^\+[0-9]{1,3} [0-9]{1,9}$')
|
||||
password: str = Field(..., min_length=6, max_length=128)
|
||||
shop_id: Optional[int] = None
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
@@ -0,0 +1,17 @@
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
|
||||
|
||||
class UserRegisterSchema(BaseModel):
|
||||
username: str = Field(..., min_length=3, max_length=64)
|
||||
email: EmailStr = Field(...)
|
||||
phone_number: str = Field(..., min_length=2, max_length=16, pattern=r'^\+[1-9]\d{1,14}$')
|
||||
password: str = Field(..., min_length=6, max_length=128)
|
||||
shop_id: int = 0
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
|
||||
class UserLoginSchema(BaseModel):
|
||||
shop_id: int = 0
|
||||
username: str = Field(..., min_length=3, max_length=64)
|
||||
password: str = Field(..., min_length=6, max_length=128)
|
||||
@@ -0,0 +1,73 @@
|
||||
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,15 +1,17 @@
|
||||
from app.database.manager import DatabaseManager
|
||||
from app.models.user_model import User
|
||||
|
||||
from app.schemas.user_register_schema import UserRegisterSchema
|
||||
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")
|
||||
with DatabaseManager.get_session() as session:
|
||||
user = User(
|
||||
username=user_data.username,
|
||||
password=user_data.password,
|
||||
password=get_password_hash(user_data.password),
|
||||
email=user_data.email,
|
||||
phone_number=user_data.phone_number,
|
||||
shop_id=user_data.shop_id
|
||||
|
||||
Reference in new issue
Block a user