[rewrite] WIP login and register

This commit is contained in:
Thastertyn 2025-03-11 21:53:37 +01:00
parent f5547be799
commit cd8fdb9c21
9 changed files with 38 additions and 62 deletions

View File

@ -1,12 +1,11 @@
from fastapi import APIRouter
from app.api.routes import cart_routes, shop_routes, user_routes, utils_routes
from app.api.routes.shop import shop_login_routes, shop_user_routes
from app.api.routes import cart_routes, user_routes, utils_routes, shop
api_router = APIRouter()
api_router.include_router(cart_routes.router)
api_router.include_router(shop_routes.router)
api_router.include_router(user_routes.router)
api_router.include_router(utils_routes.router)
api_router.include_router(shop.shop_router)

View File

@ -1,8 +1,14 @@
from typing import Annotated
from fastapi import APIRouter
from app.api.routes.shop import shop_login_routes, shop_user_routes
api_router = APIRouter()
shop_router = APIRouter(
prefix="/shop/{shop_uuid}",
tags=["Shop"]
)
api_router.include_router(shop_login_routes.router)
api_router.include_router(shop_user_routes.router)
shop_router.include_router(shop_login_routes.router)
shop_router.include_router(shop_user_routes.router)

View File

@ -3,7 +3,7 @@ from typing import Annotated
from fastapi import APIRouter, Body, Path
from app.schemas.user_schemas import UserRegisterSchema, UserLoginSchema
from app.schemas.user_schemas import UserRegister
router = APIRouter(
@ -17,18 +17,13 @@ async def delete_user(shop_uuid=Annotated[uuid.UUID, Path(title="UUID of the sho
raise NotImplementedError("delete_user() needs to be implemented.")
@router.post("/login", summary="User login")
async def login(login_data: UserLoginSchema, shop_uuid=Annotated[uuid.UUID, Path(title="UUID of the shop")]):
raise NotImplementedError("login() needs to be implemented.")
@router.delete("/logout", summary="User logout")
async def logout():
raise NotImplementedError("logout() needs to be implemented.")
@router.post("/register", summary="Register new user")
async def register(user_data: UserRegisterSchema):
async def register(user_data: UserRegister):
raise NotImplementedError()

View File

@ -1,14 +0,0 @@
import uuid
from typing import Annotated
from fastapi import APIRouter, Path
router = APIRouter(
prefix="/shop/{shop_uuid}",
tags=["Shop"]
)
@router.get("/login")
async def get_shop_info(shop_uuid=Annotated[uuid.UUID, Path(title="UUID of the shop")]):
raise NotImplementedError

View File

@ -1,7 +1,9 @@
from fastapi import APIRouter, Body
from app.schemas.user_schemas import UserRegisterSchema, UserLoginSchema
from app.schemas.user_schemas import UserRegister
from app.api.dependencies import SessionDep
from app.crud import user_crud
router = APIRouter(
prefix="/user",
@ -14,35 +16,18 @@ async def delete_user():
raise NotImplementedError("delete_user() needs to be implemented.")
@router.post("/login", summary="User login")
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():
raise NotImplementedError("logout() needs to be implemented.")
@router.post("/register", summary="Register new user")
async def register(user_data: UserRegisterSchema):
async def register(session: SessionDep, user_data: UserRegister):
try:
create_user(user_data)
user_crud.create_user(session, user_data)
return {"message": "User registered successfully"}
except BaseException:
return {"message": "An error occured"}
return {"message": "An error occurred"}
@router.put("/update", summary="Update user details")

View File

@ -1,8 +1,10 @@
import uuid
from typing import Optional
from sqlmodel import Session, select
from app.database.models.user_model import User
from app.core.security import verify_password
from app.schemas.user_schemas import UserRegister
from app.core.security import verify_password, get_password_hash
from app.utils.models import generate_user_uuid5
def get_user_by_generated_uuid(session: Session, email: str, shop_id: Optional[int]) -> Optional[User]:
@ -11,8 +13,19 @@ def get_user_by_generated_uuid(session: Session, email: str, shop_id: Optional[i
db_user = session.exec(stmt).one_or_none()
return db_user
def create_user(session: Session):
raise NotImplementedError()
def create_user(session: Session, user_register: UserRegister, shop_id: Optional[int], user_role: str):
user_uuid = generate_user_uuid5(user_register.email, shop_id)
password = get_password_hash(user_register.password)
new_user = User(
uuid=user_uuid,
shop_id=shop_id,
email=user_register.email,
username=user_register.username,
phone_number=user_register.phone_number
)
session.add(new_user)
session.commit()
def authenticate(session: Session, email: str, password: str, shop_id: Optional[int]) -> Optional[User]:
db_user = get_user_by_generated_uuid(session, email, shop_id)

View File

@ -1,5 +1,4 @@
import logging
from contextlib import contextmanager
from typing import Generator
from sqlalchemy.exc import DatabaseError as SqlAlchemyError

View File

@ -1,3 +1,4 @@
from uuid import UUID
from enum import Enum as PyEnum
from typing import Optional, List
from datetime import datetime, time
@ -38,6 +39,7 @@ class Shop(SQLModel, table=True):
__tablename__ = 'shop'
id: Optional[int] = Field(default=None, primary_key=True)
uuid: UUID = Field(nullable=False, unique=True)
owner_id: int = Field(foreign_key='user.id', nullable=False)
name: str = Field(max_length=100, nullable=False, unique=True)
description: str = Field(max_length=500, nullable=False)

View File

@ -2,22 +2,13 @@ from sqlmodel import Field as SqlModelField, SQLModel
from pydantic import EmailStr, Field
class UserRegisterSchema(SQLModel):
class UserRegister(SQLModel):
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:
from_attributes = True
class UserLoginSchema(SQLModel):
shop_id: int = 0
username: str = Field(..., min_length=3, max_length=64)
password: str = Field(..., min_length=6, max_length=128)
class Token(SQLModel):
access_token: str