switch to the SQLModel ORM

This commit is contained in:
maxDorninger
2025-03-02 21:14:07 +01:00
parent b890b9e8dc
commit b88cb1b042
8 changed files with 126 additions and 241 deletions

View File

@@ -1,12 +1,15 @@
from typing import Annotated
import hashlib
import bcrypt
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlmodel import Session, select
import database
from auth import create_access_token, Token, router
from database import users
from database import users, SessionDependency
from database.users import UserInternal
@@ -17,21 +20,18 @@ def verify_password(plain_password, hashed_password):
)
def get_password_hash(password):
return bcrypt.hashpw(
bytes(password, encoding="utf-8"),
bcrypt.gensalt(),
)
def get_password_hash(password: str) -> str:
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def authenticate_user(email: str, password: str) -> bool | UserInternal:
def authenticate_user(db: SessionDependency, email: str, password: str) -> bool | UserInternal:
"""
:param email: email of the user
:param password: password of the user
:return: if authentication succeeds, returns the user object with added name and lastname, otherwise or if the user doesn't exist returns False
"""
user = database.users.get_user(email=email)
user: UserInternal | None = db.exec(select(UserInternal).where(UserInternal.email == email)).first()
if not user:
return False
if not verify_password(password, user.hashed_password):
@@ -42,13 +42,15 @@ def authenticate_user(email: str, password: str) -> bool | UserInternal:
@router.post("/token")
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
db: SessionDependency,
) -> Token:
user = authenticate_user(form_data.username, form_data.password)
user = authenticate_user(db,form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = create_access_token(data={"sub": user.id})
# id needs to be converted because a UUID object isn't json serializable
access_token = create_access_token(data={"sub": user.id.__str__()})
return Token(access_token=access_token, token_type="bearer")