Refactor crud module
This commit is contained in:
31
src/crud/users.py
Normal file
31
src/crud/users.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from fastapi import HTTPException
|
||||
from passlib.context import CryptContext
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models import User
|
||||
from schemas.users import UserCreate
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
|
||||
def patch_user(db: Session, username: str, user: UserCreate):
|
||||
"""Changes the username and/or the password of a User"""
|
||||
db_user = get_user_by_username(db, username)
|
||||
potential_duplicate = get_user_by_username(db, user.username)
|
||||
if potential_duplicate:
|
||||
if potential_duplicate.user_id != db_user.user_id:
|
||||
raise HTTPException(status_code=400, detail="Username already registered")
|
||||
|
||||
db_user.username = user.username
|
||||
db_user.hashed_password = pwd_context.hash(user.password)
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_user_by_username(db: Session, username: str):
|
||||
"""Fetches a User from the database by their username"""
|
||||
return db.query(User).filter(User.username == username).first()
|
||||
|
||||
|
||||
def get_users(db: Session):
|
||||
"""Fetch a list of all users"""
|
||||
return db.query(User).all()
|
||||
Reference in New Issue
Block a user