
- Add username field to User model - Update authentication endpoints to use username instead of email - Create migration for adding username column to user table - Update user services to handle username validation and uniqueness - Maintain email for compatibility, but make username the primary identifier
68 lines
1.8 KiB
Python
68 lines
1.8 KiB
Python
import uuid
|
|
from typing import Optional
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.security import get_password_hash, verify_password
|
|
from app.models.user import User
|
|
from app.schemas.user import UserCreate, UserUpdate
|
|
|
|
|
|
def get_by_id(db: Session, user_id: str) -> Optional[User]:
|
|
return db.query(User).filter(User.id == user_id).first()
|
|
|
|
|
|
def get_by_email(db: Session, email: str) -> Optional[User]:
|
|
return db.query(User).filter(User.email == email).first()
|
|
|
|
|
|
def get_by_username(db: Session, username: str) -> Optional[User]:
|
|
return db.query(User).filter(User.username == username).first()
|
|
|
|
|
|
def create(db: Session, *, obj_in: UserCreate) -> User:
|
|
db_obj = User(
|
|
id=str(uuid.uuid4()),
|
|
username=obj_in.username,
|
|
email=obj_in.email,
|
|
hashed_password=get_password_hash(obj_in.password),
|
|
full_name=obj_in.full_name,
|
|
is_superuser=obj_in.is_superuser,
|
|
)
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def update(db: Session, *, db_obj: User, obj_in: UserUpdate) -> User:
|
|
update_data = obj_in.dict(exclude_unset=True)
|
|
if update_data.get("password"):
|
|
hashed_password = get_password_hash(update_data["password"])
|
|
del update_data["password"]
|
|
update_data["hashed_password"] = hashed_password
|
|
|
|
for field, value in update_data.items():
|
|
setattr(db_obj, field, value)
|
|
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def authenticate(db: Session, *, username: str, password: str) -> Optional[User]:
|
|
user = get_by_username(db, username=username)
|
|
if not user:
|
|
return None
|
|
if not verify_password(password, user.hashed_password):
|
|
return None
|
|
return user
|
|
|
|
|
|
def is_active(user: User) -> bool:
|
|
return user.is_active
|
|
|
|
|
|
def is_superuser(user: User) -> bool:
|
|
return user.is_superuser |