Refactor crud module

This commit is contained in:
lvrossem
2023-03-31 07:13:13 -06:00
parent 49f8d7d713
commit 032a6ed543
6 changed files with 205 additions and 202 deletions

View File

@@ -0,0 +1,52 @@
from datetime import datetime, timedelta
import jwt
from fastapi import HTTPException
from sqlalchemy.orm import Session
from crud.users import get_user_by_username, pwd_context
from models import User
from schemas.users import UserCreate
DEFAULT_NR_HIGH_SCORES = 10
# JWT authentication setup
jwt_secret = "secret_key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 44640 # One month
def authenticate_user(db: Session, user: UserCreate):
"""Checks whether the provided credentials match with an existing User"""
db_user = get_user_by_username(db=db, username=user.username)
if not db_user:
return False
hashed_password = db_user.hashed_password
if not hashed_password or not pwd_context.verify(user.password, hashed_password):
return False
return db_user
def register(db: Session, username: str, password: str):
"""Register a new user"""
db_user = get_user_by_username(db, username)
if db_user:
raise HTTPException(status_code=400, detail="Username already registered")
db_user = User(username=username, hashed_password=pwd_context.hash(password))
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def login(db: Session, user: UserCreate):
user = authenticate_user(db, user)
if not user:
raise HTTPException(status_code=401, detail="Invalid username or password")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token_payload = {
"sub": user.username,
"exp": datetime.utcnow() + access_token_expires,
}
access_token = jwt.encode(access_token_payload, jwt_secret, algorithm=ALGORITHM)
return {"access_token": access_token}