
- Add user model with relationship to tasks - Implement JWT token authentication - Create user registration and login endpoints - Update task endpoints to filter by current user - Add Alembic migration for user table - Update documentation with authentication details
75 lines
2.5 KiB
Python
75 lines
2.5 KiB
Python
from typing import Any, Dict, Optional, Union
|
|
|
|
from sqlalchemy import or_
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.security import get_password_hash, verify_password
|
|
from app.crud.base import CRUDBase
|
|
from app.models.user import User
|
|
from app.schemas.user import UserCreate, UserUpdate
|
|
|
|
|
|
class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
|
|
def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
|
|
return db.query(User).filter(User.email == email).first()
|
|
|
|
def get_by_username(self, db: Session, *, username: str) -> Optional[User]:
|
|
return db.query(User).filter(User.username == username).first()
|
|
|
|
def get_by_email_or_username(
|
|
self, db: Session, *, email_or_username: str
|
|
) -> Optional[User]:
|
|
return (
|
|
db.query(User)
|
|
.filter(
|
|
or_(User.email == email_or_username, User.username == email_or_username)
|
|
)
|
|
.first()
|
|
)
|
|
|
|
def create(self, db: Session, *, obj_in: UserCreate) -> User:
|
|
db_obj = User(
|
|
email=obj_in.email,
|
|
username=obj_in.username,
|
|
hashed_password=get_password_hash(obj_in.password),
|
|
is_active=obj_in.is_active,
|
|
is_superuser=obj_in.is_superuser,
|
|
)
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
def update(
|
|
self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]
|
|
) -> User:
|
|
if isinstance(obj_in, dict):
|
|
update_data = obj_in
|
|
else:
|
|
update_data = obj_in.model_dump(exclude_unset=True)
|
|
if "password" in update_data and update_data["password"]:
|
|
hashed_password = get_password_hash(update_data["password"])
|
|
del update_data["password"]
|
|
update_data["hashed_password"] = hashed_password
|
|
return super().update(db, db_obj=db_obj, obj_in=update_data)
|
|
|
|
def authenticate(
|
|
self, db: Session, *, email_or_username: str, password: str
|
|
) -> Optional[User]:
|
|
user = self.get_by_email_or_username(db, email_or_username=email_or_username)
|
|
if not user:
|
|
return None
|
|
if not verify_password(password, user.hashed_password):
|
|
return None
|
|
return user
|
|
|
|
def is_active(self, user: User) -> bool:
|
|
return user.is_active
|
|
|
|
def is_superuser(self, user: User) -> bool:
|
|
return user.is_superuser
|
|
|
|
|
|
# Create instance for use throughout the app
|
|
user = CRUDUser(User)
|